/**
  * @test
  * @profile
  * @ignore(ignoreUntilFixed)
  */
 public function mockFactory()
 {
     $mockException = Mock_Factory::mock('Components\\Test_Exception', array('test/unit/case/mock', 'Mocked Exception.'));
     $mockExceptionDefault = Mock_Factory::mock('Components\\Test_Exception');
     $mockRunner = Mock_Factory::mock('Components\\Test_Runner');
     $mockListener = Mock_Factory::mock('Components\\Test_Listener');
     $mockListener->when('onInitialize')->doReturn(true);
     $mockListener->when('onExecute')->doReturn(true);
     $mockListener->when('onTerminate')->doNothing();
     assertTrue($mockListener->onExecute($mockRunner));
     assertTrue($mockListener->onInitialize($mockRunner));
     $mockLL->onTerminate($mockRunner);
     assertEquals('test/unit/case/mock', $mockException->getNamespace());
     assertEquals('Mocked Exception.', $mockException->getMessage());
     assertEquals('test/exception', $mockExceptionDefault->getNamespace());
     assertEquals('Test exception.', $mockExceptionDefault->getMessage());
     $mockBindingModule = Mock_Factory::mock('Components\\Binding_Module');
     $mockBindingModule->when('bind')->doAnswer(function (Binding_Module $self_, $type_) {
         echo "Bound {$type_}\r\n";
         return $self_->bind($type_);
     });
     $mockBindingModule->when('configure')->doAnswer(function (Binding_Module $self_) {
         $self_->bind('Components\\Test_Runner')->toInstance(Test_Runner::get());
         $self_->bind(Integer::TYPE)->toInstance(22)->named('boundInteger');
     });
     $injector = Injector::create($mockBindingModule);
     assertSame(Test_Runner::get(), $injector->resolveInstance('Components\\Test_Runner'));
     assertEquals(22, $injector->resolveInstance(Integer::TYPE, 'boundInteger'));
 }
 public function testItCanUseDifferentContainerAdapters()
 {
     $container = new ExampleContainer();
     ExampleContainerAdapter::reset();
     Configurator::apply()->withContainerAdapter(ExampleContainer::class, ExampleContainerAdapter::class)->configFromArray([])->to($container);
     assertSame(1, ExampleContainerAdapter::getNumberOfInstances());
 }
 /**
  * @param string       $code
  * @param PyStringNode $csv
  *
  * @Then /^exported file of "([^"]*)" should contain:$/
  *
  * @throws ExpectationException
  * @throws \Exception
  */
 public function exportedFileOfShouldContain($code, PyStringNode $csv)
 {
     $config = $this->getFixturesContext()->getJobInstance($code)->getRawConfiguration();
     $path = $this->getMainContext()->getSubcontext('job')->getJobInstancePath($code);
     if (!is_file($path)) {
         throw $this->getMainContext()->createExpectationException(sprintf('File "%s" doesn\'t exist', $path));
     }
     $delimiter = isset($config['delimiter']) ? $config['delimiter'] : ';';
     $enclosure = isset($config['enclosure']) ? $config['enclosure'] : '"';
     $escape = isset($config['escape']) ? $config['escape'] : '\\';
     $csvFile = new \SplFileObject($path);
     $csvFile->setFlags(\SplFileObject::READ_CSV | \SplFileObject::READ_AHEAD | \SplFileObject::SKIP_EMPTY | \SplFileObject::DROP_NEW_LINE);
     $csvFile->setCsvControl($delimiter, $enclosure, $escape);
     $expectedLines = [];
     foreach ($csv->getLines() as $line) {
         if (!empty($line)) {
             $expectedLines[] = explode($delimiter, str_replace($enclosure, '', $line));
         }
     }
     $actualLines = [];
     while ($data = $csvFile->fgetcsv()) {
         if (!empty($data)) {
             $actualLines[] = array_map(function ($item) use($enclosure) {
                 return str_replace($enclosure, '', $item);
             }, $data);
         }
     }
     $expectedCount = count($expectedLines);
     $actualCount = count($actualLines);
     assertSame($expectedCount, $actualCount, sprintf('Expecting to see %d rows, found %d', $expectedCount, $actualCount));
     if (md5(json_encode($actualLines[0])) !== md5(json_encode($expectedLines[0]))) {
         throw new \Exception(sprintf('Header in the file %s does not match expected one: %s', $path, implode(' | ', $actualLines[0])));
     }
     unset($actualLines[0]);
     unset($expectedLines[0]);
     foreach ($expectedLines as $expectedLine) {
         $originalExpectedLine = $expectedLine;
         $found = false;
         foreach ($actualLines as $index => $actualLine) {
             // Order of columns is not ensured
             // Sorting the line values allows to have two identical lines
             // with values in different orders
             sort($expectedLine);
             sort($actualLine);
             // Same thing for the rows
             // Order of the rows is not reliable
             // So we generate a hash for the current line and ensured that
             // the generated file contains a line with the same hash
             if (md5(json_encode($actualLine)) === md5(json_encode($expectedLine))) {
                 $found = true;
                 // Unset line to prevent comparing it twice
                 unset($actualLines[$index]);
                 break;
             }
         }
         if (!$found) {
             throw new \Exception(sprintf('Could not find a line containing "%s" in %s', implode(' | ', $originalExpectedLine), $path));
         }
     }
 }
 public function testServiceAliasDefinition()
 {
     $definition = new ServiceDefinition('service_name', ['service' => __CLASS__]);
     assertTrue($definition->isAlias());
     assertFalse($definition->isFactory());
     assertSame(__CLASS__, $definition->getClass());
 }
 public function testReturnsTheSameReaderForTheSameFileType()
 {
     $this->createTestFile('test1.php');
     $this->createTestFile('test2.php');
     $reader1 = $this->factory->create($this->getTestPath('test1.php'));
     $reader2 = $this->factory->create($this->getTestPath('test2.php'));
     assertSame($reader1, $reader2);
 }
 public function testItAddToConfigUsingFiles()
 {
     $config = ['keyB' => 'valueB'];
     $this->createJSONConfigFile('config.json', $config);
     Configurator::apply()->configFromArray(['keyA' => 'valueA', 'keyB' => 'valueX'])->configFromFiles($this->getTestPath('*'))->to($this->container);
     assertSame('valueA', $this->container->get('config.keyA'));
     assertSame('valueB', $this->container->get('config.keyB'));
 }
 /**
  * @test
  * @covers Mobileka\ScopeApplicator\Laravel\InputManager::get
  */
 public function gets_value_from_user_input()
 {
     $lim = new Mobileka\ScopeApplicator\Laravel\InputManager();
     assertNull($lim->get('param'));
     assertSame('no such param', $lim->get('param', 'no such param'));
     // add something to request parameters
     $lim->inputManager->query->set('param', 'hello');
     assertEquals('hello', $lim->get('param'));
 }
Example #8
0
 public function testGet()
 {
     $alias = new Alias('test');
     $locator = $this->getMockBuilder(LocatorInterface::class)->getMock();
     $locator->method('get')->will($this->returnValue(123));
     /** @var LocatorInterface $locator */
     assertSame(123, $alias->get($locator));
     assertSame(123, $alias->get($locator));
 }
 /**
  * @test
  * @covers Mobileka\ScopeApplicator\Yii2\InputManager::get
  */
 public function gets_value_from_user_input()
 {
     $im = new Mobileka\ScopeApplicator\Yii2\InputManager();
     assertNull($im->get('param'));
     assertSame('no such param', $im->get('param', 'no such param'));
     // add something to request parameters
     $im->setQueryParams(['param' => 'hello']);
     assertEquals('hello', $im->get('param'));
 }
 public function testCreateException()
 {
     $this->setExpectedException(\RuntimeException::class);
     $this->createModels(Order::class, []);
     $source = DataSource::make(Order::all());
     assertSame(null, $source[0]);
     $source['0.code'] = 'a1';
     return;
 }
Example #11
0
 public function testBasicFlow()
 {
     $source = [];
     $e = new Endpoint($source);
     assertSame($source, $e->toArray());
     $source = ['name' => 'Frank', 'surname' => 'Sinatra'];
     $e = new Endpoint($source);
     $e->string('name');
     $e->string('surname');
     $e->fromSource();
     $e->fromInput();
     $e->validate();
     $e->writeSource();
     assertSame($source, $e->toArray());
 }
 /**
  * @param string $identifiers
  *
  * @Then /^I should be able to normalize and denormalize (?:the )?products? (.*)$/
  */
 public function iShouldBeAbleToNormalizeAndDenormalizeProducts($identifiers)
 {
     $identifiers = $this->getMainContext()->listToArray($identifiers);
     $serializer = $this->getContainer()->get('pim_serializer');
     foreach ($identifiers as $identifier) {
         $product = $this->getFixturesContext()->getProduct($identifier);
         $data = $serializer->normalize($product, 'json');
         $values = $data['values'];
         foreach ($values as $attributeCode => $valuesData) {
             $attribute = $this->getFixturesContext()->getAttribute($attributeCode);
             foreach ($valuesData as $valueData) {
                 $createdValue = $serializer->denormalize($valueData, 'Pim\\Bundle\\CatalogBundle\\Model\\ProductValue', 'json', ['attribute' => $attribute]);
                 $newData = $serializer->normalize($createdValue, 'json', ['entity' => 'product']);
                 assertSame($valueData, $newData, sprintf("Product's \"%s\" value for attribute %s in locale %s and scope %s is not correct", $identifier, $attributeCode, $valueData['locale'] ?: 'null', $valueData['scope'] ?: 'null'));
             }
         }
     }
 }
Example #13
0
 public function testBelongsToOne()
 {
     $details = new CustomerDetail();
     $source = DataSource::make($details);
     $source['biography'] = 'A nice life!';
     $source['accepts_cookies'] = 0;
     $source['customer.name'] = 'Frank';
     $source['customer.surname'] = 'Sinatra';
     assertSame('A nice life!', $source['biography']);
     assertSame(0, $source['accepts_cookies']);
     $source->save();
     assertSame(1, Customer::all()->count());
     assertSame(1, CustomerDetail::all()->count());
     // test that we don't create duplicates
     $source['biography'] = 'prefers not say';
     $source['customer.name'] = 'Frank';
     assertSame(1, Customer::all()->count());
     assertSame(1, CustomerDetail::all()->count());
 }
 /**
  * @param array  $expectedLines
  * @param array  $actualLines
  * @param string $path
  *
  * @throws \Exception
  */
 protected function compareFile(array $expectedLines, array $actualLines, $path)
 {
     $expectedCount = count($expectedLines);
     $actualCount = count($actualLines);
     assertSame($expectedCount, $actualCount, sprintf('Expecting to see %d rows, found %d', $expectedCount, $actualCount));
     $currentActualLines = current($actualLines);
     $currentExpectedLines = current($expectedLines);
     $headerDiff = array_diff($currentActualLines, $currentExpectedLines);
     if (0 !== count(array_diff($currentActualLines, $currentExpectedLines))) {
         throw new \Exception(sprintf("Header in the file %s does not match \n expected one: %s \n missing headers : %s", $path, implode(' | ', current($actualLines)), implode(' | ', $headerDiff)));
     }
     array_shift($actualLines);
     array_shift($expectedLines);
     foreach ($expectedLines as $expectedLine) {
         $rows = array_filter($actualLines, function ($actualLine) use($expectedLine) {
             return 0 === count(array_diff($expectedLine, $actualLine));
         });
         if (1 !== count($rows)) {
             throw new \Exception(sprintf('Could not find a line containing "%s" in %s', implode(' | ', $expectedLine), $path));
         }
     }
 }
Example #15
0
 public function testExistingChildren()
 {
     // --- test load
     $this->createModels(Customer::class, []);
     $this->createModels(Order::class, [['code' => 'a1', 'shipping' => 'home', 'customer_id' => 1], ['code' => 'b1', 'shipping' => 'office', 'customer_id' => 1]]);
     $customer = new Customer();
     $source = Datasource::make(new Customer());
     $source['id'] = 1;
     $source['name'] = 'Frank';
     $source['surname'] = 'Sinatra';
     $source->save();
     // this is how eloquent behaves (always false)
     assertFalse(isset($customer->orders));
     // this is how datasource behaves (always true)
     assertTrue(isset($source['orders']));
     assertInstanceOf(Collection::class, $customer->orders);
     assertInstanceOf(Collection::class, $source['orders']);
     assertModelArrayEqual(Order::all(), $source['orders']);
     // don't do this at home, folks :)
     assertSame('Frank', $source['orders.0.customer.name']);
     assertSame('Frank', $source['orders.0.customer.orders.0.customer.name']);
 }
Example #16
0
 public function testExistingChildren()
 {
     // --- test load
     $this->createModels(Order::class, []);
     $this->createModels(Book::class, [['title' => 'Happiness'], ['title' => 'Delight']]);
     $this->createPivot('book_order', [['book_id' => 1, 'order_id' => 1], ['book_id' => 2, 'order_id' => 1]]);
     $order = new Order();
     $source = Datasource::make(new Order());
     $source['id'] = 1;
     $source['code'] = 'a1';
     $source['shipping'] = 'home';
     $source['customer_id'] = 1;
     $source->save();
     // this is how eloquent behaves (always false)
     assertFalse(isset($order->books));
     // this is how datasource behaves (always true)
     assertTrue(isset($source['books']));
     assertInstanceOf(Collection::class, $order->books);
     assertInstanceOf(Collection::class, $source['books']);
     assertModelArrayEqual(Book::all()->toArray(), $source['books']->toArray());
     // don't do this at home, folks :)
     assertSame('Happiness', $source['books.0.orders.0.books.0.title']);
     assertSame('Happiness', $source['books.0.orders.0.books.0.orders.0.books.0.orders.0.books.0.title']);
 }
Example #17
0
 public function testHasOne()
 {
     $customer = new Customer();
     $source = DataSource::make($customer);
     $source['name'] = 'Frank';
     $source['surname'] = 'Sinatra';
     $source['details.biography'] = 'A nice life!';
     $source['details.accepts_cookies'] = 0;
     $source['details.accepts_cookies'] = 0;
     // test cache
     assertSame('Frank', $source['name']);
     assertSame('A nice life!', $source['details.biography']);
     assertSame(0, $source['details.accepts_cookies']);
     $source->save();
     assertSame(1, Customer::all()->count());
     assertSame(1, CustomerDetail::all()->count());
     // test everything's saved
     $result = Customer::all()->first();
     assertSame('A nice life!', $result->details->biography);
     assertEquals(0, $result->details->accepts_cookies);
     // test we don't create duplicates
     $source['surname'] = 'Sinatrax';
     $source['details.biography'] = 'prefers not say';
     $source['details.accepts_cookies'] = 1;
     assertSame(1, Customer::all()->count());
     assertSame(1, CustomerDetail::all()->count());
     return;
 }
Example #18
0
 /**
  * Checks, that (?P<num>\d+) CSS elements exist on the page
  *
  * @Then /^(?:|I )should see (?P<num>\d+) "(?P<element>[^"]*)" elements?$/
  */
 public function assertNumElements($num, $element)
 {
     $nodes = $this->getSession()->getPage()->findAll('css', $element);
     if (null === $nodes) {
         throw new ElementNotFoundException($this->getSession(), 'element: ' . $element . ' ');
     }
     assertSame((int) $num, count($nodes));
 }
 public function testItUpdatesTheSeparator()
 {
     $config = new ApplicationConfig(['group' => ['keyA' => 'valueA']]);
     $config->setSeparator('/');
     assertSame('valueA', $config['group/keyA']);
 }
Example #20
0
 /**
  * @test
  */
 public function toIsoStringShouldBeWithMillisconds()
 {
     $dt = new \Clock\DateTime('2012-08-16T09:38:14.451Z');
     assertSame('2012-08-16T09:38:14.451Z', $dt->toIsoString(true));
 }
Example #21
0
 /**
  * @Then /^I should see$/
  */
 public function iShouldSee(PyStringNode $string)
 {
     assertSame($string->getRaw(), $this->testCommand->getDisplay());
 }
 public function testItCanBeCreatedFromThePattern()
 {
     assertSame('No files found matching pattern: "*.json".', NoMatchingFilesException::fromPattern('*.json')->getMessage());
 }
 public function testItCanBeCreatedFromSetting()
 {
     $exception = UnknownSettingException::fromSetting('unknown', ['setting_a', 'setting_b']);
     assertSame('Setting "unknown" is unknown; valid settings are ["setting_a", "setting_b"].', $exception->getMessage());
 }
 /**
  * @Given /^the "([^"]*)" property is a integer equalling "([^"]*)"$/
  */
 public function thePropertyIsAIntegerEqualling($property, $expectedValue)
 {
     $payload = $this->getScopePayload();
     $actualValue = $this->arrayGet($payload, $property);
     $this->thePropertyIsAnInteger($property);
     assertSame($actualValue, (int) $expectedValue, "Asserting the [{$property}] property in current scope [{$this->scope}] is an integer equalling [{$expectedValue}].");
 }
Example #25
0
 /**
  * @param string    $fileName
  * @param TableNode $table
  *
  * @Given /^the category order in the file "([^"]*)" should be following:$/
  *
  * @throws ExpectationException
  */
 public function theCategoryOrderInTheFileShouldBeFollowing($fileName, TableNode $table)
 {
     $fileName = $this->replacePlaceholders($fileName);
     if (!file_exists($fileName)) {
         throw $this->createExpectationException(sprintf('File %s does not exist.', $fileName));
     }
     $categories = [];
     foreach (array_keys($table->getRowsHash()) as $category) {
         $categories[] = $category;
     }
     $file = fopen($fileName, 'rb');
     fgets($file);
     while (false !== ($row = fgets($file))) {
         $category = array_shift($categories);
         assertSame(0, strpos($row, $category), sprintf('Expecting category "%s", saw "%s"', $category, $row));
     }
     fclose($file);
 }
Example #26
0
 /**
  * @Given /^the response body length is "([^"]*)"$/
  */
 public function assertResponseBodyLength($length)
 {
     assertSame(strlen((string) $this->getLastResponse()->getBody()), (int) $length);
 }
Example #27
0
 public function testGetDependencyMap()
 {
     $locator = new Locator();
     $result = [];
     assertSame($result, $locator->getDependencyMap());
     $locator->set('test', 'magic');
     assertSame($result, $locator->getDependencyMap());
     $locator->get('test');
     $result += ['test' => []];
     assertSame($result, $locator->getDependencyMap());
 }
Example #28
0
 /**
  * @covers Mobileka\MosaicArray\MosaicArray::excludeByRule
  */
 public function test_excludes_target_elements_by_rule()
 {
     $fixture = ['key' => 'value', 1, 2, 3, 'numbers' => [1, 2, 3]];
     $ma = new MosaicArray($fixture);
     $expect = [1, 2, 3, 'numbers' => [1, 2, 3]];
     $result = $ma->excludeByRule(function ($key, $value) {
         return $key === 'key';
     });
     assertSame($expect, $result);
     $expect = $fixture;
     $result = $ma->excludeByRule(function ($key, $value) {
         return $value == 'nothing will be excluded';
     });
     assertSame($expect, $result);
     // exclude all numeric values
     $expect = ['key' => 'value', 'numbers' => [1, 2, 3]];
     $result = $ma->excludeByRule(function ($key, $value) {
         return is_numeric($value);
     });
     assertSame($expect, $result);
     // exclude all arrays
     $expect = ['key' => 'value', 1, 2, 3];
     $result = $ma->excludeByRule(function ($key, $value) {
         return is_array($value);
     });
     assertSame($expect, $result);
     // exclude all non-numeric keys
     $expect = [1, 2, 3];
     $result = $ma->excludeByRule(function ($key, $value) {
         return !is_numeric($key);
     });
     assertSame($expect, $result);
 }
 /** @test */
 public function reportViolationSendsMailAndReturnsOK()
 {
     $client = $this->createClient();
     $crawler = $client->request('GET', '/api/reportViolation.php', array('docment_id' => 'testid'));
     assertSame('OK', $client->getResponse()->getContent());
 }
Example #30
0
 /**
  * @Then the car with the id :id should have property :propertyName with the value :expectedValue:
  */
 public function theCarWithTheIdShouldHavePropertyWithValue($id, $propertyName, $expectedValue)
 {
     if ('true' === $expectedValue) {
         $expectedValue = true;
     } elseif ('false' === $expectedValue) {
         $expectedValue = false;
     }
     $car = $this->repository->find($id);
     $getter = 'get' . ucfirst(strtolower($propertyName));
     assertSame($expectedValue, $car->{$getter}());
 }