/** @dataProvider provideDateInterval */ public function testShouldLoadMonthsBetweenTwoDates($start, $end, $expectedMonthsCount) { $analyzer = $this->prophesize('Scortes\\Calendar\\Month\\AnalyzeMonth'); $analyzer->__invoke(Argument::any())->shouldBeCalledTimes($expectedMonthsCount); $uc = new CreateMonthsInterval($analyzer->reveal()); $months = $uc(DateTime::createFromFormat('Y-m', $start), DateTime::createFromFormat('Y-m', $end)); assertThat($months, arrayWithSize($expectedMonthsCount)); return $months; }
public function testShouldFormatManyAccordingToConvertMethod() { $items = ['foo', 'bar', 'baz']; $formatter = new MockFormatter(); $result = $formatter->formatMany($items); assertThat('The result of `formatMany` should be an array of arrays.', $result, everyItem(is(typeOf('array')))); assertThat('The result should be the same size as the number of items passed to `formatMany`.', $result, is(arrayWithSize(count($items)))); assertThat('The result should be correctly formatted.', $result, is(anArray([['count' => 1], ['count' => 2], ['count' => 3]]))); }
public function testRouteWithOptionalVariable() { $pattern = $this->instance->build('/news/{year:\\d{4}}/{month:\\d{2}}/{?slug}'); assertThat($pattern, is(arrayWithSize(2))); list($regEx, $variables) = $pattern; assertThat($regEx, is(equalTo('/news/(\\d{4})/(\\d{2})(?:/([^/]+))?'))); assertThat($variables, is(equalTo(['year', 'month', 'slug']))); assertThat(preg_match('~^' . $regEx . '$~', '/news/2014/05/lastest-news'), is(true)); assertThat(preg_match('~^' . $regEx . '$~', '/news/2014/05'), is(true)); }
public function testOperation() { $CartGetOperation = $this->app->make('Giftertipster\\Service\\Api\\AmzProductApi\\ApaiIO\\Operations\\CartGetOperation'); $CartGetOperation->setCartId('cart id stub'); $CartGetOperation->setHMAC('hmac stub'); $params = $CartGetOperation->getOperationParameter(); assertThat($CartGetOperation->getName(), equalTo('CartGet')); assertThat($params, arrayWithSize(2)); assertThat($params, hasKeyValuePair('CartId', 'cart id stub')); assertThat($params, hasKeyValuePair('HMAC', 'hmac stub')); }
public function testOperation() { $CartCreateOperation = $this->app->make('Giftertipster\\Service\\Api\\AmzProductApi\\ApaiIO\\Operations\\CartCreateOperation'); $CartCreateOperation->addItem('foo bar', 1); $CartCreateOperation->addItem('foo bar2', 2); $params = $CartCreateOperation->getOperationParameter(); assertThat($CartCreateOperation->getName(), equalTo('CartCreate')); assertThat($params, arrayWithSize(4)); assertThat($params, hasKeyValuePair('Item.1.OfferListingId', 'foo bar')); assertThat($params, hasKeyValuePair('Item.1.Quantity', 1)); assertThat($params, hasKeyValuePair('Item.2.OfferListingId', 'foo bar2')); assertThat($params, hasKeyValuePair('Item.2.Quantity', 2)); }
public function testMountControllerWithBaseRoute() { $patternBuilder = \Mockery::mock('Rootr\\PatternBuilder'); $router = new Router($patternBuilder); $controllerRouter = \Mockery::mock('Rootr\\Router'); $controllerRouter->shouldReceive('getStaticRoutes')->andReturn(['' => ['GET' => ['Rootr\\ProductController', 'indexAction']]]); $controllerRouter->shouldReceive('getVariableRoutes')->andReturn(['/(\\d+)' => ['GET' => [['Rootr\\ProductController', 'showAction'], ['id']]]]); $controller = \Mockery::mock(['getRouter' => $controllerRouter]); $router->mountController('/products', $controller); assertThat($router->getStaticRoutes(), arrayWithSize(1)); assertThat($router->getStaticRoutes(), hasKeyInArray('/products')); assertThat($router->getVariableRoutes(), arrayWithSize(1)); assertThat($router->getVariableRoutes(), hasKeyInArray('/products/(\\d+)')); }
public function testOperation() { $CartModifyOperation = $this->app->make('Giftertipster\\Service\\Api\\AmzProductApi\\ApaiIO\\Operations\\CartModifyOperation'); $CartModifyOperation->setCartId('cart id stub'); $CartModifyOperation->setHMAC('hmac stub'); $CartModifyOperation->modifyItem('foo bar', 1); $CartModifyOperation->modifyItem('foo bar2', 2); $params = $CartModifyOperation->getOperationParameter(); assertThat($CartModifyOperation->getName(), equalTo('CartModify')); assertThat($params, arrayWithSize(6)); assertThat($params, hasKeyValuePair('CartId', 'cart id stub')); assertThat($params, hasKeyValuePair('HMAC', 'hmac stub')); assertThat($params, hasKeyValuePair('Item.1.CartItemId', 'foo bar')); assertThat($params, hasKeyValuePair('Item.1.Quantity', 1)); assertThat($params, hasKeyValuePair('Item.2.CartItemId', 'foo bar2')); assertThat($params, hasKeyValuePair('Item.2.Quantity', 2)); }
public function testGetCopyrightHighlights() { $this->testDb->createPlainTables(array(), true); $this->testDb->createInheritedTables(); $uploadDao = M::mock('Fossology\\Lib\\Dao\\UploadDao'); $uploadDao->shouldReceive('getUploadEntry')->with(1)->andReturn(array('pfile_fk' => 8)); $uploadDao->shouldReceive('getUploadEntry')->with(2)->andReturn(array('pfile_fk' => 9)); $copyrightDao = new CopyrightDao($this->dbManager, $uploadDao); $noHighlights = $copyrightDao->getHighlights($uploadTreeId = 1); assertThat($noHighlights, emptyArray()); $this->testDb->insertData(array('copyright')); $highlights = $copyrightDao->getHighlights($uploadTreeId = 1); assertThat($highlights, arrayWithSize(1)); $highlight0 = $highlights[0]; assertThat($highlight0, anInstanceOf(Highlight::classname())); $this->assertInstanceOf('Fossology\\Lib\\Data\\Highlight', $highlight0); assertThat($highlight0->getEnd(), equalTo(201)); $hilights = $copyrightDao->getHighlights($uploadTreeId = 2); assertThat($hilights, arrayWithSize(1)); $hilight0 = $hilights[0]; assertThat($hilight0->getStart(), equalTo(0)); }
public function testValidateCartReturnsFalseAndLogsErrorsOnFailWhenThereAreErrorsInTheResponseThatAreIgnorable() { \Config::shouldReceive('get')->with('api.amz_product_api_response_validation.ignorable_error_codes')->once()->andReturn(['ignorable test code']); $validator = $this->app->make('Giftertipster\\Service\\Api\\AmzProductApi\\ResponseValidation'); $api_response_stub = new \SimpleXMLElement('<xml></xml>'); $items = $api_response_stub->addChild('Cart'); $items->addChild('Request')->addChild('IsValid', 'true'); $errors = $items->Request->addChild('Errors'); $error1 = $errors->addChild('Error'); $error2 = $errors->addChild('Error'); $error1->addChild('Code', 'ignorable test code'); $error1->addChild('Message', 'message one'); $error2->addChild('Code', 'valid code'); $error2->addChild('Message', 'message two'); $response = $validator->validate($api_response_stub); $errors = $validator->errors(); assertThat($response, identicalTo(false)); assertThat($errors, arrayWithSize(1)); assertThat($errors[0], equalTo('message two')); }
public function testGetIdRangeReturnsExpectedResultsWithOnlyStartId() { $this->makeRelatedModels(); $add_attributes = ['add_type_id' => 1, 'product_id' => 1]; $response = $this->eloquent_add->newInstance()->fill($add_attributes)->save(); $add_attributes = ['add_type_id' => 2, 'product_id' => 1]; $response = $this->eloquent_add->newInstance()->fill($add_attributes)->save(); $add_attributes = ['add_type_id' => 3, 'product_id' => 1]; $response = $this->eloquent_add->newInstance()->fill($add_attributes)->save(); $add_attributes = ['add_type_id' => 4, 'product_id' => 1]; $response = $this->eloquent_add->newInstance()->fill($add_attributes)->save(); $result = $this->add_repo->getIdRange(0); assertThat($result, arrayWithSize(4)); assertThat($result[0]['id'], equalTo(1)); assertThat($result[0]['add_type_id'], equalTo(1)); assertThat($result[3]['id'], equalTo(4)); assertThat($result[3]['add_type_id'], equalTo(4)); }
private function runnerReuserScanWithARepoClearingEnhanced($runner) { $this->setUpTables(); $this->setUpRepo(); $originallyClearedItemId = 23; /* upload 3 in the test db is the same as upload 2 -> items 13-24 in upload 2 correspond to 33-44 */ $reusingUploadItemShift = 20; $this->dbManager->queryOnce("UPDATE uploadtree_a SET pfile_fk=351 WHERE uploadtree_pk={$originallyClearedItemId}+{$reusingUploadItemShift}", __METHOD__ . '.minorChange'); $this->uploadDao->addReusedUpload($uploadId = 3, $reusedUpload = 2, $this->groupId, $this->groupId, $reuseMode = 1); $repoPath = $this->testDb->getFossSysConf() . '/repo/files/'; $this->treeDao->shouldReceive('getRepoPathOfPfile')->with(4)->andReturn($repoPath . '04621571bcbabce75c4dd1c6445b87dec0995734.59cacdfce5051cd8a1d8a1f2dcce40a5.12320'); $this->treeDao->shouldReceive('getRepoPathOfPfile')->with(351)->andReturn($repoPath . 'c518ce1658140b65fa0132ad1130cb91512416bf.8e913e594d24ff3aeabe350107d97815.35829'); list($clearingLicense1, $clearingLicense2, $addedEventIds) = $this->insertDecisionFromTwoEvents(DecisionScopes::REPO, $originallyClearedItemId); $clearingLicenses = array($clearingLicense1, $clearingLicense2); list($success, $output, $retCode) = $runner->run($uploadId, $this->userId, $this->groupId); $this->assertTrue($success, 'cannot run runner'); $this->assertEquals($retCode, 0, 'reuser failed: ' . $output); $newUploadClearings = $this->getFilteredClearings($uploadId, $this->groupId); $potentiallyReusableClearings = $this->getFilteredClearings($reusedUpload, $this->groupId); assertThat($newUploadClearings, is(arrayWithSize(1))); assertThat($potentiallyReusableClearings, is(arrayWithSize(1))); /** @var ClearingDecision */ $potentiallyReusableClearing = $potentiallyReusableClearings[0]; /** @var ClearingDecision */ $newClearing = $newUploadClearings[0]; /* they are actually the same ClearingDecision * only sameFolder and sameUpload are different */ assertThat($newClearing, not(equalTo($potentiallyReusableClearing))); assertThat($newClearing->getClearingLicenses(), arrayContainingInAnyOrder($clearingLicenses)); assertThat($newClearing->getType(), equalTo($potentiallyReusableClearing->getType())); assertThat($newClearing->getScope(), equalTo($potentiallyReusableClearing->getScope())); assertThat($newClearing->getUploadTreeId(), equalTo($potentiallyReusableClearing->getUploadTreeId() + $reusingUploadItemShift)); /* reuser should have not created a correct local event history */ $bounds = $this->uploadDao->getItemTreeBounds($originallyClearedItemId + $reusingUploadItemShift); $newEvents = $this->clearingDao->getRelevantClearingEvents($bounds, $this->groupId); assertThat($newEvents, is(arrayWithSize(count($clearingLicenses)))); /** @var ClearingEvent $newEvent */ foreach ($newEvents as $newEvent) { assertThat($newEvent->getEventId(), anyOf($addedEventIds)); assertThat($newEvent->getClearingLicense(), anyOf($clearingLicenses)); } $this->rmRepo(); }
/** @dataProvider provideLevels */ public function testMergeValuesWithSameKey($key) { $this->events->set($key, 'value'); $this->events->set($key, 'override'); assertThat($this->events->get($key), arrayWithSize(2)); }
private function runnerDeciderScanWithNoEventsAndNomosContainedInMonkWithButWithOtherAgentMatchForSameLicenseShouldMakeADecision($runner) { $this->setUpTables(); $this->setUpRepo(); $licenseRef1 = $this->licenseDao->getLicenseByShortName("GPL-3.0")->getRef(); $licenseRef2 = $this->licenseDao->getLicenseByShortName("GPL-1.0")->getRef(); $licenseRef3 = $this->licenseDao->getLicenseByShortName("APL-1.0")->getRef(); $licId1 = $licenseRef1->getId(); $licId2 = $licenseRef2->getId(); $licId3 = $licenseRef3->getId(); $agentNomosId = 6; $agentMonkId = 5; $agentOther = 8; $pfile = 4; $this->dbManager->queryOnce("INSERT INTO license_map(rf_fk, rf_parent, usage) VALUES ({$licId2}, {$licId1}, " . LicenseMap::CONCLUSION . ")"); $this->dbManager->queryOnce("INSERT INTO license_map(rf_fk, rf_parent, usage) VALUES ({$licId3}, {$licId1}, " . LicenseMap::CONCLUSION . ")"); $this->dbManager->queryOnce("DELETE FROM license_file"); $this->dbManager->queryOnce("INSERT INTO license_file (fl_pk,rf_fk,pfile_fk,agent_fk) VALUES(12222,{$licId1},{$pfile},{$agentNomosId})"); $this->dbManager->queryOnce("INSERT INTO highlight (fl_fk,start,len) VALUES(12222,10,3)"); $this->dbManager->queryOnce("INSERT INTO highlight (fl_fk,start,len) VALUES(12222,18,3)"); $this->dbManager->queryOnce("INSERT INTO license_file (fl_pk,rf_fk,pfile_fk,agent_fk) VALUES(12223,{$licId2},{$pfile},{$agentMonkId})"); $this->dbManager->queryOnce("INSERT INTO highlight (fl_fk,start,len) VALUES(12223,6,2)"); $this->dbManager->queryOnce("INSERT INTO highlight (fl_fk,start,len) VALUES(12223,13,19)"); $this->dbManager->queryOnce("INSERT INTO license_file (fl_pk,rf_fk,pfile_fk,agent_fk) VALUES(12224,{$licId3},{$pfile},{$agentOther})"); $this->dbManager->queryOnce("INSERT INTO highlight (fl_fk,start,len) VALUES(12224,9,2)"); $this->dbManager->queryOnce("INSERT INTO highlight (fl_fk,start,len) VALUES(12224,13,19)"); list($success, $output, $retCode) = $runner->run($uploadId = 2, $userId = 6, $groupId = 4, $jobId = 31, $args = ""); $this->assertTrue($success, 'cannot run runner'); $this->assertEquals($retCode, 0, 'decider failed (did you make test?): ' . $output); assertThat($this->getHeartCount($output), equalTo(1)); $uploadBounds = $this->uploadDao->getParentItemBounds($uploadId); $decisions = $this->clearingDao->getFileClearingsFolder($uploadBounds, $groupId); assertThat($decisions, is(arrayWithSize(1))); $this->rmRepo(); }
public function testGetRemovableContents() { $this->folderDao->ensureTopLevelFolder(); $folderA = $this->folderDao->insertFolder($folderName = 'A', '/A', FolderDao::TOP_LEVEL); $this->folderDao->insertFolder('B', '/A/B', $folderA); $folderC = $this->folderDao->insertFolder('C', '/C', FolderDao::TOP_LEVEL); assertThat($this->folderDao->getRemovableContents($folderA), arrayWithSize(0)); $this->dbManager->insertTableRow('foldercontents', array('foldercontents_mode' => FolderDao::MODE_UPLOAD, 'parent_fk' => $folderA, 'child_id' => $folderC)); assertThat($this->folderDao->getRemovableContents($folderA), arrayWithSize(0)); $this->dbManager->insertTableRow('foldercontents', array('foldercontents_mode' => FolderDao::MODE_FOLDER, 'parent_fk' => $folderA, 'child_id' => $folderC)); assertThat($this->folderDao->getRemovableContents($folderA), arrayWithSize(1)); }
public function testGetMappedLicenseRefView() { $this->testDb = new TestPgDb(); $this->testDb->createPlainTables(array('license_ref', 'license_map')); $this->dbManager = $this->testDb->getDbManager(); $this->dbManager->queryOnce("CREATE TABLE license_candidate (group_fk integer) INHERITS (license_ref)"); $this->dbManager->insertTableRow('license_map', array('license_map_pk' => 0, 'rf_fk' => 2, 'rf_parent' => 1, 'usage' => LicenseMap::CONCLUSION)); $this->dbManager->insertTableRow('license_ref', array('rf_pk' => 1, 'rf_shortname' => 'One', 'rf_fullname' => 'One-1')); $this->dbManager->insertTableRow('license_ref', array('rf_pk' => 2, 'rf_shortname' => 'Two', 'rf_fullname' => 'Two-2')); $this->dbManager->insertTableRow('license_candidate', array('rf_pk' => 3, 'rf_shortname' => 'Three', 'rf_fullname' => 'Three-3', 'group_fk' => $this->groupId)); $this->assertCountBefore = \Hamcrest\MatcherAssert::getCount(); $view = LicenseMap::getMappedLicenseRefView(LicenseMap::CONCLUSION); $stmt = __METHOD__; $this->dbManager->prepare($stmt, $view); $res = $this->dbManager->execute($stmt); $map = $this->dbManager->fetchAll($res); $this->dbManager->freeResult($res); assertThat($map, is(arrayWithSize(2))); $expected = array(array('rf_origin' => 1, 'rf_pk' => 1, 'rf_shortname' => 'One', 'rf_fullname' => 'One-1'), array('rf_origin' => 2, 'rf_pk' => 1, 'rf_shortname' => 'One', 'rf_fullname' => 'One-1')); assertThat($map, containsInAnyOrder($expected)); }
public function testGetCurrentClearingsWithUserRemovedDecisionsOnly() { /** @var LicenseRef $licenseRef */ list($scannerResults, $licenseRef, $agentRef) = $this->createScannerDetectedLicenses(); $removedEvent = $this->createClearingEvent(123, $this->timestamp, $licenseRef->getId(), $licenseRef->getShortName(), $licenseRef->getFullName(), ClearingEventTypes::USER, true); $this->agentLicenseEventProcessor->shouldReceive("getScannerEvents")->with($this->itemTreeBounds, LicenseMap::TRIVIAL)->andReturn($scannerResults); $this->clearingDao->shouldReceive("getRelevantClearingEvents")->with($this->itemTreeBounds, $this->groupId)->andReturn(array($licenseRef->getId() => $removedEvent)); list($licenseDecisions, $removedClearings) = $this->clearingDecisionProcessor->getCurrentClearings($this->itemTreeBounds, $this->groupId); assertThat($licenseDecisions, is(emptyArray())); assertThat($removedClearings, is(arrayWithSize(1))); /** @var ClearingResult $result */ $result = $removedClearings[$removedEvent->getLicenseId()]; assertThat($result->getLicenseRef(), is($removedEvent->getLicenseRef())); assertThat($result->getClearingEvent(), is($removedEvent)); $agentClearingEvents = $result->getAgentDecisionEvents(); assertThat($agentClearingEvents, is(arrayWithSize(1))); $agentEvent = $agentClearingEvents[0]; assertThat($agentEvent->getAgentRef(), is($agentRef)); assertThat($agentEvent->getLicenseRef(), is($licenseRef)); assertThat($agentEvent->getMatchId(), is(self::MATCH_ID)); assertThat($agentEvent->getPercentage(), is(self::PERCENTAGE)); }
public function testCreate() { Factory::create('Giftertipster\\Entity\\Eloquent\\User', ['permissions' => []]); $product_attributes = ['user_id' => 1, 'vendor' => 'amazon', 'vendor_id' => 'b000000', 'binding' => 'testbinding', 'brand' => 'testbrand', 'manufacturer' => 'test manufacturer', 'model' => 'test model', 'group' => 'test group', 'type' => 'test type', 'size' => 'testsize', 'clothing_size' => 'test clothing size', 'color' => 'testcolor', 'title' => 'test title', 'department' => 'test department', 'min_price_amount' => '4000', 'min_price_currency' => 'usd', 'min_price_formatted' => '$40.00', 'max_price_amount' => '4000', 'max_price_currency' => 'usd', 'max_price_formatted' => '$40.00', 'reviews_url' => 'reviewsurl.com', 'detail_url' => 'detailurl.com']; $product = $this->app->make('Giftertipster\\Repository\\Product\\EloquentProductRepository'); $response = $product->create($product_attributes); $products = $product->all(10); assertThat($response, equalTo(true)); assertThat($products, arrayWithSize(1)); assertThat($products[0], hasKeyValuePair('id', 1)); }
private function runnerDeciderScanWithForceDecision($runner) { $this->setUpTables(); $this->setUpRepo(); $jobId = 42; $licenseRef1 = $this->licenseDao->getLicenseByShortName("GPL-3.0")->getRef(); $licenseRef2 = $this->licenseDao->getLicenseByShortName("3DFX")->getRef(); $agentLicId = $this->licenseDao->getLicenseByShortName("Adaptec")->getRef()->getId(); $addedLicenses = array($licenseRef1, $licenseRef2); assertThat($addedLicenses, not(arrayContaining(null))); $agentId = 5; $pfile = 4; $this->dbManager->queryOnce("INSERT INTO license_file (fl_pk,rf_fk,pfile_fk,agent_fk) VALUES(12222,{$agentLicId},{$pfile},{$agentId})"); $itemTreeBounds = $this->uploadDao->getItemTreeBounds($itemId = 23); assertThat($this->agentLicenseEventProcessor->getScannerEvents($itemTreeBounds), is(not(emptyArray()))); $eventId1 = $this->clearingDao->insertClearingEvent($itemId, $userId = 2, $groupId = 3, $licenseRef1->getId(), false); $eventId2 = $this->clearingDao->insertClearingEvent($itemId, 5, $groupId, $licenseRef2->getId(), true); $this->dbManager->queryOnce("UPDATE clearing_event SET job_fk={$jobId}"); $addedEventIds = array($eventId1, $eventId2); list($success, $output, $retCode) = $runner->run($uploadId = 2, $userId, $groupId, $jobId, $args = "-k1"); $this->assertTrue($success, 'cannot run runner'); $this->assertEquals($retCode, 0, 'decider failed: ' . $output); assertThat($this->getHeartCount($output), equalTo(1)); $uploadBounds = $this->uploadDao->getParentItemBounds($uploadId); $decisions = $this->clearingDao->getFileClearingsFolder($uploadBounds, $groupId); assertThat($decisions, is(arrayWithSize(1))); /** @var ClearingDecision $deciderMadeDecision */ $deciderMadeDecision = $decisions[0]; $eventIds = array(); foreach ($deciderMadeDecision->getClearingEvents() as $event) { $eventIds[] = $event->getEventId(); } assertThat($eventIds, arrayValue($addedEventIds[0])); assertThat($eventIds, arrayValue($addedEventIds[1])); assertThat($eventIds, arrayWithSize(1 + count($addedEventIds))); $this->rmRepo(); }
public function testFilteredProductsWithAllFiltersWorks() { $seed_product = Factory::create('Giftertipster\\Entity\\Eloquent\\Product', ['group' => 'foo', 'min_price_amount' => 50, 'max_price_amount' => 50]); $seed_product2 = Factory::create('Giftertipster\\Entity\\Eloquent\\Product', ['group' => 'bar', 'min_price_amount' => 150, 'max_price_amount' => 150]); $seed_product3 = Factory::create('Giftertipster\\Entity\\Eloquent\\Product', ['group' => 'foobar']); $seed_image1 = Factory::create('Giftertipster\\Entity\\Eloquent\\Image', ['imageable_id' => 1, 'imageable_type' => 'Giftertipster\\Entity\\Eloquent\\Product']); $seed_image2 = Factory::create('Giftertipster\\Entity\\Eloquent\\Image', ['imageable_id' => 2, 'imageable_type' => 'Giftertipster\\Entity\\Eloquent\\Product']); $categories_filter = new CategoriesFilter(); $categories_filter->categories(['foo', 'bar']); $price_range_filter = new PriceRangeFilter(); $price_range_filter->minPrice(5)->maxPrice(100); $product = $this->app->make('Giftertipster\\Repository\\ProductSuite\\EloquentProductSuiteRepository'); $products = $product->filteredProducts([$categories_filter, $price_range_filter]); assertThat($products, arrayWithSize(1)); assertThat($products[0], hasKeyValuePair('id', 1)); assertThat($products[0]['images'], not(emptyArray())); }
public function testMainLicenseIds() { $this->testDb->createPlainTables(array('upload_clearing_license')); $uploadId = 101; $mainLicIdsInitially = $this->clearingDao->getMainLicenseIds($uploadId, $this->groupId); assertThat($mainLicIdsInitially, is(emptyArray())); $this->clearingDao->makeMainLicense($uploadId, $this->groupId, $licenseId = 402); $mainLicIdsAfterAddingOne = $this->clearingDao->getMainLicenseIds($uploadId, $this->groupId); assertThat($mainLicIdsAfterAddingOne, arrayContaining(array($licenseId))); $this->clearingDao->makeMainLicense($uploadId, $this->groupId, $licenseId); $mainLicIdsAfterAddingOneTwice = $this->clearingDao->getMainLicenseIds($uploadId, $this->groupId); assertThat($mainLicIdsAfterAddingOneTwice, is(arrayWithSize(1))); $this->clearingDao->makeMainLicense($uploadId, $this->groupId, $licenseId2 = 403); $mainLicIdsAfterAddingOther = $this->clearingDao->getMainLicenseIds($uploadId, $this->groupId); assertThat($mainLicIdsAfterAddingOther, arrayContainingInAnyOrder(array($licenseId, $licenseId2))); $this->clearingDao->removeMainLicense($uploadId, $this->groupId, $licenseId2); $mainLicIdsAfterRemovingOne = $this->clearingDao->getMainLicenseIds($uploadId, $this->groupId); assertThat($mainLicIdsAfterRemovingOne, is(arrayWithSize(1))); $this->clearingDao->removeMainLicense($uploadId, $this->groupId, $licenseId2); $mainLicIdAfterRemovingSomethingNotInSet = $this->clearingDao->getMainLicenseIds($uploadId, $this->groupId); assertThat($mainLicIdAfterRemovingSomethingNotInSet, is(arrayWithSize(1))); $this->clearingDao->removeMainLicense($uploadId, $this->groupId + 1, $licenseId); $mainLicIdAfterInsertToOtherGroup = $this->clearingDao->getMainLicenseIds($uploadId, $this->groupId); assertThat($mainLicIdAfterInsertToOtherGroup, is(arrayWithSize(1))); $this->clearingDao->removeMainLicense($uploadId + 1, $this->groupId, $licenseId); $mainLicIdAfterInsertToOtherUpload = $this->clearingDao->getMainLicenseIds($uploadId, $this->groupId); assertThat($mainLicIdAfterInsertToOtherUpload, is(arrayWithSize(1))); }
public function testFinderCreateLogsNoticeWhenSomeSubProductVariationsAttributesAreInvalid() { Factory::create('Giftertipster\\Entity\\Eloquent\\Idea', ['user_id' => 1, 'is_fulfilled' => 0]); $suite_attributes = ['vendor' => 'amazon', 'vendor_id' => 'b000000', 'binding' => 'testbinding', 'brand' => 'testbrand', 'manufacturer' => 'test manufacturer', 'model' => 'test model', 'group' => 'test group', 'type' => 'test type', 'size' => 'testsize', 'clothing_size' => 'test clothing size', 'color' => 'testcolor', 'title' => 'test title', 'department' => 'test department', 'min_price_amount' => 4000, 'min_price_currency' => 'USD', 'min_price_formatted' => '$40.00', 'max_price_amount' => 4000, 'max_price_currency' => 'USD', 'max_price_formatted' => '$40.00', 'reviews_url' => 'reviewsurl.com', 'detail_url' => 'detailurl.com']; $suite_attributes['images'] = []; $suite_attributes['features'] = []; $suite_attributes['descriptions'] = []; $suite_attributes['sub_products'][] = ['vendor' => 'amazon', 'vendor_id' => 'b000001', 'parent_vendor_id' => 'b000000', 'binding' => 'testbinding', 'brand' => 'testbrand', 'manufacturer' => 'test manufacturer', 'model' => 'test model', 'group' => 'test group', 'type' => 'test type', 'size' => 'testsize', 'clothing_size' => 'test clothing size', 'color' => 'testcolor', 'title' => 'test title', 'condition' => 'test condition', 'department' => 'test department', 'list_price_amount' => 4000, 'list_price_currency' => 'USD', 'list_price_formatted' => '$40.00', 'price_amount' => 4000, 'price_currency' => 'USD', 'price_formatted' => '$40.00', 'availability' => 'test avail', 'availability_type' => 'test avail type', 'availability_max_hours' => 'test avail max hours', 'availability_min_hours' => 'test avail min hours', 'availability_ship' => 'test avail ship', 'availability_ss_ship' => 1, 'offer_listing_id' => 'foo1', 'images' => [], 'descriptions' => [], 'features' => []]; $suite_attributes['sub_products'][0]['variations'][] = ['type' => 'variationtype', 'value' => 'variation1']; $suite_attributes['sub_products'][0]['variations'][] = ['type' => '', 'value' => 'variation2']; $suite_attributes['keyword_profile']['profile'] = []; $suite_attributes['category_keywords'] = []; $expected_index_attributes = ['vendor' => 'amazon', 'vendor_id' => 'b000000', 'binding' => 'testbinding', 'brand' => 'testbrand', 'manufacturer' => 'test manufacturer', 'model' => 'test model', 'group' => 'test group', 'type' => 'test type', 'size' => 'testsize', 'clothing_size' => 'test clothing size', 'color' => 'testcolor', 'title' => 'test title', 'department' => 'test department', 'min_price_amount' => 4000, 'min_price_currency' => 'USD', 'min_price_formatted' => '$40.00', 'max_price_amount' => 4000, 'max_price_currency' => 'USD', 'max_price_formatted' => '$40.00', 'reviews_url' => 'reviewsurl.com', 'detail_url' => 'detailurl.com']; $expected_index_attributes['images'] = []; $expected_index_attributes['features'] = []; $expected_index_attributes['descriptions'] = []; $expected_index_attributes['sub_products'][] = ['vendor' => 'amazon', 'vendor_id' => 'b000001', 'parent_vendor_id' => 'b000000', 'binding' => 'testbinding', 'brand' => 'testbrand', 'manufacturer' => 'test manufacturer', 'model' => 'test model', 'group' => 'test group', 'type' => 'test type', 'size' => 'testsize', 'clothing_size' => 'test clothing size', 'color' => 'testcolor', 'title' => 'test title', 'condition' => 'test condition', 'department' => 'test department', 'list_price_amount' => 4000, 'list_price_currency' => 'USD', 'list_price_formatted' => '$40.00', 'price_amount' => 4000, 'price_currency' => 'USD', 'price_formatted' => '$40.00', 'availability' => 'test avail', 'availability_type' => 'test avail type', 'availability_max_hours' => 'test avail max hours', 'availability_min_hours' => 'test avail min hours', 'availability_ship' => 'test avail ship', 'availability_ss_ship' => 1, 'offer_listing_id' => 'foo1', 'images' => [], 'descriptions' => [], 'features' => []]; $expected_index_attributes['sub_products'][0]['variations'][] = ['type' => 'variationtype', 'value' => 'variation1']; $expected_index_attributes['keyword_profile']['profile'] = []; $expected_index_attributes['category_keywords'] = []; \Log::shouldReceive('notice')->once(); //mock ProductSuiteIndexer $expected_product_suite = $expected_index_attributes; $indexer = Mockery::mock('Giftertipster\\Service\\ProductSuite\\ProductSuiteIndexerInterface'); $indexer->shouldReceive('queueIndex')->with(Mockery::on(function ($product_suite) use($expected_product_suite) { if (!empty($this->arrayRecursiveDiff($expected_product_suite, $product_suite))) { return false; } return true; }), false, false)->once()->andReturn(true); $this->app->instance('Giftertipster\\Service\\ProductSuite\\ProductSuiteIndexerInterface', $indexer); $repo = $this->app->make('Giftertipster\\Repository\\ProductSuite\\EloquentProductSuiteRepository'); $response = $repo->finderCreate($suite_attributes, 'Idea', 1, 2); $errors = $repo->errors(); assertThat($response, equalTo(true)); $eloquent_product = $this->app->make('Giftertipster\\Entity\\Eloquent\\Product'); $product = $eloquent_product->find(1); $eloquent_variation = $this->app->make('Giftertipster\\Entity\\Eloquent\\Variation'); $sub_product_variation = $eloquent_variation->where('sub_product_id', '=', 1)->get()->toArray(); assertThat($errors, nullValue()); assertThat($product, notNullValue()); assertThat($sub_product_variation, arrayWithSize(1)); }
public function testGetAdminsWithProfile() { \Artisan::call('db:seed'); //user 1 comes from db:seed $user1 = \Giftertipster\Entity\Eloquent\User::find(1); $user2 = Factory::create('Giftertipster\\Entity\\Eloquent\\User', ['permissions' => ['test']]); $user3 = Factory::create('Giftertipster\\Entity\\Eloquent\\User', ['permissions' => ['test']]); //seed user profile for user 1 $user1_profile = $user1->user_profile()->get()->first(); $user1_profile->first_name = 'foobar'; $user1_profile->save(); $result = $this->repo()->getAdminsWithProfile(); assertThat($result, arrayWithSize(3)); assertThat($result[0], hasKeyValuePair('id', 1)); assertThat($result[0]['user_profile'][0]['first_name'], equalTo('foobar')); assertThat($result[1], hasKeyValuePair('id', 2)); assertThat($result[1]['user_profile'], identicalTo([])); assertThat($result[2], hasKeyValuePair('id', 3)); assertThat($result[2]['user_profile'], identicalTo([])); }
public function testDeletePermDeletesProductAndIdeaRelationAndReturnsTrue() { $index_repo = Mockery::mock('Giftertipster\\Repository\\ProductsIndex\\Product\\ProductsIndexProductRepositoryInterface'); $index_repo->shouldReceive('deleteProductAndAdds')->with(1, true)->once()->andReturn(true); $this->app->instance('Giftertipster\\Repository\\ProductsIndex\\Product\\ProductsIndexProductRepositoryInterface', $index_repo); $data_repo = $this->dataRepoSetup(); $this->getDataRepoData(); //make second product $product = $this->app->make('Giftertipster\\Entity\\Eloquent\\Product'); $product->fill(['user_id' => 1, 'vendor' => 'amazon', 'vendor_id' => 'b000000', 'binding' => 'testbinding', 'brand' => 'testbrand', 'manufacturer' => 'test manufacturer', 'model' => 'test model', 'group' => 'test group', 'type' => 'test type', 'size' => 'testsize', 'clothing_size' => 'test clothing size', 'color' => 'testcolor', 'title' => 'test title', 'department' => 'test department', 'min_price_amount' => 4000, 'min_price_currency' => 'USD', 'min_price_formatted' => '$40.00', 'max_price_amount' => 4000, 'max_price_currency' => 'USD', 'max_price_formatted' => '$40.00', 'reviews_url' => 'reviewsurl.com', 'detail_url' => 'detailurl.com'])->save(); //connect products to idea Factory::create('Giftertipster\\Entity\\Eloquent\\User', ['permissions' => []]); $idea = $this->app->make('Giftertipster\\Entity\\Eloquent\\Idea'); $idea->fill(['user_id' => 1, 'vendor' => 'test', 'vendor_id' => 100, 'description' => 'test', 'add_profile' => '', 'is_fulfilled' => 0]); $this->product->ideas()->save($idea); //product id 1 $product->ideas()->save($idea); //product id 2 $idea_check = $idea->where('product_id', '=', 1)->get(); assertThat($idea_check, not(nullValue())); $idea_check = $idea->where('product_id', '=', 2)->get(); assertThat($idea_check, not(nullValue())); $response = $data_repo->delete(1); assertThat($response, identicalTo(true)); $product = $this->app->make('Giftertipster\\Entity\\Eloquent\\Product'); $product_check = $product->find(1); $idea_check = $idea->has('products')->get()->toArray(); assertThat($product_check, nullValue()); assertThat($idea_check, arrayWithSize(1)); assertThat($idea->exists(), equalTo(true)); }
public function testGetJobInfo() { $this->dbManager->prepare($stmt = 'insert.jobqueue', "INSERT INTO jobqueue (jq_pk, jq_job_fk, jq_type, jq_args, jq_starttime, jq_endtime, jq_endtext, jq_end_bits, jq_schedinfo, jq_itemsprocessed)" . "VALUES (\$1, \$2, \$3, \$4,\$5, \$6,\$7,\$8,\$9,\$10)"); $nowTime = time(); $diffTime = 2345; $nomosTime = date('Y-m-d H:i:sO', $nowTime - $diffTime); $uploadArrayQue = array(array(8, $jobId = 1, "nomos", 1, $nomosTime, null, "Started", 0, "localhost.5963", $itemNomos = 147), array(1, $jobId, "ununpack", 1, "2015-04-21 18:29:19.23825+05:30", "2015-04-21 18:29:26.396562+05:30", "Completed", 1, null, $itemCount = 646)); foreach ($uploadArrayQue as $uploadEntry) { $this->dbManager->freeResult($this->dbManager->execute($stmt, $uploadEntry)); } $this->dbManager->prepare($stmt = 'insert.uploadtree_a', "INSERT INTO uploadtree_a (uploadtree_pk, parent, upload_fk, pfile_fk, ufile_mode, lft, rgt, ufile_name)" . "VALUES (\$1, \$2, \$3, \$4,\$5, \$6, \$7, \$8)"); $uploadTreeArray = array(array(123, 121, 1, 103, 32768, 542, 543, "fckeditorcode_ie.js"), array(121, 120, 1, 0, 536888320, 537, 544, "js"), array(715, 651, 2, 607, 33188, 534, 535, "zconf.h.cmakein"), array(915, 651, 2, 606, 33188, 532, 533, "zconf.h")); foreach ($uploadTreeArray as $uploadEntry) { $this->dbManager->freeResult($this->dbManager->execute($stmt, $uploadEntry)); } $this->dbManager->prepare($stmt = 'insert.jobdepends', "INSERT INTO jobdepends (jdep_jq_fk, jdep_jq_depends_fk) VALUES (\$1, \$2 )"); $jqWithTwoDependencies = 8; $jobDependsArray = array(array(2, 1), array(3, 2), array(4, 2), array(5, 2), array(6, 2), array($jqWithTwoDependencies, 4), array($jqWithTwoDependencies, 4)); foreach ($jobDependsArray as $uploadEntry) { $this->dbManager->freeResult($this->dbManager->execute($stmt, $uploadEntry)); } $testMyJobInfo = $this->showJobsDao->getJobInfo($this->job_pks); assertThat($testMyJobInfo, hasKey($jobId)); assertThat($testMyJobInfo[$jobId]['jobqueue'][$jqWithTwoDependencies]['depends'], is(arrayWithSize(2))); $testFilesPerSec = 0.23; $formattedEstimatedTime = $this->showJobsDao->getEstimatedTime($job_pk = 1, $jq_Type = "nomos", $testFilesPerSec); assertThat($formattedEstimatedTime, matchesPattern('/\\d+:\\d{2}:\\d{2}/')); $hourMinSec = explode(':', $formattedEstimatedTime); assertThat($hourMinSec[0] * 3600 + $hourMinSec[1] * 60 + $hourMinSec[2], is(closeTo(($itemCount - $itemNomos) / $testFilesPerSec, 0.5 + $testFilesPerSec))); $testGetEstimatedTime = $this->showJobsDao->getEstimatedTime($job_pk = 1, $jq_Type, 0); assertThat($testGetEstimatedTime, matchesPattern('/\\d+:\\d{2}:\\d{2}/')); $hourMinSec = explode(':', $testGetEstimatedTime); $tolerance = 0.5 + ($itemCount - $itemNomos) / $itemNomos + (time() - $nowTime); assertThat($hourMinSec[0] * 3600 + $hourMinSec[1] * 60 + $hourMinSec[2], is(closeTo(($itemCount - $itemNomos) / $itemNomos * $diffTime, $tolerance))); $fewFilesPerSec = 0.003; $formattedLongTime = $this->showJobsDao->getEstimatedTime($job_pk = 1, $jq_Type = "nomos", $fewFilesPerSec); assertThat($formattedLongTime, matchesPattern('/\\d+:\\d{2}:\\d{2}/')); $hourMinSec = explode(':', $formattedLongTime); assertThat($hourMinSec[0] * 3600 + $hourMinSec[1] * 60 + $hourMinSec[2], is(closeTo(($itemCount - $itemNomos) / $fewFilesPerSec, 0.5 + $fewFilesPerSec))); }
public function testFilterEffectiveEventsOppositeIdenticalEventsOverwriteInOtherOrder() { $events = array(); $licenseRef1 = M::mock(ClearingLicense::classname()); $licenseRef1->shouldReceive("getLicenseId")->withNoArgs()->andReturn("fortyTwo"); $events[] = $this->createEvent($this->timestamp, $licenseRef1); $licenseRef2 = M::mock(ClearingLicense::classname()); $licenseRef2->shouldReceive("getLicenseId")->withNoArgs()->andReturn("fortyTwo"); $events[] = $this->createEvent($this->timestamp + 60, $licenseRef2); $filteredEvents = $this->clearingEventProcessor->filterEffectiveEvents($events); assertThat($filteredEvents, is(arrayWithSize(1))); assertThat($filteredEvents, hasKeyValuePair('fortyTwo', $events[1])); }
/* Copyright (C) 2015, Siemens AG This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ namespace Fossology\Decider; use Mockery as M; $deciderPlugin = M::mock(); //'Fossology\\DeciderJob\\UI\\DeciderJobAgentPlugin'); $deciderPlugin->shouldReceive('AgentAdd')->withArgs(array(16, 2, anything(), arrayWithSize(1)))->once(); $GLOBALS['xyyzzzDeciderJob'] = $deciderPlugin; function plugin_find($x) { return $GLOBALS['xyyzzzDeciderJob']; } function IsAlreadyScheduled($jobId, $agentName, $uploadId) { return 177; }
public function testReceiveWithPolling() { $url = $this->stubCreateQueue(); $timeout = $this->stubQueueVisibilityTimeout($url); $receiveModel = m::mock('Aws\\ResultInterface'); $receiveModel->shouldReceive('get')->once()->with('Messages')->andReturn([['Body' => 'foo', 'Attributes' => [], 'MessageAttributes' => [], 'MessageId' => 0, 'ReceiptHandle' => 'a']]); $this->sqsClient->shouldReceive('receiveMessage')->once()->with(['QueueUrl' => $url, 'AttributeNames' => ['All'], 'MaxNumberOfMessages' => SqsAdapter::BATCHSIZE_RECEIVE, 'VisibilityTimeout' => $timeout])->andReturn($receiveModel); $deleteModel = m::mock('Aws\\ResultInterface'); $deleteModel->shouldReceive('get')->once()->with('Failed')->andReturn([]); $this->sqsClient->shouldReceive('deleteMessageBatch')->once()->with(['QueueUrl' => $url, 'Entries' => [['Id' => 0, 'ReceiptHandle' => 'a']]])->andReturn($deleteModel); $msgs = []; $this->client->receive(function ($msg, $done) use(&$msgs) { $msgs[] = $msg; $done(); }, null); assertThat($msgs, is(arrayWithSize(1))); }
public function testGetThese() { $this->createStubCategories(); $this->repo = $this->app->make('Giftertipster\\Repository\\Categories\\EloquentCategoriesRepository'); $collection = $this->repo->getThese([2, 3], 'occasion'); assertThat($collection, arrayWithSize(2)); assertThat($collection[0]['id'], equalTo(2)); assertThat($collection[1]['id'], equalTo(3)); }
public function testHasAReadableDescription() { $this->assertDescription('an array with size <3>', arrayWithSize(equalTo(3))); $this->assertDescription('an empty array', emptyArray()); }
public function testValidateSuiteAttributesForCreateReturnsFalseWhenCategoryKeywordsKeyIsMissing() { $stub = $this->suite_attributes_stub; unset($stub['category_keywords']); $response = $this->validator->validateSuiteAttributesForCreate($stub); assertThat($response, identicalTo(false)); assertThat($this->validator->errors(), arrayWithSize(greaterThan(0))); }