xref: /openbsd-src/gnu/usr.bin/perl/t/class/construct.t (revision 5486feefcc8cb79b19e014ab332cc5dfd05b3b33)
1f2a19305Safresh1#!./perl
2f2a19305Safresh1
3f2a19305Safresh1BEGIN {
4f2a19305Safresh1    chdir 't' if -d 't';
5f2a19305Safresh1    require './test.pl';
6f2a19305Safresh1    set_up_inc('../lib');
7f2a19305Safresh1    require Config;
8f2a19305Safresh1}
9f2a19305Safresh1
10f2a19305Safresh1use v5.36;
11f2a19305Safresh1use feature 'class';
12f2a19305Safresh1no warnings qw( experimental::class experimental::builtin );
13f2a19305Safresh1
14f2a19305Safresh1use builtin qw( blessed reftype );
15f2a19305Safresh1
16f2a19305Safresh1{
17*5486feefSafresh1    class Testcase1 {
18f2a19305Safresh1        field $x :param;
19f2a19305Safresh1        method x { return $x; }
20f2a19305Safresh1    }
21f2a19305Safresh1
22*5486feefSafresh1    my $obj = Testcase1->new(x => 123);
23f2a19305Safresh1    is($obj->x, 123, 'Value of $x set by constructor');
24f2a19305Safresh1
25f2a19305Safresh1    # The following tests aren't really related to construction, just the
26f2a19305Safresh1    # general nature of object instance refs. If this test file gets too long
27f2a19305Safresh1    # they could be moved to their own file.
28*5486feefSafresh1    is(ref $obj, "Testcase1", 'ref of $obj');
29*5486feefSafresh1    is(blessed $obj, "Testcase1", 'blessed of $obj');
30f2a19305Safresh1    is(reftype $obj, "OBJECT", 'reftype of $obj');
31f2a19305Safresh1
32f2a19305Safresh1    # num/stringification of object without overload
33f2a19305Safresh1    is($obj+0, builtin::refaddr($obj), 'numified object');
34*5486feefSafresh1    like("$obj", qr/^Testcase1=OBJECT\(0x[[:xdigit:]]+\)$/, 'stringified object' );
35f2a19305Safresh1
36*5486feefSafresh1    ok(!eval { Testcase1->new(x => 123, y => 456); 1 }, 'Unrecognised parameter fails');
37*5486feefSafresh1    like($@, qr/^Unrecognised parameters for "Testcase1" constructor: y at /,
38f2a19305Safresh1        'Exception thrown by constructor for unrecogniser parameter');
39f2a19305Safresh1}
40f2a19305Safresh1
41f2a19305Safresh1{
42*5486feefSafresh1    class Testcase2 {
43f2a19305Safresh1        use overload
44f2a19305Safresh1            '0+' => sub { return 12345 },
45*5486feefSafresh1            '""' => sub { "<Testcase2 instance>" },
46f2a19305Safresh1            fallback => 1;
47f2a19305Safresh1    }
48f2a19305Safresh1
49*5486feefSafresh1    my $obj = Testcase2->new;
50f2a19305Safresh1    is($obj+0, 12345, 'numified object with overload');
51*5486feefSafresh1    is("$obj", "<Testcase2 instance>", 'stringified object with overload' );
52f2a19305Safresh1}
53f2a19305Safresh1
54f2a19305Safresh1done_testing;
55