/**
  * Helper method
  *
  * @param   string name
  * @param   string parent
  * @param   string[] interfaces
  * @return  lang.XPClass class
  * @throws  unittest.AssertionFailedError
  */
 protected function defineClass($name, $parent, $interfaces, $bytes)
 {
     if (class_exists(xp::reflect($name), FALSE)) {
         $this->fail('Class "' . $name . '" may not exist!');
     }
     return ClassLoader::defineClass($name, $parent, $interfaces, $bytes);
 }
 public static function defineExiterClass()
 {
     self::$exiterClass = ClassLoader::defineClass('net.xp_framework.unittest.core.Exiter', 'lang.Object', array(), '{
     public function __construct() { throw new SystemExit(0); }
     public static function doExit() { new self(); }
   }');
 }
    static function __static()
    {
        // For singletonInstance test
        ClassLoader::defineClass('net.xp_framework.unittest.core.AnonymousSingleton', 'lang.Object', array(), '{
        protected static $instance= NULL;

        static function getInstance() {
          if (!isset(self::$instance)) self::$instance= new AnonymousSingleton();
          return self::$instance;
        }
      }');
        // For returnNewObject and returnNewObjectViaReflection tests
        ClassLoader::defineClass('net.xp_framework.unittest.core.AnonymousList', 'lang.Object', array(), '{
        function __construct() {
          ReferencesTest::registry("list", $this);
        }
      }');
        ClassLoader::defineClass('net.xp_framework.unittest.core.AnonymousFactory', 'lang.Object', array(), '{
        static function factory() {
          return new AnonymousList();
        }
      }');
        ClassLoader::defineClass('net.xp_framework.unittest.core.AnonymousNewInstanceFactory', 'lang.Object', array(), '{
        static function factory() {
          return XPClass::forName("net.xp_framework.unittest.core.AnonymousList")->newInstance();
        }
      }');
    }
 static function __static()
 {
     ClassLoader::defineClass('net.xp_framework.unittest.core.TypeHintedClass', 'lang.Object', array(), '{
     public static function passObject(Generic $o) { return $o; }
     public static function passNullable(Generic $o= NULL) { return $o; }
   }');
 }
    public static function dummyConnectionClass()
    {
        self::$conn = ClassLoader::defineClass('RestClientExecutionTest_Connection', 'peer.http.HttpConnection', array(), '{
        protected $result= NULL;
        protected $exception= NULL;

        public function __construct($status, $body, $headers) {
          parent::__construct("http://test");
          if ($status instanceof Throwable) {
            $this->exception= $status;
          } else {
            $this->result= "HTTP/1.1 ".$status."\\r\\n";
            foreach ($headers as $name => $value) {
              $this->result.= $name.": ".$value."\\r\\n";
            }
            $this->result.= "\\r\\n".$body;
          }
        }
        
        public function send(HttpRequest $request) {
          if ($this->exception) {
            throw $this->exception;
          } else {
            return new HttpResponse(new MemoryInputStream($this->result));
          }
        }
      }');
    }
 /**
  * Constructor
  *
  * @param   string bytes method sourcecode
  */
 public function __construct($bytes)
 {
     $name = 'xp.unittest.DynamicallyGeneratedTestCase·' . self::$uniqId++;
     $this->testClass = ClassLoader::defineClass($name, 'unittest.TestCase', array(), '{
     #[@test] 
     public function run() { ' . $bytes . ' }
   }');
 }
 static function __static()
 {
     self::$fileStreamAdapter = ClassLoader::defineClass('FileStreamAdapter', 'io.File', array(), '{
     protected $stream= NULL;
     public function __construct($stream) { $this->stream= $stream; }
     public function exists() { return NULL !== $this->stream; }
     public function getURI() { return Streams::readableUri($this->stream); }
     public function getInputStream() { return $this->stream; }
   }');
 }
    public function map_of_string_to_object()
    {
        ClassLoader::defineClass('GenericsBCTest_Map', 'lang.Object', array(), '{
        public $__generic;

        public function getClassName() {
          return "Map<".$this->__generic[0].", ".$this->__generic[1].">";
        }
      }');
        $this->assertEquals('Map<String, Object>', create('new GenericsBCTest_Map<String, Object>')->getClassName());
    }
    public static function registerTransport()
    {
        HttpTransport::register('test', ClassLoader::defineClass('TestHttpTransport', 'peer.http.HttpTransport', array(), '{
        public $host, $port, $arg;

        public function __construct(URL $url, $arg) {
          $this->host= $url->getHost();
          $this->port= $url->getPort(80);
          $this->arg= $arg;
        }
        
        public function send(HttpRequest $request, $timeout= 60, $connecttimeout= 2.0) {
          // Not implemented
        }
      }'));
    }
    public static function defineMockSocket()
    {
        self::$mockSocket = ClassLoader::defineClass('net.xp_framework.unittest.remote.MockSocket', 'lang.Object', array(), '{
        public function __construct($bytes) {
          $this->bytes= $bytes;
          $this->offset= 0;
        }

        public function readBinary($size= 8192) {
          if ($this->offset > strlen($this->bytes)) return FALSE;
          $chunk= substr($this->bytes, $this->offset, $size);
          $this->offset+= strlen($chunk);
          return $chunk;
        }
      }');
    }
 public static function requestEchoingConnectionClass()
 {
     self::$conn = ClassLoader::defineClass('RestClientSendTest_Connection', 'peer.http.HttpConnection', array(), '{
     public function __construct() {
       parent::__construct("http://test");
     }
     
     public function send(HttpRequest $request) {
       $str= $request->getRequestString();
       return new HttpResponse(new MemoryInputStream(sprintf(
         "HTTP/1.0 200 OK\\r\\nContent-Type: text/plain\\r\\nContent-Length: %d\\r\\n\\r\\n%s",
         strlen($str),
         $str
       )));
     }
   }');
 }
 static function __static()
 {
     $self = new XPClass(__CLASS__);
     foreach (hash_algos() as $algo) {
         MessageDigest::register($algo, $self);
     }
     // Overwrite crc32b implementation if a buggy implementation is detected.
     // Workaround for http://bugs.php.net/bug.php?id=45028
     if ('0a1cb779' === hash('crc32b', 'AAAAAAAA')) {
         MessageDigest::register('crc32b', ClassLoader::defineClass(__CLASS__ . '·CRC32bDigestImpl', $self->getName(), array(), '{
       public function doFinal() {
         $n= hexdec(hash_final($this->handle));
         return sprintf("%08x", (($n & 0xFF) << 24) + (($n & 0xFF00) << 8) + (($n & 0xFF0000) >> 8) + (($n >> 24) & 0xFF));
       }
     }'));
     }
 }
    public static function mockSocket()
    {
        self::$sock = ClassLoader::defineClass('net.xp_framework.unittest.rdbms.tds.MockTdsSocket', 'peer.Socket', array(), '{
        public $bytes;
        protected $offset= 0;
        
        public function __construct($bytes= "") {
          $this->bytes= $bytes;
        }

        public function write($bytes) {
          $this->bytes.= $bytes;
        }
        
        public function readBinary($l) {
          $chunk= substr($this->bytes, $this->offset, $l);
          $this->offset+= $l;
          return $chunk;
        }
      }');
    }
 public function static_member_excluded()
 {
     $class = ClassLoader::defineClass('RestConversionTest_StaticMemberExcluded', 'lang.Object', array(), '{
     public $name;
     public static $instance= NULL;
   }');
     $this->assertNull($this->fixture->convert($class, array('name' => 'Test', 'instance' => 'Value'))->getClass()->getField('instance')->get(NULL));
 }
Example #15
0
    public static function defineScriptlets()
    {
        self::$errorScriptlet = ClassLoader::defineClass('ErrorScriptlet', 'scriptlet.HttpScriptlet', array('util.log.Traceable'), '{
        protected function _request() {
          $req= parent::_request();
          $req->method= "GET";
          $req->env["SERVER_PROTOCOL"]= "HTTP/1.1";
          $req->env["REQUEST_URI"]= "/error";
          $req->env["HTTP_HOST"]= "localhost";
          return $req;
        }
        
        public function setTrace($cat) {
          $cat->debug("Injected", $cat->getClassName());
        }
        
        protected function _setupRequest($request) {
          // Intentionally empty
        }
        
        public function doGet($request, $response) {
          throw new IllegalAccessException("No shoes, no shorts, no service");
        }
      }');
        self::$welcomeScriptlet = ClassLoader::defineClass('WelcomeScriptlet', 'scriptlet.HttpScriptlet', array(), '{
        protected function _request() {
          $req= parent::_request();
          $req->method= "GET";
          $req->env["SERVER_PROTOCOL"]= "HTTP/1.1";
          $req->env["REQUEST_URI"]= "/welcome";
          $req->env["HTTP_HOST"]= "localhost";
          return $req;
        }
        
        protected function _setupRequest($request) {
          // Intentionally empty
        }
        
        public function doGet($request, $response) {
          $response->write("<h1>Welcome, we are open</h1>");
        }
      }');
        self::$xmlScriptlet = ClassLoader::defineClass('XmlScriptletImpl', 'scriptlet.xml.XMLScriptlet', array(), '{
        protected function _request() {
          $req= parent::_request();
          $req->method= "GET";
          $req->env["SERVER_PROTOCOL"]= "HTTP/1.1";
          $req->env["REQUEST_URI"]= "/welcome";
          $req->env["HTTP_HOST"]= "localhost";
          return $req;
        }

        protected function _response() {
          $res= parent::_response();
          $stylesheet= create(new Stylesheet())
            ->withEncoding("iso-8859-1")
            ->withOutputMethod("xml")
            ->withTemplate(create(new XslTemplate())->matching("/")
              ->withChild(create(new Node("h1"))
                ->withChild(new Node("xsl:value-of", NULL, array("select" => "/formresult/result")))
              )
            )
          ;
          $res->setStylesheet($stylesheet, XSLT_TREE);
          return $res;
        }
        
        protected function _setupRequest($request) {
          // Intentionally empty
        }
        
        public function doGet($request, $response) {
          $response->addFormresult(new Node("result", "Welcome, we are open"));
        }
      }');
        self::$debugScriptlet = ClassLoader::defineClass('DebugScriptlet', 'scriptlet.HttpScriptlet', array(), '{
        protected $title, $date;

        public function __construct($title, $date) {
          $this->title= $title;
          $this->date= $date;
        }
        
        protected function _request() {
          $req= parent::_request();
          $req->method= "GET";
          $req->env["SERVER_PROTOCOL"]= "HTTP/1.1";
          $req->env["REQUEST_URI"]= "/debug";
          $req->env["HTTP_HOST"]= "localhost";
          return $req;
        }
        
        protected function _setupRequest($request) {
          // Intentionally empty
        }
        
        public function doGet($request, $response) {
          $response->write("<h1>".$this->title." @ ".$this->date."</h1>");

          $response->write("<ul>");
          $response->write("  <li>ENV.DOMAIN = ".$request->getEnvValue("DOMAIN")."</li>");
          $response->write("  <li>ENV.ADMINS = ".$request->getEnvValue("ADMINS")."</li>");
          $response->write("</ul>");

          $config= PropertyManager::getInstance()->getProperties("debug")->getFileName();
          $response->write("<h2>".strtr($config, DIRECTORY_SEPARATOR, "/")."</h2>");
        }
      }');
        self::$exitScriptlet = ClassLoader::defineClass('ExitScriptlet', 'scriptlet.HttpScriptlet', array(), '{
        protected function _request() {
          $req= parent::_request();
          $req->method= "GET";
          $req->env["SERVER_PROTOCOL"]= "HTTP/1.1";
          $req->env["REQUEST_URI"]= "/exit";
          $req->env["HTTP_HOST"]= "localhost";
          $req->setParams($_REQUEST);
          return $req;
        }
        
        protected function _setupRequest($request) {
          // Intentionally empty
        }
        
        public function doGet($request, $response) {
          Runtime::halt($request->getParam("code"), $request->getParam("message"));
        }
      }');
    }
 public function indenting()
 {
     $cl = ClassLoader::defineClass('net.xp_framework.unittest.core.StringOfTest_IndentingFixture', 'lang.Object', array(), '{
     protected $inner= NULL;
     public function __construct($inner) {
       $this->inner= $inner;
     }
     public function toString() {
       return "object {\\n  ".xp::stringOf($this->inner, "  ")."\\n}";
     }
   }');
     $this->assertEquals("object {\n  object {\n    null\n  }\n}", $cl->newInstance($cl->newInstance(NULL))->toString());
 }
 public function implementedConstructorInvocation()
 {
     $i = ClassLoader::defineClass('ANonAbstractClass', 'net.xp_framework.unittest.reflection.AbstractTestClass', array(), '{
     public function getDate() {}
   }');
     $this->assertSubclass($i->getConstructor()->newInstance(), 'net.xp_framework.unittest.reflection.AbstractTestClass');
 }
 public function missingStaticParentPassMethodInvocation()
 {
     $b = ClassLoader::defineClass('MissingMethodsTest_StaticPassBaseFixture', 'lang.Object', array(), '{
     public static function run() {
       parent::run();
     }
   }');
     $c = ClassLoader::defineClass('MissingMethodsTest_StaticPassChildFixture', $b->getName(), array(), '{
     public static function run() {
       parent::run();
     }
   }');
     call_user_func(array($c->literal(), 'run'));
 }
 public function process_extended()
 {
     $extended = ClassLoader::defineClass('net.xp_framework.unittest.webservices.rest.srv.fixture.GreetingHandlerExtended', $this->fixtureClass('GreetingHandler')->getName(), array(), '{}');
     $route = array('handler' => $extended, 'target' => $extended->getMethod('greet_class'), 'params' => array(), 'segments' => array(0 => '/greet/class'), 'input' => NULL, 'output' => 'text/json');
     $this->assertProcess(200, array('Content-Type: text/json'), '"Hello ' . $extended->getName() . '"', $route, $this->newRequest());
 }
Example #20
0
 /**
  * Returns the enumeration members for a given class
  *
  * @param  lang.XPClass class class object
  * @return self[]
  * @throws lang.IllegalArgumentException in case the given class is not an enum
  */
 public static function valuesOf(XPClass $class)
 {
     if (!$class->isEnum()) {
         throw new IllegalArgumentException('Argument class must be lang.XPClass<? extends lang.Enum>');
     }
     $r = [];
     if ($class->isSubclassOf(self::class)) {
         foreach ($class->reflect()->getStaticProperties() as $prop) {
             $class->isInstance($prop) && ($r[] = $prop);
         }
     } else {
         $t = ClassLoader::defineClass($class->getName() . 'Enum', self::class, []);
         foreach ($class->reflect()->getMethod('getValues')->invoke(null) as $name => $ordinal) {
             $r[] = $t->newInstance($ordinal, $name);
         }
     }
     return $r;
 }
 public function searchImplementation()
 {
     // Should not be found
     $this->register('tests', XPClass::forName('net.xp_framework.unittest.rdbms.mock.MockConnection'));
     // Should choose the "a" implementation
     $this->register('test+a', ClassLoader::defineClass('net.xp_framework.unittest.rdbms.mock.AMockConnection', 'net.xp_framework.unittest.rdbms.mock.MockConnection', array(), '{}'));
     $this->register('test+b', ClassLoader::defineClass('net.xp_framework.unittest.rdbms.mock.BMockConnection', 'net.xp_framework.unittest.rdbms.mock.MockConnection', array(), '{}'));
     $this->assertInstanceOf('net.xp_framework.unittest.rdbms.mock.AMockConnection', DriverManager::getConnection('test://localhost'));
 }
Example #22
0
 public function implementedConstructorInvocation()
 {
     $i = ClassLoader::defineClass('ANonAbstractClass', AbstractTestClass::class, [], '{
   public function getDate() {}
 }');
     $this->assertInstanceOf(AbstractTestClass::class, $i->getConstructor()->newInstance());
 }
 public function defined_class_exists()
 {
     ClassLoader::defineClass('net.xp_framework.unittest.core.NamespaceAliasClassFixture', 'lang.Object', array(), '{}');
     $this->assertTrue(class_exists('net\\xp_framework\\unittest\\core\\NamespaceAliasClassFixture', FALSE));
 }
Example #24
0
 public function interfaces()
 {
     ClassLoader::defineClass('net.xp_framework.unittest.core.DestructionCallbackImpl', 'lang.Object', array('net.xp_framework.unittest.core.DestructionCallback'), '{
       public function onDestruction($object) { 
         // ... Implementation here
       }
     }');
     ClassLoader::defineClass('net.xp_framework.unittest.core.DestructionCallbackImplEx', 'net.xp_framework.unittest.core.DestructionCallbackImpl', NULL, '{}');
     $this->assertTrue(is('net.xp_framework.unittest.core.DestructionCallback', new DestructionCallbackImpl()));
     $this->assertTrue(is('net.xp_framework.unittest.core.DestructionCallback', new DestructionCallbackImplEx()));
     $this->assertFalse(is('net.xp_framework.unittest.core.DestructionCallback', new Object()));
 }
 public function bestMapping()
 {
     $fooClass = ClassLoader::defineClass('net.xp_framework.unittest.remote.FooClass', 'lang.Object', NULL);
     $barClass = ClassLoader::defineClass('net.xp_framework.unittest.remote.BarClass', 'FooClass', NULL);
     $bazClass = ClassLoader::defineClass('net.xp_framework.unittest.remote.BazClass', 'BarClass', NULL);
     $bazookaClass = ClassLoader::defineClass('net.xp_framework.unittest.remote.BazookaClass', 'BazClass', NULL);
     // Both must be serialized with the FOO mapping, because both are Foo or Foo-derived objects.
     $this->serializer->mapping('FOO', newinstance('remote.protocol.SerializerMapping', array(), '{
     function handledClass() { return XPClass::forName("net.xp_framework.unittest.remote.FooClass"); }
     function representationOf($serializer, $value, $context= array()) { return "FOO:"; }
     public function valueOf($serializer, $serialized, $context= array()) { return NULL; }
   }'));
     $this->assertEquals('FOO:', $this->serializer->representationOf(new FooClass()));
     $this->assertEquals('FOO:', $this->serializer->representationOf(new BarClass()));
     $this->assertEquals('FOO:', $this->serializer->representationOf(new BazClass()));
     // Add more concrete mapping for BAR. Foo must still be serialized with FOO, but the BarClass-object
     // has a better matching mapping.
     $this->serializer->mapping('BAR', newinstance('remote.protocol.SerializerMapping', array(), '{
     function handledClass() { return XPClass::forName("net.xp_framework.unittest.remote.BarClass"); }
     function representationOf($serializer, $value, $context= array()) { return "BAR:"; }
     function valueOf($serializer, $serialized, $context= array()) { return NULL; }
   }'));
     $this->assertEquals('FOO:', $this->serializer->representationOf(new FooClass()));
     $this->assertEquals('BAR:', $this->serializer->representationOf(new BarClass()));
     $this->assertEquals('BAR:', $this->serializer->representationOf(new BazClass()));
     $this->assertEquals('BAR:', $this->serializer->representationOf(new BazookaClass()));
 }
 public function equals_same_object_payloads()
 {
     $class = ClassLoader::defineClass('ResponseTest_SameObjectFixture', 'lang.Object', array(), '{
     public function equals($cmp) { return TRUE; }
   }');
     $this->assertEquals(Response::status(200)->withPayload($class->newInstance()), Response::status(200)->withPayload($class->newInstance()));
 }