Ejemplo n.º 1
0
 public function get_contents_read_returns_less_than_size()
 {
     $f = new File(Streams::readableFd(newinstance(MemoryInputStream::class, ['Test'], ['read' => function ($size = 4096) {
         return parent::read(min(1, $size));
     }])));
     $this->assertEquals('Test', FileUtil::getContents($f));
 }
Ejemplo n.º 2
0
 public function calls_equals_method_in_maps($value, $outcome)
 {
     $object = newinstance('lang.Object', [], ['equals' => function ($cmp) {
         return 'Test' === $cmp;
     }]);
     $this->assertEquals($outcome, (new IsEqual(['key' => $object]))->matches($value));
 }
Ejemplo n.º 3
0
 static function __static()
 {
     self::$UNKNOWN = newinstance(__CLASS__, [0.0, 0.0, []], '{
   static function __static() { }
   public function toString() { return "com.maxmind.geoip.Location(UNKNOWN)"; }
 }');
 }
Ejemplo n.º 4
0
 /**
  * Sets up test case and backups Console::$err stream.
  *
  */
 public function setUp()
 {
     $this->cat = (new LogCategory('default'))->withAppender((new ConsoleAppender())->withLayout(newinstance(Layout::class, [], ['format' => function (LoggingEvent $event) {
         return implode(' ', $event->getArguments());
     }])));
     $this->stream = Console::$err->getStream();
 }
 /**
  * Compile and then run sourcecode
  *
  * @param   string source
  * @return  lang.Runnable
  */
 protected function compile($source)
 {
     $decl = '
 import integrationtests.ArrayExtensions;
 
 class FixturePrimitiveExtensionMethodsIntegrationTest·%d implements Runnable {
   public var run() {
     %s
   }
 }';
     $emitter = new V54Emitter();
     $task = new CompilationTask(new StringSource(sprintf($decl, $this->counter++, $source), self::$syntax, $this->name), new NullDiagnosticListener(), newinstance(FileManager::class, [$this->getClass()->getClassLoader()], '{
     protected $cl;
     
     public function __construct($cl) {
       $this->cl= $cl;
     }
     
     public function findClass($qualified) {
       return new FileSource($this->cl->getResourceAsStream("net/xp_lang/tests/integration/src/".strtr($qualified, ".", "/").".xp"));
     }
     
     public function write($r, File $target) {
       // DEBUG $r->writeTo(Console::$out->getStream());
       $r->executeWith(array());   // Defines the class
     }
   }'), $emitter);
     $type = $task->run();
     return XPClass::forName($type->name())->newInstance();
 }
Ejemplo n.º 6
0
 public function noTimeout()
 {
     $r = $this->suite->runTest(newinstance(TestCase::class, ['fixture'], ['#[@test, @limit(time= 0.010)] fixture' => function () {
         /* No timeout */
     }]));
     $this->assertEquals(1, $r->successCount());
 }
Ejemplo n.º 7
0
    /**
     * Setup record handlers
     *
     * @see     http://infocenter.sybase.com/help/topic/com.sybase.dc35823_1500/html/uconfig/uconfig111.htm
     * @see     http://infocenter.sybase.com/help/topic/com.sybase.dc38421_1500/html/ntconfig/ntconfig80.htm
     * @return  [:rdbms.tds.TdsRecord] handlers
     */
    protected function setupRecords()
    {
        $records[self::T_NUMERIC] = newinstance('rdbms.tds.TdsRecord', array(), '{
        public function unmarshal($stream, $field) {
          if (-1 === ($len= $stream->getByte()- 1)) return NULL;
          $pos= $stream->getByte();
          $bytes= $stream->read($len);
          if ($i= ($len % 4)) {
            $bytes= str_repeat("\\0", 4 - $i).$bytes;
            $len+= 4 - $i;
          }
          for ($n= 0, $m= $pos ? -1 : 1, $i= $len- 4; $i >= 0; $i-= 4, $m= bcmul($m, "4294967296", 0)) {
            $n= bcadd($n, bcmul(sprintf("%u", current(unpack("N", substr($bytes, $i, 4)))), $m, 0), 0);
          }
          return $this->toNumber($n, $field["scale"], $field["prec"]);
        }
      }');
        $records[self::T_DECIMAL] = $records[self::T_NUMERIC];
        $records[self::T_BINARY] = newinstance('rdbms.tds.TdsRecord', array(), '{
        public function unmarshal($stream, $field) {
          if (0 === ($len= $stream->getByte())) return NULL;
          $string= $stream->read($len);
          return iconv($field["conv"], "iso-8859-1", substr($string, 0, strcspn($string, "\\0")));
        }
      }');
        $records[self::T_IMAGE] = newinstance('rdbms.tds.TdsRecord', array(), '{
        public function unmarshal($stream, $field) {
          $has= $stream->getByte();
          if ($has !== 16) return NULL; // Seems to always be 16 - obsolete?

          $stream->read(24);  // Skip 16 Byte TEXTPTR, 8 Byte TIMESTAMP
          $len= $stream->getLong();
          if (0 === $len) return NULL;

          $r= $stream->read($len);

          // HACK - cannot figure out why UNITEXT is not being returned as such
          // but as IMAGE type with different inside layout!
          return iconv(
            strlen($r) > 1 && "\\0" === $r{1} ? "ucs-2le" : $field["conv"],
            "iso-8859-1",
            $r
          );
        }
      }');
        $records[self::T_VARBINARY] = newinstance('rdbms.tds.TdsRecord', array(), '{
        public function unmarshal($stream, $field) {
          if (0 === ($len= $stream->getByte())) return NULL;

          return iconv($field["conv"], "iso-8859-1", $stream->read($len));
        }
      }');
        $records[self::T_LONGBINARY] = newinstance('rdbms.tds.TdsRecord', array(), '{
        public function unmarshal($stream, $field) {
          $len= $stream->getLong();
          return $stream->getString($len / 2);
        }
      }');
        return $records;
    }
Ejemplo n.º 8
0
 protected function newConnection(URL $url)
 {
     return newinstance(Connection::class, [$url], ['response' => '', 'sent' => null, 'in' => null, 'out' => null, '__construct' => function ($url) {
         parent::__construct($url);
         $this->_connect($url);
         // FIXME: Required for unittest
     }, '_connect' => function (URL $url) {
         $this->in = new StringReader(new MemoryInputStream($this->response));
         $this->out = new StringWriter(new MemoryOutputStream());
     }, '_disconnect' => function () {
         $this->sent = $this->out->getStream()->getBytes();
         $this->in = null;
         $this->out = null;
     }, 'setResponseBytes' => function ($s) {
         $this->in = new StringReader(new MemoryInputStream($s));
         $this->response = $s;
     }, 'readSentBytes' => function () {
         // Case of DISCONNECT
         if (null !== $this->sent) {
             $sent = $this->sent;
             $this->sent = null;
             return $sent;
         }
         return $this->out->getStream()->getBytes();
     }, 'clearSentBytes' => function () {
         $this->_connect(new URL());
         $this->sent = null;
     }]);
 }
 /** @return lang.Object */
 protected function hashCodeCounter()
 {
     return newinstance(Object::class, [], ['invoked' => 0, 'hashCode' => function () {
         $this->invoked++;
         return parent::hashCode();
     }]);
 }
Ejemplo n.º 10
0
 /**
  * Returns a testcase with getName() as test method
  *
  * @return  unittest.TestCase
  */
 protected function getNameCase()
 {
     return newinstance('unittest.TestCase', ['getName'], '{
   #[@test]
   public function getName($compound= FALSE) { }
 }');
 }
Ejemplo n.º 11
0
 static function __static()
 {
     self::$EQUALS = newinstance(__CLASS__, array(1, 'EQUALS', '='), '{
     static function __static() {}
   }');
     self::$NOT_EQUALS = newinstance(__CLASS__, array(1, 'NOT_EQUALS', '!='), '{
     static function __static() {}
   }');
     self::$GREATER_THAN = newinstance(__CLASS__, array(1, 'GREATER_THAN', '>'), '{
     static function __static() {}
   }');
     self::$GREATER_EQUALS = newinstance(__CLASS__, array(1, 'GREATER_EQUALS', '>='), '{
     static function __static() {}
   }');
     self::$LESS_THAN = newinstance(__CLASS__, array(1, 'LESS_THAN', '<'), '{
     static function __static() {}
   }');
     self::$LESS_EQUALS = newinstance(__CLASS__, array(1, 'LESS_EQUALS', '<='), '{
     static function __static() {}
   }');
     self::$IN = newinstance(__CLASS__, array(1, 'IN', 'in'), '{
     static function __static() {}
     function forValue($value) {
       return $this->op." (".implode(", ", (array)$value).")";
     }
   }');
     self::$NOT_IN = newinstance(__CLASS__, array(1, 'NOT_IN', 'not in'), '{
     static function __static() {}
     function forValue($value) {
       return $this->op." (".implode(", ", (array)$value).")";
     }
   }');
 }
Ejemplo n.º 12
0
 public function newinstance()
 {
     $runnable = newinstance(Runnable::class, [], ['run' => function () {
         return 'Test';
     }]);
     $this->assertEquals('Test', cast($runnable, Runnable::class)->run());
 }
Ejemplo n.º 13
0
 public function newinstance()
 {
     $runnable = newinstance('lang.Runnable', array(), '{
     public function run() { return "RUN"; }
   }');
     $this->assertEquals('RUN', cast($runnable, 'lang.Runnable')->run());
 }
    /**
     * Creates underlying base for class loader, e.g. a directory or a .XAR file
     *
     * @return  net.xp_framework.unittest.reflection.ClassFromUriBase
     */
    protected static function baseImpl()
    {
        return newinstance('net.xp_framework.unittest.reflection.ClassFromUriBase', array(), '{
      protected $t= NULL;

      public function create() {
        $this->t= new \\io\\Folder(\\lang\\System::tempDir(), "fsclt");
        $this->t->create();
      }

      public function delete() {
        $this->t->unlink();
      }

      public function newFile($name, $contents) {
        $file= new \\io\\File($this->t, $name);
        $path= new \\io\\Folder($file->getPath());
        $path->exists() || $path->create();

        \\io\\FileUtil::setContents($file, $contents);
      }

      public function path() {
        return rtrim($this->t->getURI(), DIRECTORY_SEPARATOR);
      }
    }');
    }
Ejemplo n.º 15
0
 /**
  * Sets up test case
  */
 public function setUp()
 {
     $this->fixture = newinstance(ImapStore::class, [], ['connect' => [], '_connect' => function ($mbx, $user, $pass, $flags) {
         $this->connect = ['mbx' => $mbx, 'user' => $user, 'pass' => $pass, 'flags' => $flags];
         return true;
     }]);
 }
Ejemplo n.º 16
0
 static function __static()
 {
     self::$sources['cookie'] = self::$COOKIE = newinstance(__CLASS__, array(1, 'cookie'), '{
     static function __static() { }
     public function read($name, $target, $request) {
       if (NULL === ($cookie= $request->getCookie($name, NULL))) return NULL;
       return $cookie->getValue();
     }
   }');
     self::$sources['header'] = self::$HEADER = newinstance(__CLASS__, array(2, 'header'), '{
     static function __static() { }
     public function read($name, $target, $request) {
       return $request->getHeader($name, NULL);
     }
   }');
     self::$sources['param'] = self::$PARAM = newinstance(__CLASS__, array(3, 'param'), '{
     static function __static() { }
     public function read($name, $target, $request) {
       return $request->getParam($name, NULL);
     }
   }');
     self::$sources['path'] = self::$PATH = newinstance(__CLASS__, array(4, 'path'), '{
     static function __static() { }
     public function read($name, $target, $request) {
       return isset($target["segments"][$name]) ? rawurldecode($target["segments"][$name]) : NULL;
     }
   }');
     self::$sources['body'] = self::$BODY = newinstance(__CLASS__, array(5, 'body'), '{
     static function __static() { }
     public function read($name, $target, $request) {
       return RestFormat::forMediaType($target["input"])->read($request->getInputStream(), Type::$VAR); 
     }
   }');
 }
Ejemplo n.º 17
0
 static function __static()
 {
     self::$CLEANLY = newinstance(self::class, [], '{
   static function __static() { }
   public function isError() { return false; }
 }');
 }
Ejemplo n.º 18
0
 static function __static()
 {
     self::$UNKNOWN = newinstance(__CLASS__, [null, [], null], '{
   static function __static() { }
   public function toString() { return "com.maxmind.geoip.Name(UNKNOWN)"; }
 }');
 }
Ejemplo n.º 19
0
 /**
  * Sets up test case
  *
  */
 public function setUp()
 {
     $this->builder = new MarkupBuilder();
     $this->builder->registerProcessor('summary', newinstance('text.doclet.markup.DelegatingProcessor', [$this->builder->processors['default']], ['tag' => function () {
         return "summary";
     }]));
 }
Ejemplo n.º 20
0
 /**
  * Initialize streams
  *
  * @param  bool console
  */
 public static function initialize($console)
 {
     if ($console) {
         self::$in = new StringReader(new ConsoleInputStream(STDIN));
         self::$out = new StringWriter(new ConsoleOutputStream(STDOUT));
         self::$err = new StringWriter(new ConsoleOutputStream(STDERR));
     } else {
         self::$in = newinstance('io.streams.InputStreamReader', [null], '{
     public function __construct($in) { }
     public function getStream() { return null; }
     public function raise() { throw new \\lang\\IllegalStateException("There is no console present"); }
     public function read($count= 8192) { $this->raise(); }
     public function readLine() { $this->raise(); }
   }');
         self::$out = self::$err = newinstance('io.streams.OutputStreamWriter', [null], '{
     public function __construct($out) { }
     public function getStream() { return null; }
     public function flush() { $this->raise(); }
     public function raise() { throw new \\lang\\IllegalStateException("There is no console present"); }
     public function write() { $this->raise(); }
     public function writeLine() { $this->raise(); }
     public function writef() { $this->raise(); }
     public function writeLinef() { $this->raise(); }
   }');
     }
 }
Ejemplo n.º 21
0
 public function invocation()
 {
     $methods = newinstance('net.xp_framework.unittest.core.generics.ArrayFilter<lang.reflect.Method>', [], ['accept' => function ($method) {
         return 'invocation' === $method->getName();
     }]);
     $this->assertEquals([$this->getClass()->getMethod('invocation')], $methods->filter($this->getClass()->getMethods()));
 }
Ejemplo n.º 22
0
 /**
  * Initialize members.
  */
 public function __construct()
 {
     $this->typeName = new Tokens(T_STRING, T_NS_SEPARATOR);
     $this->collectMembers = newinstance('text.parse.rules.Collection', [], '{
   public function collect(&$values, $value) {
     $values[$value["kind"]][$value["name"]]= $value;
   }
 }');
     $this->collectElements = newinstance('text.parse.rules.Collection', [], '{
   public function collect(&$values, $value) {
     if (is_array($value)) {
       $values[key($value)]= current($value);
     } else {
       $values[]= $value;
     }
   }
 }');
     $this->collectAnnotations = newinstance('text.parse.rules.Collection', [], '{
   public function collect(&$values, $value) {
     $target= $value["target"];
     $values[$target[0]][$target[1]]= $value["value"];
   }
 }');
     parent::__construct();
 }
Ejemplo n.º 23
0
    static function __static()
    {
        self::$iterate = newinstance('Iterator', [], '{
      private $i= 0, $c;
      private function value($n) {
        if (!$n->hasChildren()) return $n->getContent();
        $names= array();
        foreach ($n->getChildren() as $c) {
          $names[$c->getName()]= TRUE;
        }
        $result= array();
        if (sizeof($names) > 1) foreach ($n->getChildren() as $c) {
          $result[$c->getName()]= $this->value($c);
        } else foreach ($n->getChildren() as $c) {
          $result[]= $this->value($c);
        }

        return $result;
      }
      public function on($c) { $self= new self(); $self->c= $c; return $self; }
      public function current() { return $this->value($this->c[$this->i]); }
      public function key() { return $this->c[$this->i]->getName(); }
      public function next() { $this->i++; }
      public function rewind() { $this->i= 0; }
      public function valid() { return $this->i < sizeof($this->c); }
    }');
    }
Ejemplo n.º 24
0
 /**
  * Start server
  *
  * @param   string[] args
  */
 public static function main(array $args)
 {
     $stor = new TestingStorage();
     $stor->add(new TestingCollection('/', $stor));
     $stor->add(new TestingCollection('/.trash', $stor));
     $stor->add(new TestingElement('/.trash/do-not-remove.txt', $stor));
     $stor->add(new TestingCollection('/htdocs', $stor));
     $stor->add(new TestingElement('/htdocs/file with whitespaces.html', $stor));
     $stor->add(new TestingElement('/htdocs/index.html', $stor, "<html/>\n"));
     $stor->add(new TestingCollection('/outer', $stor));
     $stor->add(new TestingCollection('/outer/inner', $stor));
     $stor->add(new TestingElement('/outer/inner/index.html', $stor));
     $auth = newinstance('lang.Object', array(), '{
     public function authenticate($user, $password) {
       return ("testtest" == $user.$password);
     }
   }');
     $protocol = newinstance('peer.ftp.server.FtpProtocol', array($stor, $auth), '{
     public function onShutdown($socket, $params) {
       $this->answer($socket, 200, "Shutting down");
       $this->server->terminate= TRUE;
     }
   }');
     isset($args[0]) && $protocol->setTrace(Logger::getInstance()->getCategory()->withAppender(new FileAppender($args[0])));
     $s = new Server('127.0.0.1', 0);
     try {
         $s->setProtocol($protocol);
         $s->init();
         Console::writeLinef('+ Service %s:%d', $s->socket->host, $s->socket->port);
         $s->service();
         Console::writeLine('+ Done');
     } catch (Throwable $e) {
         Console::writeLine('- ', $e->getMessage());
     }
 }
Ejemplo n.º 25
0
 /**
  * Sets up test case
  *
  */
 public function setUp()
 {
     $this->builder = new MarkupBuilder();
     $this->builder->registerProcessor('summary', newinstance('text.doclet.markup.DelegatingProcessor', array($this->builder->processors['default']), '{
     public function tag() { return "summary"; }
   }'));
 }
Ejemplo n.º 26
0
    static function __static()
    {
        if (defined('HHVM_VERSION')) {
            $reflect = 'FromHHVM';
        } else {
            if (PHP_VERSION < '7.0.0') {
                $reflect = 'From';
            } else {
                $reflect = 'FromPhp7';
            }
        }
        self::$REFLECTION = newinstance(self::class, [1, 'REFLECTION'], sprintf('{
      static function __static() { }

      public function reflect($class, $source= null) {
        if ($class instanceof \\ReflectionClass) {
          return new %1$sReflection($class, $source ?: $this);
        } else if ($class instanceof \\lang\\XPClass) {
          return new %1$sReflection($class->reflect(), $source ?: $this);
        }

        $literal= strtr($class, ".", "\\\\");
        if (class_exists($literal) || interface_exists($literal) || trait_exists($literal)) {
          return new %1$sReflection(new \\ReflectionClass($literal), $source ?: $this);
        }

        $dotted= strtr($class, "\\\\", ".");
        if (\\lang\\ClassLoader::getDefault()->providesClass($dotted)) {
          return new %1$sCode($dotted, $source ?: $this);
        } else {
          return new FromIncomplete($literal);
        }
      }
    }', $reflect));
        self::$CODE = newinstance(self::class, [2, 'CODE'], sprintf('{
      static function __static() { }

      public function reflect($class, $source= null) {
        if ($class instanceof \\ReflectionClass) {
          return new %1$sReflection($class, $source ?: $this);
        } else if ($class instanceof \\lang\\XPClass) {
          return new %1$sReflection($class->reflect(), $source ?: $this);
        }

        $dotted= strtr($class, "\\\\", ".");
        if (\\lang\\ClassLoader::getDefault()->providesClass($dotted)) {
          return new %1$sCode($dotted, $source ?: $this);
        }

        $literal= strtr($class, ".", "\\\\");
        if (class_exists($literal) || interface_exists($literal) || trait_exists($literal)) {
          return new %1$sReflection(new \\ReflectionClass($literal), $source ?: $this);
        } else {
          return new FromIncomplete($literal);
        }
      }
    }', $reflect));
        self::$DEFAULT = self::$REFLECTION;
    }
Ejemplo n.º 27
0
 public function can_optionally_be_given_bindings()
 {
     $inject = new Injector($this->bindings, newinstance(Bindings::class, [], ['configure' => function ($inject) {
         $inject->bind(Currency::class, Currency::$EUR, 'EUR');
     }]));
     $this->assertInstanceOf(FileSystem::class, $inject->get(Storage::class));
     $this->assertEquals(Currency::$EUR, $inject->get(Currency::class, 'EUR'));
 }
Ejemplo n.º 28
0
 public function cloneInterceptorThrowsException()
 {
     clone newinstance('lang.Object', array(), '{
   public function __clone() {
     throw new CloneNotSupportedException("I am *UN*Cloneable");
   }
 }');
 }
Ejemplo n.º 29
0
 public function register_algorithm()
 {
     $algorithm = newinstance(Algorithm::class, [], ['strengthOf' => function ($password) {
         return 0;
     }]);
     PasswordStrength::setAlgorithm('test', typeof($algorithm));
     $this->assertInstanceOf(nameof($algorithm), PasswordStrength::getAlgorithm('test'));
 }
Ejemplo n.º 30
0
 /** @return void */
 public function setUp()
 {
     $this->handler = newinstance(InvocationHandler::class, [], ['invocations' => [], 'invoke' => function ($proxy, $method, $args) {
         $this->invocations[$method . '_' . sizeof($args)] = $args;
     }]);
     $this->iteratorClass = XPClass::forName(XPIterator::class);
     $this->observerClass = XPClass::forName(Observer::class);
 }