From 6dfd5d507d9863f987b30b0a5ab4268aea2ed875 Mon Sep 17 00:00:00 2001 From: Ludovic Pouzenc Date: Thu, 2 Aug 2012 11:09:40 +0000 Subject: J'étais parti sur un download pourri de Cake. Les gars on abusé sur GitHub. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit git-svn-id: file:///var/svn/2012-php-weave/trunk@7 d972a294-176a-4cf9-8ea1-fcd5b0c30f5c --- .../lib/Cake/Test/Case/AllBehaviorsTest.php | 42 + .../lib/Cake/Test/Case/AllCacheTest.php | 40 + .../lib/Cake/Test/Case/AllComponentsTest.php | 42 + .../lib/Cake/Test/Case/AllConfigureTest.php | 40 + .../lib/Cake/Test/Case/AllConsoleTest.php | 44 + .../lib/Cake/Test/Case/AllControllerTest.php | 44 + .../lib/Cake/Test/Case/AllCoreTest.php | 41 + .../lib/Cake/Test/Case/AllDatabaseTest.php | 56 + .../lib/Cake/Test/Case/AllErrorTest.php | 42 + .../lib/Cake/Test/Case/AllEventTest.php | 40 + .../lib/Cake/Test/Case/AllHelpersTest.php | 42 + .../lib/Cake/Test/Case/AllI18nTest.php | 40 + .../lib/Cake/Test/Case/AllLogTest.php | 41 + .../lib/Cake/Test/Case/AllNetworkTest.php | 42 + .../lib/Cake/Test/Case/AllRoutingTest.php | 44 + .../lib/Cake/Test/Case/AllTestSuiteTest.php | 40 + .../lib/Cake/Test/Case/AllTestsTest.php | 60 + .../lib/Cake/Test/Case/AllUtilityTest.php | 39 + .../lib/Cake/Test/Case/AllViewTest.php | 40 + .../lib/Cake/Test/Case/BasicsTest.php | 942 ++ .../lib/Cake/Test/Case/Cache/CacheTest.php | 412 + .../Cake/Test/Case/Cache/Engine/ApcEngineTest.php | 273 + .../Cake/Test/Case/Cache/Engine/FileEngineTest.php | 455 + .../Test/Case/Cache/Engine/MemcacheEngineTest.php | 479 + .../Test/Case/Cache/Engine/RedisEngineTest.php | 335 + .../Test/Case/Cache/Engine/WincacheEngineTest.php | 263 + .../Test/Case/Cache/Engine/XcacheEngineTest.php | 272 + .../lib/Cake/Test/Case/Configure/IniReaderTest.php | 188 + .../lib/Cake/Test/Case/Configure/PhpReaderTest.php | 170 + .../Cake/Test/Case/Console/AllConsoleLibsTest.php | 48 + .../lib/Cake/Test/Case/Console/AllConsoleTest.php | 44 + .../lib/Cake/Test/Case/Console/AllShellsTest.php | 42 + .../lib/Cake/Test/Case/Console/AllTasksTest.php | 42 + .../Test/Case/Console/Command/AclShellTest.php | 311 + .../Test/Case/Console/Command/ApiShellTest.php | 96 + .../Test/Case/Console/Command/BakeShellTest.php | 124 + .../Case/Console/Command/CommandListShellTest.php | 118 + .../Test/Case/Console/Command/SchemaShellTest.php | 492 ++ .../Console/Command/Task/ControllerTaskTest.php | 652 ++ .../Case/Console/Command/Task/DbConfigTaskTest.php | 133 + .../Case/Console/Command/Task/ExtractTaskTest.php | 462 + .../Case/Console/Command/Task/FixtureTaskTest.php | 388 + .../Case/Console/Command/Task/ModelTaskTest.php | 1189 +++ .../Case/Console/Command/Task/PluginTaskTest.php | 207 + .../Case/Console/Command/Task/ProjectTaskTest.php | 369 + .../Case/Console/Command/Task/TemplateTaskTest.php | 165 + .../Case/Console/Command/Task/TestTaskTest.php | 783 ++ .../Case/Console/Command/Task/ViewTaskTest.php | 731 ++ .../Test/Case/Console/Command/TestShellTest.php | 335 + .../Test/Case/Console/ConsoleErrorHandlerTest.php | 134 + .../Test/Case/Console/ConsoleOptionParserTest.php | 594 ++ .../Cake/Test/Case/Console/ConsoleOutputTest.php | 242 + .../Cake/Test/Case/Console/HelpFormatterTest.php | 505 ++ .../Cake/Test/Case/Console/ShellDispatcherTest.php | 576 ++ .../lib/Cake/Test/Case/Console/ShellTest.php | 875 ++ .../Cake/Test/Case/Console/TaskCollectionTest.php | 124 + .../Case/Controller/Component/Acl/DbAclTest.php | 543 ++ .../Case/Controller/Component/Acl/IniAclTest.php | 69 + .../Case/Controller/Component/Acl/PhpAclTest.php | 337 + .../Case/Controller/Component/AclComponentTest.php | 91 + .../Component/Auth/ActionsAuthorizeTest.php | 192 + .../Component/Auth/BasicAuthenticateTest.php | 206 + .../Component/Auth/ControllerAuthorizeTest.php | 84 + .../Component/Auth/CrudAuthorizeTest.php | 185 + .../Component/Auth/DigestAuthenticateTest.php | 306 + .../Component/Auth/FormAuthenticateTest.php | 193 + .../Controller/Component/AuthComponentTest.php | 1290 +++ .../Controller/Component/CookieComponentTest.php | 602 ++ .../Controller/Component/EmailComponentTest.php | 889 ++ .../Component/PaginatorComponentTest.php | 1194 +++ .../Component/RequestHandlerComponentTest.php | 879 ++ .../Controller/Component/SecurityComponentTest.php | 1375 +++ .../Controller/Component/SessionComponentTest.php | 294 + .../Case/Controller/ComponentCollectionTest.php | 178 + .../Cake/Test/Case/Controller/ComponentTest.php | 305 + .../Case/Controller/ControllerMergeVarsTest.php | 252 + .../Cake/Test/Case/Controller/ControllerTest.php | 1441 +++ .../Test/Case/Controller/PagesControllerTest.php | 53 + .../lib/Cake/Test/Case/Controller/ScaffoldTest.php | 350 + .../lib/Cake/Test/Case/Core/AppTest.php | 851 ++ .../lib/Cake/Test/Case/Core/CakePluginTest.php | 268 + .../lib/Cake/Test/Case/Core/ConfigureTest.php | 408 + .../lib/Cake/Test/Case/Core/ObjectTest.php | 673 ++ .../lib/Cake/Test/Case/Error/ErrorHandlerTest.php | 296 + .../Cake/Test/Case/Error/ExceptionRendererTest.php | 776 ++ .../Cake/Test/Case/Event/CakeEventManagerTest.php | 406 + .../lib/Cake/Test/Case/Event/CakeEventTest.php | 85 + .../lib/Cake/Test/Case/I18n/I18nTest.php | 1952 +++++ .../lib/Cake/Test/Case/I18n/L10nTest.php | 955 ++ .../lib/Cake/Test/Case/I18n/MultibyteTest.php | 9228 ++++++++++++++++++++ .../lib/Cake/Test/Case/Log/CakeLogTest.php | 676 ++ .../Cake/Test/Case/Log/Engine/ConsoleLogTest.php | 136 + .../lib/Cake/Test/Case/Log/Engine/FileLogTest.php | 83 + .../lib/Cake/Test/Case/Model/AclNodeTest.php | 385 + .../Test/Case/Model/Behavior/AclBehaviorTest.php | 491 ++ .../Model/Behavior/ContainableBehaviorTest.php | 3660 ++++++++ .../Case/Model/Behavior/TranslateBehaviorTest.php | 1061 +++ .../Case/Model/Behavior/TreeBehaviorAfterTest.php | 77 + .../Case/Model/Behavior/TreeBehaviorNumberTest.php | 1379 +++ .../Case/Model/Behavior/TreeBehaviorScopedTest.php | 316 + .../Test/Case/Model/Behavior/TreeBehaviorTest.php | 43 + .../Case/Model/Behavior/TreeBehaviorUuidTest.php | 255 + .../Test/Case/Model/BehaviorCollectionTest.php | 1185 +++ .../lib/Cake/Test/Case/Model/CakeSchemaTest.php | 1091 +++ .../Cake/Test/Case/Model/ConnectionManagerTest.php | 346 + .../Test/Case/Model/Datasource/CakeSessionTest.php | 754 ++ .../Test/Case/Model/Datasource/DataSourceTest.php | 250 + .../Case/Model/Datasource/Database/MysqlTest.php | 3623 ++++++++ .../Model/Datasource/Database/PostgresTest.php | 945 ++ .../Case/Model/Datasource/Database/SqliteTest.php | 419 + .../Model/Datasource/Database/SqlserverTest.php | 679 ++ .../Test/Case/Model/Datasource/DboSourceTest.php | 1102 +++ .../Model/Datasource/Session/CacheSessionTest.php | 117 + .../Datasource/Session/DatabaseSessionTest.php | 188 + .../Test/Case/Model/ModelCrossSchemaHabtmTest.php | 232 + .../lib/Cake/Test/Case/Model/ModelDeleteTest.php | 865 ++ .../Cake/Test/Case/Model/ModelIntegrationTest.php | 2426 +++++ .../lib/Cake/Test/Case/Model/ModelReadTest.php | 7881 +++++++++++++++++ .../lib/Cake/Test/Case/Model/ModelTest.php | 47 + .../lib/Cake/Test/Case/Model/ModelTestBase.php | 96 + .../Cake/Test/Case/Model/ModelValidationTest.php | 2201 +++++ .../lib/Cake/Test/Case/Model/ModelWriteTest.php | 6877 +++++++++++++++ .../Model/Validator/CakeValidationRuleTest.php | 155 + .../Case/Model/Validator/CakeValidationSetTest.php | 321 + .../lib/Cake/Test/Case/Model/models.php | 4989 +++++++++++ .../lib/Cake/Test/Case/Network/CakeRequestTest.php | 1890 ++++ .../Cake/Test/Case/Network/CakeResponseTest.php | 1009 +++ .../lib/Cake/Test/Case/Network/CakeSocketTest.php | 217 + .../Cake/Test/Case/Network/Email/CakeEmailTest.php | 1793 ++++ .../Test/Case/Network/Email/DebugTransportTest.php | 77 + .../Test/Case/Network/Email/SmtpTransportTest.php | 265 + .../Case/Network/Http/BasicAuthenticationTest.php | 64 + .../Case/Network/Http/DigestAuthenticationTest.php | 195 + .../Test/Case/Network/Http/HttpResponseTest.php | 558 ++ .../Cake/Test/Case/Network/Http/HttpSocketTest.php | 1629 ++++ .../lib/Cake/Test/Case/Routing/DispatcherTest.php | 1746 ++++ .../Case/Routing/Filter/AssetDispatcherTest.php | 124 + .../Cake/Test/Case/Routing/Route/CakeRouteTest.php | 883 ++ .../Case/Routing/Route/PluginShortRouteTest.php | 72 + .../Test/Case/Routing/Route/RedirectRouteTest.php | 107 + .../lib/Cake/Test/Case/Routing/RouterTest.php | 2669 ++++++ .../Cake/Test/Case/TestSuite/CakeTestCaseTest.php | 342 + .../Test/Case/TestSuite/CakeTestFixtureTest.php | 499 ++ .../Cake/Test/Case/TestSuite/CakeTestSuiteTest.php | 104 + .../Test/Case/TestSuite/ControllerTestCaseTest.php | 564 ++ .../Test/Case/TestSuite/HtmlCoverageReportTest.php | 231 + .../lib/Cake/Test/Case/Utility/CakeNumberTest.php | 526 ++ .../lib/Cake/Test/Case/Utility/CakeTimeTest.php | 1052 +++ .../Cake/Test/Case/Utility/ClassRegistryTest.php | 349 + .../lib/Cake/Test/Case/Utility/DebuggerTest.php | 499 ++ .../lib/Cake/Test/Case/Utility/FileTest.php | 556 ++ .../lib/Cake/Test/Case/Utility/FolderTest.php | 937 ++ .../lib/Cake/Test/Case/Utility/HashTest.php | 2151 +++++ .../lib/Cake/Test/Case/Utility/InflectorTest.php | 440 + .../Test/Case/Utility/ObjectCollectionTest.php | 595 ++ .../lib/Cake/Test/Case/Utility/SanitizeTest.php | 462 + .../lib/Cake/Test/Case/Utility/SecurityTest.php | 207 + .../lib/Cake/Test/Case/Utility/SetTest.php | 3542 ++++++++ .../lib/Cake/Test/Case/Utility/StringTest.php | 650 ++ .../lib/Cake/Test/Case/Utility/ValidationTest.php | 2217 +++++ .../lib/Cake/Test/Case/Utility/XmlTest.php | 1064 +++ .../Cake/Test/Case/View/Helper/CacheHelperTest.php | 650 ++ .../Cake/Test/Case/View/Helper/FormHelperTest.php | 8004 +++++++++++++++++ .../Cake/Test/Case/View/Helper/HtmlHelperTest.php | 1910 ++++ .../Case/View/Helper/JqueryEngineHelperTest.php | 373 + .../Cake/Test/Case/View/Helper/JsHelperTest.php | 928 ++ .../Case/View/Helper/MootoolsEngineHelperTest.php | 378 + .../Test/Case/View/Helper/NumberHelperTest.php | 107 + .../Test/Case/View/Helper/PaginatorHelperTest.php | 2501 ++++++ .../Case/View/Helper/PrototypeEngineHelperTest.php | 386 + .../Cake/Test/Case/View/Helper/RssHelperTest.php | 720 ++ .../Test/Case/View/Helper/SessionHelperTest.php | 192 + .../Cake/Test/Case/View/Helper/TextHelperTest.php | 301 + .../Cake/Test/Case/View/Helper/TimeHelperTest.php | 170 + .../Cake/Test/Case/View/HelperCollectionTest.php | 188 + .../lib/Cake/Test/Case/View/HelperTest.php | 941 ++ .../lib/Cake/Test/Case/View/JsonViewTest.php | 101 + .../lib/Cake/Test/Case/View/MediaViewTest.php | 402 + .../lib/Cake/Test/Case/View/ScaffoldViewTest.php | 463 + .../lib/Cake/Test/Case/View/ThemeViewTest.php | 265 + .../lib/Cake/Test/Case/View/ViewTest.php | 1448 +++ .../lib/Cake/Test/Case/View/XmlViewTest.php | 130 + .../lib/Cake/Test/Fixture/AccountFixture.php | 57 + .../lib/Cake/Test/Fixture/AcoActionFixture.php | 55 + .../lib/Cake/Test/Fixture/AcoFixture.php | 68 + .../lib/Cake/Test/Fixture/AcoTwoFixture.php | 66 + .../lib/Cake/Test/Fixture/AdFixture.php | 63 + .../lib/Cake/Test/Fixture/AdvertisementFixture.php | 55 + .../lib/Cake/Test/Fixture/AfterTreeFixture.php | 62 + .../Cake/Test/Fixture/AnotherArticleFixture.php | 56 + .../lib/Cake/Test/Fixture/AppleFixture.php | 64 + .../lib/Cake/Test/Fixture/ArmorFixture.php | 66 + .../lib/Cake/Test/Fixture/ArmorsPlayerFixture.php | 67 + .../lib/Cake/Test/Fixture/AroFixture.php | 60 + .../lib/Cake/Test/Fixture/AroTwoFixture.php | 66 + .../lib/Cake/Test/Fixture/ArosAcoFixture.php | 55 + .../lib/Cake/Test/Fixture/ArosAcoTwoFixture.php | 76 + .../Cake/Test/Fixture/ArticleFeaturedFixture.php | 59 + .../Test/Fixture/ArticleFeaturedsTagsFixture.php | 44 + .../lib/Cake/Test/Fixture/ArticleFixture.php | 60 + .../lib/Cake/Test/Fixture/ArticlesTagFixture.php | 56 + .../lib/Cake/Test/Fixture/AssertTagsTestCase.php | 118 + .../lib/Cake/Test/Fixture/AttachmentFixture.php | 55 + .../Test/Fixture/AuthUserCustomFieldFixture.php | 60 + .../lib/Cake/Test/Fixture/AuthUserFixture.php | 60 + .../lib/Cake/Test/Fixture/AuthorFixture.php | 58 + .../lib/Cake/Test/Fixture/BakeArticleFixture.php | 55 + .../Test/Fixture/BakeArticlesBakeTagFixture.php | 51 + .../lib/Cake/Test/Fixture/BakeCommentFixture.php | 55 + .../lib/Cake/Test/Fixture/BakeTagFixture.php | 52 + .../lib/Cake/Test/Fixture/BasketFixture.php | 56 + .../lib/Cake/Test/Fixture/BidFixture.php | 57 + .../lib/Cake/Test/Fixture/BiddingFixture.php | 56 + .../Cake/Test/Fixture/BiddingMessageFixture.php | 55 + .../lib/Cake/Test/Fixture/BinaryTestFixture.php | 50 + .../lib/Cake/Test/Fixture/BookFixture.php | 56 + .../Cake/Test/Fixture/CacheTestModelFixture.php | 44 + .../lib/Cake/Test/Fixture/CallbackFixture.php | 57 + .../lib/Cake/Test/Fixture/CampaignFixture.php | 55 + .../lib/Cake/Test/Fixture/CategoryFixture.php | 62 + .../Cake/Test/Fixture/CategoryThreadFixture.php | 61 + .../lib/Cake/Test/Fixture/CdFixture.php | 54 + .../lib/Cake/Test/Fixture/CommentFixture.php | 62 + .../Cake/Test/Fixture/ContentAccountFixture.php | 60 + .../lib/Cake/Test/Fixture/ContentFixture.php | 57 + .../Cake/Test/Fixture/CounterCachePostFixture.php | 41 + ...ounterCachePostNonstandardPrimaryKeyFixture.php | 40 + .../Cake/Test/Fixture/CounterCacheUserFixture.php | 40 + ...ounterCacheUserNonstandardPrimaryKeyFixture.php | 39 + .../lib/Cake/Test/Fixture/DataTestFixture.php | 60 + .../lib/Cake/Test/Fixture/DatatypeFixture.php | 53 + .../lib/Cake/Test/Fixture/DependencyFixture.php | 53 + .../lib/Cake/Test/Fixture/DeviceFixture.php | 56 + .../Test/Fixture/DeviceTypeCategoryFixture.php | 52 + .../lib/Cake/Test/Fixture/DeviceTypeFixture.php | 59 + .../Cake/Test/Fixture/DocumentDirectoryFixture.php | 52 + .../lib/Cake/Test/Fixture/DocumentFixture.php | 53 + .../lib/Cake/Test/Fixture/DomainFixture.php | 65 + .../lib/Cake/Test/Fixture/DomainsSiteFixture.php | 66 + .../Test/Fixture/ExteriorTypeCategoryFixture.php | 53 + .../lib/Cake/Test/Fixture/FeatureSetFixture.php | 52 + .../lib/Cake/Test/Fixture/FeaturedFixture.php | 58 + .../lib/Cake/Test/Fixture/FilmFileFixture.php | 53 + .../lib/Cake/Test/Fixture/FixturizedTestCase.php | 60 + .../lib/Cake/Test/Fixture/FlagTreeFixture.php | 51 + .../lib/Cake/Test/Fixture/FruitFixture.php | 58 + .../lib/Cake/Test/Fixture/FruitsUuidTagFixture.php | 55 + .../Cake/Test/Fixture/GroupUpdateAllFixture.php | 60 + .../lib/Cake/Test/Fixture/GuildFixture.php | 54 + .../lib/Cake/Test/Fixture/GuildsPlayerFixture.php | 57 + .../lib/Cake/Test/Fixture/HomeFixture.php | 57 + .../lib/Cake/Test/Fixture/ImageFixture.php | 56 + .../lib/Cake/Test/Fixture/InnoFixture.php | 57 + .../lib/Cake/Test/Fixture/ItemFixture.php | 59 + .../Cake/Test/Fixture/ItemsPortfolioFixture.php | 58 + .../lib/Cake/Test/Fixture/JoinABFixture.php | 58 + .../lib/Cake/Test/Fixture/JoinACFixture.php | 58 + .../lib/Cake/Test/Fixture/JoinAFixture.php | 57 + .../lib/Cake/Test/Fixture/JoinBFixture.php | 56 + .../lib/Cake/Test/Fixture/JoinCFixture.php | 56 + .../lib/Cake/Test/Fixture/JoinThingFixture.php | 58 + .../lib/Cake/Test/Fixture/MessageFixture.php | 55 + .../Test/Fixture/MyCategoriesMyProductsFixture.php | 55 + .../Test/Fixture/MyCategoriesMyUsersFixture.php | 55 + .../lib/Cake/Test/Fixture/MyCategoryFixture.php | 54 + .../lib/Cake/Test/Fixture/MyProductFixture.php | 53 + .../lib/Cake/Test/Fixture/MyUserFixture.php | 53 + .../lib/Cake/Test/Fixture/NodeFixture.php | 55 + .../lib/Cake/Test/Fixture/NumberTreeFixture.php | 50 + .../lib/Cake/Test/Fixture/NumberTreeTwoFixture.php | 51 + .../Cake/Test/Fixture/NumericArticleFixture.php | 55 + .../Cake/Test/Fixture/OverallFavoriteFixture.php | 55 + .../lib/Cake/Test/Fixture/PersonFixture.php | 64 + .../lib/Cake/Test/Fixture/PlayerFixture.php | 57 + .../lib/Cake/Test/Fixture/PortfolioFixture.php | 55 + .../lib/Cake/Test/Fixture/PostFixture.php | 59 + .../lib/Cake/Test/Fixture/PostsTagFixture.php | 56 + .../lib/Cake/Test/Fixture/PrefixTestFixture.php | 37 + .../lib/Cake/Test/Fixture/PrimaryModelFixture.php | 52 + .../lib/Cake/Test/Fixture/ProductFixture.php | 61 + .../Cake/Test/Fixture/ProductUpdateAllFixture.php | 65 + .../lib/Cake/Test/Fixture/ProjectFixture.php | 54 + .../lib/Cake/Test/Fixture/SampleFixture.php | 56 + .../Cake/Test/Fixture/SecondaryModelFixture.php | 52 + .../lib/Cake/Test/Fixture/SessionFixture.php | 51 + .../lib/Cake/Test/Fixture/SiteFixture.php | 61 + .../lib/Cake/Test/Fixture/SomethingElseFixture.php | 58 + .../lib/Cake/Test/Fixture/SomethingFixture.php | 58 + .../lib/Cake/Test/Fixture/StoriesTagFixture.php | 53 + .../lib/Cake/Test/Fixture/StoryFixture.php | 53 + .../lib/Cake/Test/Fixture/SyfileFixture.php | 59 + .../lib/Cake/Test/Fixture/TagFixture.php | 56 + .../Cake/Test/Fixture/TestPluginArticleFixture.php | 59 + .../Cake/Test/Fixture/TestPluginCommentFixture.php | 62 + .../Cake/Test/Fixture/ThePaperMonkiesFixture.php | 50 + .../lib/Cake/Test/Fixture/ThreadFixture.php | 55 + .../Cake/Test/Fixture/TranslateArticleFixture.php | 80 + .../lib/Cake/Test/Fixture/TranslateFixture.php | 80 + .../Cake/Test/Fixture/TranslateTableFixture.php | 63 + .../Test/Fixture/TranslateWithPrefixFixture.php | 84 + .../Cake/Test/Fixture/TranslatedArticleFixture.php | 57 + .../Cake/Test/Fixture/TranslatedItemFixture.php | 55 + .../Test/Fixture/UnconventionalTreeFixture.php | 49 + .../Cake/Test/Fixture/UnderscoreFieldFixture.php | 59 + .../lib/Cake/Test/Fixture/UserFixture.php | 58 + .../lib/Cake/Test/Fixture/UuidFixture.php | 58 + .../lib/Cake/Test/Fixture/UuidTagFixture.php | 53 + .../lib/Cake/Test/Fixture/UuidTreeFixture.php | 47 + .../lib/Cake/Test/Fixture/UuiditemFixture.php | 58 + .../Test/Fixture/UuiditemsUuidportfolioFixture.php | 56 + .../UuiditemsUuidportfolioNumericidFixture.php | 56 + .../lib/Cake/Test/Fixture/UuidportfolioFixture.php | 53 + .../lib/Cake/Test/Fixture/rss.xml | 33 + .../lib/Cake/Test/Fixture/sample.xml | 9 + .../lib/Cake/Test/Fixture/soap_request.xml | 12 + .../lib/Cake/Test/Fixture/soap_response.xml | 12 + .../lib/Cake/Test/test_app/Config/acl.ini.php | 60 + .../lib/Cake/Test/test_app/Config/acl.php | 74 + .../lib/Cake/Test/test_app/Config/empty.php | 2 + .../Test/test_app/Config/htmlhelper_minimized.ini | 2 + .../Cake/Test/test_app/Config/htmlhelper_tags.php | 8 + .../lib/Cake/Test/test_app/Config/nested.ini | 17 + .../lib/Cake/Test/test_app/Config/no_section.ini | 2 + .../lib/Cake/Test/test_app/Config/routes.php | 23 + .../lib/Cake/Test/test_app/Config/var_test.php | 12 + .../lib/Cake/Test/test_app/Config/var_test2.php | 13 + .../Test/test_app/Console/Command/SampleShell.php | 29 + .../Cake/Test/test_app/Console/Command/Task/empty | 0 .../Console/Templates/test/classes/test_object.ctp | 2 + .../Console/Templates/test/views/admin_edit.ctp | 1 + .../Test/test_app/Controller/AppController.php | 36 + .../Cake/Test/test_app/Controller/Component/empty | 0 .../Test/test_app/Controller/PagesController.php | 80 + .../Controller/TestAppsErrorController.php | 14 + .../test_app/Controller/TestsAppsController.php | 48 + .../Controller/TestsAppsPostsController.php | 73 + .../test_app/Error/TestAppsExceptionRenderer.php | 21 + .../Lib/Cache/Engine/TestAppCacheEngine.php | 44 + .../lib/Cake/Test/test_app/Lib/Library.php | 20 + .../Test/test_app/Lib/Log/Engine/TestAppLog.php | 27 + .../Test/test_app/Lib/Utility/TestUtilityClass.php | 20 + .../Locale/cache_test_po/LC_MESSAGES/default.po | 5 + .../Locale/cache_test_po/LC_MESSAGES/dom1.po | 8 + .../Locale/cache_test_po/LC_MESSAGES/dom2.po | 8 + .../Locale/eng/LC_MESSAGES/validation_messages.po | 5 + .../lib/Cake/Test/test_app/Locale/ja_jp/LC_TIME | 48 + .../Test/test_app/Locale/po/LC_MESSAGES/default.po | 76 + .../Test/test_app/Locale/po/LC_MONETARY/default.po | 18 + .../lib/Cake/Test/test_app/Locale/po/LC_TIME | 60 + .../test_app/Locale/rule_0_mo/LC_MESSAGES/core.mo | Bin 0 -> 673 bytes .../Locale/rule_0_mo/LC_MESSAGES/default.mo | Bin 0 -> 617 bytes .../test_app/Locale/rule_0_po/LC_MESSAGES/core.po | 21 + .../Locale/rule_0_po/LC_MESSAGES/default.po | 24 + .../test_app/Locale/rule_10_mo/LC_MESSAGES/core.mo | Bin 0 -> 845 bytes .../Locale/rule_10_mo/LC_MESSAGES/default.mo | Bin 0 -> 759 bytes .../test_app/Locale/rule_10_po/LC_MESSAGES/core.po | 24 + .../Locale/rule_10_po/LC_MESSAGES/default.po | 27 + .../test_app/Locale/rule_11_mo/LC_MESSAGES/core.mo | Bin 0 -> 858 bytes .../Locale/rule_11_mo/LC_MESSAGES/default.mo | Bin 0 -> 762 bytes .../test_app/Locale/rule_11_po/LC_MESSAGES/core.po | 25 + .../Locale/rule_11_po/LC_MESSAGES/default.po | 25 + .../test_app/Locale/rule_12_mo/LC_MESSAGES/core.mo | Bin 0 -> 821 bytes .../Locale/rule_12_mo/LC_MESSAGES/default.mo | Bin 0 -> 735 bytes .../test_app/Locale/rule_12_po/LC_MESSAGES/core.po | 24 + .../Locale/rule_12_po/LC_MESSAGES/default.po | 24 + .../test_app/Locale/rule_13_mo/LC_MESSAGES/core.mo | Bin 0 -> 865 bytes .../Locale/rule_13_mo/LC_MESSAGES/default.mo | Bin 0 -> 779 bytes .../test_app/Locale/rule_13_po/LC_MESSAGES/core.po | 24 + .../Locale/rule_13_po/LC_MESSAGES/default.po | 24 + .../test_app/Locale/rule_14_mo/LC_MESSAGES/core.mo | Bin 0 -> 769 bytes .../Locale/rule_14_mo/LC_MESSAGES/default.mo | Bin 0 -> 693 bytes .../test_app/Locale/rule_14_po/LC_MESSAGES/core.po | 23 + .../Locale/rule_14_po/LC_MESSAGES/default.po | 23 + .../test_app/Locale/rule_1_mo/LC_MESSAGES/core.mo | Bin 0 -> 704 bytes .../Locale/rule_1_mo/LC_MESSAGES/default.mo | Bin 0 -> 638 bytes .../test_app/Locale/rule_1_po/LC_MESSAGES/core.po | 22 + .../Locale/rule_1_po/LC_MESSAGES/default.po | 25 + .../test_app/Locale/rule_2_mo/LC_MESSAGES/core.mo | Bin 0 -> 699 bytes .../Locale/rule_2_mo/LC_MESSAGES/default.mo | Bin 0 -> 633 bytes .../test_app/Locale/rule_2_po/LC_MESSAGES/core.po | 22 + .../Locale/rule_2_po/LC_MESSAGES/default.po | 25 + .../test_app/Locale/rule_3_mo/LC_MESSAGES/core.mo | Bin 0 -> 790 bytes .../Locale/rule_3_mo/LC_MESSAGES/default.mo | Bin 0 -> 714 bytes .../test_app/Locale/rule_3_po/LC_MESSAGES/core.po | 23 + .../Locale/rule_3_po/LC_MESSAGES/default.po | 26 + .../test_app/Locale/rule_4_mo/LC_MESSAGES/core.mo | Bin 0 -> 758 bytes .../Locale/rule_4_mo/LC_MESSAGES/default.mo | Bin 0 -> 682 bytes .../test_app/Locale/rule_4_po/LC_MESSAGES/core.po | 23 + .../Locale/rule_4_po/LC_MESSAGES/default.po | 26 + .../test_app/Locale/rule_5_mo/LC_MESSAGES/core.mo | Bin 0 -> 806 bytes .../Locale/rule_5_mo/LC_MESSAGES/default.mo | Bin 0 -> 658 bytes .../test_app/Locale/rule_5_po/LC_MESSAGES/core.po | 23 + .../Locale/rule_5_po/LC_MESSAGES/default.po | 24 + .../test_app/Locale/rule_6_mo/LC_MESSAGES/core.mo | Bin 0 -> 841 bytes .../Locale/rule_6_mo/LC_MESSAGES/default.mo | Bin 0 -> 765 bytes .../test_app/Locale/rule_6_po/LC_MESSAGES/core.po | 23 + .../Locale/rule_6_po/LC_MESSAGES/default.po | 26 + .../test_app/Locale/rule_7_mo/LC_MESSAGES/core.mo | Bin 0 -> 850 bytes .../Locale/rule_7_mo/LC_MESSAGES/default.mo | Bin 0 -> 774 bytes .../test_app/Locale/rule_7_po/LC_MESSAGES/core.po | 23 + .../Locale/rule_7_po/LC_MESSAGES/default.po | 26 + .../test_app/Locale/rule_8_mo/LC_MESSAGES/core.mo | Bin 0 -> 774 bytes .../Locale/rule_8_mo/LC_MESSAGES/default.mo | Bin 0 -> 698 bytes .../test_app/Locale/rule_8_po/LC_MESSAGES/core.po | 23 + .../Locale/rule_8_po/LC_MESSAGES/default.po | 26 + .../test_app/Locale/rule_9_mo/LC_MESSAGES/core.mo | Bin 0 -> 819 bytes .../Locale/rule_9_mo/LC_MESSAGES/default.mo | Bin 0 -> 743 bytes .../test_app/Locale/rule_9_po/LC_MESSAGES/core.po | 23 + .../Locale/rule_9_po/LC_MESSAGES/default.po | 26 + .../Cake/Test/test_app/Locale/time_test/LC_TIME | 42 + .../lib/Cake/Test/test_app/Model/AppModel.php | 35 + .../Behavior/PersisterOneBehaviorBehavior.php | 29 + .../Behavior/PersisterTwoBehaviorBehavior.php | 29 + .../lib/Cake/Test/test_app/Model/Comment.php | 27 + .../Model/Datasource/Database/TestLocalDriver.php | 5 + .../Model/Datasource/Session/TestAppLibSession.php | 30 + .../test_app/Model/Datasource/Test2OtherSource.php | 27 + .../Test/test_app/Model/Datasource/Test2Source.php | 27 + .../lib/Cake/Test/test_app/Model/PersisterOne.php | 60 + .../lib/Cake/Test/test_app/Model/PersisterTwo.php | 31 + .../lib/Cake/Test/test_app/Model/Post.php | 27 + .../test_app/Plugin/PluginJs/Config/bootstrap.php | 2 + .../Plugin/PluginJs/webroot/js/one/plugin_one.js | 1 + .../Plugin/PluginJs/webroot/js/plugin_js.js | 1 + .../Plugin/TestPlugin/Config/Schema/schema.php | 35 + .../Plugin/TestPlugin/Config/bootstrap.php | 2 + .../Plugin/TestPlugin/Config/custom_config.php | 2 + .../test_app/Plugin/TestPlugin/Config/load.php | 19 + .../Plugin/TestPlugin/Config/more.load.php | 19 + .../test_app/Plugin/TestPlugin/Config/routes.php | 2 + .../TestPlugin/Console/Command/ExampleShell.php | 29 + .../Console/Command/Task/OtherTaskTask.php | 21 + .../Plugin/TestPlugin/Console/Templates/empty | 0 .../Controller/Component/OtherComponent.php | 20 + .../Controller/Component/PluginsComponent.php | 23 + .../Controller/Component/TestPluginComponent.php | 23 + .../Component/TestPluginOtherComponent.php | 20 + .../Controller/TestPluginAppController.php | 20 + .../TestPlugin/Controller/TestPluginController.php | 31 + .../TestPlugin/Controller/TestsController.php | 37 + .../Lib/Cache/Engine/TestPluginCacheEngine.php | 41 + .../Lib/Custom/Package/CustomLibClass.php | 20 + .../Lib/Error/TestPluginExceptionRenderer.php | 35 + .../TestPlugin/Lib/Log/Engine/TestPluginLog.php | 28 + .../Lib/Routing/Filter/Test2DispatcherFilter.php | 33 + .../Lib/Routing/Filter/TestDispatcherFilter.php | 31 + .../Plugin/TestPlugin/Lib/TestPluginLibrary.php | 20 + .../TestPlugin/Lib/TestPluginOtherLibrary.php | 20 + .../Locale/po/LC_MESSAGES/test_plugin.po | 50 + .../Locale/po/LC_MONETARY/test_plugin.po | 22 + .../Behavior/TestPluginPersisterOneBehavior.php | 31 + .../Behavior/TestPluginPersisterTwoBehavior.php | 31 + .../Model/Datasource/Database/DboDummy.php | 10 + .../Model/Datasource/Database/TestDriver.php | 3 + .../Model/Datasource/Session/TestPluginSession.php | 29 + .../Model/Datasource/TestOtherSource.php | 27 + .../TestPlugin/Model/Datasource/TestSource.php | 29 + .../Plugin/TestPlugin/Model/TestPluginAppModel.php | 20 + .../Plugin/TestPlugin/Model/TestPluginAuthUser.php | 41 + .../Plugin/TestPlugin/Model/TestPluginAuthors.php | 28 + .../Plugin/TestPlugin/Model/TestPluginComment.php | 28 + .../Plugin/TestPlugin/Model/TestPluginPost.php | 71 + .../Plugin/TestPlugin/Utility/TestPluginEngine.php | 5 + .../TestPlugin/Vendor/Example/ExampleExample.php | 4 + .../TestPlugin/Vendor/sample/sample_plugin.php | 20 + .../test_app/Plugin/TestPlugin/Vendor/welcome.php | 20 + .../TestPlugin/View/Elements/plugin_element.ctp | 1 + .../View/Elements/sub_dir/sub_element.ctp | 1 + .../View/Elements/test_plugin_element.ctp | 1 + .../Plugin/TestPlugin/View/Elements/translate.ctp | 1 + .../View/Emails/text/test_plugin_tpl.ctp | 1 + .../TestPlugin/View/Helper/OtherHelperHelper.php | 21 + .../TestPlugin/View/Helper/PluggedHelperHelper.php | 22 + .../TestPlugin/View/Helper/TestPluginAppHelper.php | 4 + .../View/Layouts/Emails/text/plug_default.ctp | 4 + .../Plugin/TestPlugin/View/Layouts/default.ctp | 1 + .../Plugin/TestPlugin/View/Tests/index.ctp | 1 + .../Plugin/TestPlugin/View/Tests/scaffold.form.ctp | 1 + .../TestPlugin/webroot/css/test_plugin_asset.css | 1 + .../Plugin/TestPlugin/webroot/css/theme_one.htc | 1 + .../TestPlugin/webroot/css/unknown.extension | 1 + .../TestPlugin/webroot/flash/plugin_test.swf | 1 + .../Plugin/TestPlugin/webroot/img/cake.icon.gif | Bin 0 -> 233 bytes .../TestPlugin/webroot/js/test_plugin/test.js | 1 + .../Plugin/TestPlugin/webroot/pdfs/plugin_test.pdf | 1 + .../test_app/Plugin/TestPlugin/webroot/root.js | 1 + .../Plugin/TestPluginTwo/Config/bootstrap.php | 2 + .../TestPluginTwo/Console/Command/ExampleShell.php | 29 + .../TestPluginTwo/Console/Command/Task/empty | 0 .../TestPluginTwo/Console/Command/WelcomeShell.php | 29 + .../Plugin/TestPluginTwo/Console/Templates/empty | 0 .../Cake/Test/test_app/Utility/TestAppEngine.php | 5 + .../lib/Cake/Test/test_app/Vendor/Test/MyTest.php | 20 + .../lib/Cake/Test/test_app/Vendor/Test/hello.php | 20 + .../Cake/Test/test_app/Vendor/css/test_asset.css | 1 + .../lib/Cake/Test/test_app/Vendor/img/test.jpg | Bin 0 -> 5308 bytes .../lib/Cake/Test/test_app/Vendor/img/test_2.JPG | Bin 0 -> 5308 bytes .../Vendor/sample/configure_test_vendor_sample.php | 20 + .../Test/test_app/Vendor/somename/some.name.php | 20 + .../lib/Cake/Test/test_app/Vendor/welcome.php | 20 + .../test_app/View/Elements/extended_element.ctp | 2 + .../View/Elements/extended_missing_element.ctp | 2 + .../Cake/Test/test_app/View/Elements/html_call.ctp | 3 + .../View/Elements/nocache/contains_nocache.ctp | 5 + .../Test/test_app/View/Elements/nocache/plain.ctp | 4 + .../Test/test_app/View/Elements/nocache/sub1.ctp | 8 + .../Test/test_app/View/Elements/nocache/sub2.ctp | 6 + .../Test/test_app/View/Elements/parent_element.ctp | 2 + .../Test/test_app/View/Elements/session_helper.ctp | 5 + .../Test/test_app/View/Elements/test_element.ctp | 1 + .../Test/test_app/View/Elements/test_element.xml | 1 + .../Test/test_app/View/Elements/type_check.ctp | 1 + .../Cake/Test/test_app/View/Emails/html/custom.ctp | 22 + .../Test/test_app/View/Emails/html/default.ctp | 25 + .../Cake/Test/test_app/View/Emails/html/image.ctp | 23 + .../Test/test_app/View/Emails/html/japanese.ctp | 22 + .../test_app/View/Emails/html/nested_element.ctp | 3 + .../Cake/Test/test_app/View/Emails/text/custom.ctp | 22 + .../test_app/View/Emails/text/custom_helper.ctp | 19 + .../Test/test_app/View/Emails/text/default.ctp | 19 + .../Test/test_app/View/Emails/text/japanese.ctp | 22 + .../Cake/Test/test_app/View/Emails/text/wide.ctp | 20 + .../Cake/Test/test_app/View/Errors/error400.ctp | 31 + .../Cake/Test/test_app/View/Errors/error500.ctp | 28 + .../Test/test_app/View/Helper/BananaHelper.php | 27 + .../test_app/View/Layouts/Emails/html/default.ctp | 31 + .../test_app/View/Layouts/Emails/html/japanese.ctp | 31 + .../test_app/View/Layouts/Emails/html/thin.ctp | 31 + .../test_app/View/Layouts/Emails/text/default.ctp | 22 + .../test_app/View/Layouts/Emails/text/japanese.ctp | 22 + .../lib/Cake/Test/test_app/View/Layouts/ajax.ctp | 19 + .../lib/Cake/Test/test_app/View/Layouts/ajax2.ctp | 22 + .../lib/Cake/Test/test_app/View/Layouts/banana.ctp | 5 + .../test_app/View/Layouts/cache_empty_sections.ctp | 13 + .../Test/test_app/View/Layouts/cache_layout.ctp | 31 + .../Cake/Test/test_app/View/Layouts/default.ctp | 58 + .../lib/Cake/Test/test_app/View/Layouts/flash.ctp | 37 + .../Cake/Test/test_app/View/Layouts/js/default.ctp | 2 + .../Test/test_app/View/Layouts/json/default.ctp | 1 + .../Test/test_app/View/Layouts/multi_cache.ctp | 39 + .../Test/test_app/View/Layouts/rss/default.ctp | 17 + .../Test/test_app/View/Layouts/xml/default.ctp | 2 + .../lib/Cake/Test/test_app/View/Pages/extract.ctp | 24 + .../lib/Cake/Test/test_app/View/Pages/home.ctp | 163 + .../Cake/Test/test_app/View/Pages/page.home.ctp | 2 + .../lib/Cake/Test/test_app/View/Posts/alt_ext.alt | 1 + .../test_app/View/Posts/cache_empty_sections.ctp | 2 + .../Cake/Test/test_app/View/Posts/cache_form.ctp | 14 + .../Test/test_app/View/Posts/extend_element.ctp | 3 + .../Cake/Test/test_app/View/Posts/extend_loop.ctp | 2 + .../Test/test_app/View/Posts/extend_loop_inner.ctp | 2 + .../test_app/View/Posts/extend_missing_element.ctp | 1 + .../Cake/Test/test_app/View/Posts/extend_self.ctp | 2 + .../Test/test_app/View/Posts/helper_overwrite.ctp | 4 + .../lib/Cake/Test/test_app/View/Posts/index.ctp | 1 + .../Cake/Test/test_app/View/Posts/json/index.ctp | 27 + .../Test/test_app/View/Posts/multiple_nocache.ctp | 15 + .../Test/test_app/View/Posts/nested_extends.ctp | 5 + .../View/Posts/nocache_multiple_element.ctp | 9 + .../Cake/Test/test_app/View/Posts/open_block.ctp | 3 + .../lib/Cake/Test/test_app/View/Posts/parent_1.ctp | 5 + .../lib/Cake/Test/test_app/View/Posts/parent_2.ctp | 3 + .../Cake/Test/test_app/View/Posts/parent_view.ctp | 2 + .../Test/test_app/View/Posts/scaffold.form.ctp | 1 + .../test_app/View/Posts/sequencial_nocache.ctp | 23 + .../Test/test_app/View/Posts/test_nocache_tags.ctp | 142 + .../Cake/Test/test_app/View/Posts/xml/index.ctp | 6 + .../lib/Cake/Test/test_app/View/Scaffolds/empty | 0 .../Cake/Test/test_app/View/TestsApps/index.ctp | 1 + .../Test/test_app/View/TestsApps/json/index.ctp | 1 + .../Themed/TestTheme/Elements/test_element.ctp | 1 + .../View/Themed/TestTheme/Emails/text/themed.ctp | 1 + .../View/Themed/TestTheme/Layouts/default.ctp | 2 + .../TestPlugin/Emails/text/test_plugin_tpl.ctp | 1 + .../Plugin/TestPlugin/Layouts/plugin_default.ctp | 1 + .../TestTheme/Plugin/TestPlugin/Tests/index.ctp | 1 + .../test_app/View/Themed/TestTheme/Posts/index.ctp | 1 + .../View/Themed/TestTheme/Posts/scaffold.index.ctp | 1 + .../View/Themed/TestTheme/Posts/themed.ctp | 4 + .../Themed/TestTheme/webroot/css/test_asset.css | 1 + .../Themed/TestTheme/webroot/css/theme_webroot.css | 1 + .../Themed/TestTheme/webroot/flash/theme_test.swf | 1 + .../Themed/TestTheme/webroot/img/cake.power.gif | Bin 0 -> 201 bytes .../View/Themed/TestTheme/webroot/img/test.jpg | Bin 0 -> 5308 bytes .../Themed/TestTheme/webroot/js/one/theme_one.js | 1 + .../View/Themed/TestTheme/webroot/js/theme.js | 1 + .../Themed/TestTheme/webroot/pdfs/theme_test.pdf | 1 + .../View/Themed/TestTheme/webroot/space image.text | 1 + .../lib/Cake/Test/test_app/tmp/dir_map | 2 + .../Cake/Test/test_app/webroot/img/cake.power.gif | Bin 0 -> 201 bytes .../webroot/theme/test_theme/css/theme_webroot.css | 1 + .../webroot/theme/test_theme/css/webroot_test.css | 1 + .../webroot/theme/test_theme/img/cake.power.gif | Bin 0 -> 201 bytes .../test_app/webroot/theme/test_theme/img/test.jpg | Bin 0 -> 5308 bytes 594 files changed, 149664 insertions(+) create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllBehaviorsTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllCacheTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllComponentsTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllConfigureTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllConsoleTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllControllerTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllCoreTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllDatabaseTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllErrorTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllEventTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllHelpersTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllI18nTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllLogTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllNetworkTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllRoutingTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllTestSuiteTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllTestsTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllUtilityTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllViewTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/BasicsTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Cache/CacheTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Cache/Engine/ApcEngineTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Cache/Engine/FileEngineTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Cache/Engine/MemcacheEngineTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Cache/Engine/RedisEngineTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Cache/Engine/WincacheEngineTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Cache/Engine/XcacheEngineTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Configure/IniReaderTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Configure/PhpReaderTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/AllConsoleLibsTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/AllConsoleTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/AllShellsTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/AllTasksTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/AclShellTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/ApiShellTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/BakeShellTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/CommandListShellTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/SchemaShellTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/Task/ControllerTaskTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/Task/DbConfigTaskTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/Task/ExtractTaskTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/Task/FixtureTaskTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/Task/ModelTaskTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/Task/PluginTaskTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/Task/ProjectTaskTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/Task/TemplateTaskTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/Task/TestTaskTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/Task/ViewTaskTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/TestShellTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/ConsoleErrorHandlerTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/ConsoleOptionParserTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/ConsoleOutputTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/HelpFormatterTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/ShellDispatcherTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/ShellTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/TaskCollectionTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/Acl/DbAclTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/Acl/IniAclTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/Acl/PhpAclTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/AclComponentTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/Auth/ActionsAuthorizeTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/Auth/BasicAuthenticateTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/Auth/ControllerAuthorizeTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/Auth/CrudAuthorizeTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/Auth/DigestAuthenticateTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/Auth/FormAuthenticateTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/AuthComponentTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/CookieComponentTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/EmailComponentTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/PaginatorComponentTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/RequestHandlerComponentTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/SecurityComponentTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/SessionComponentTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/ComponentCollectionTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/ComponentTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/ControllerMergeVarsTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/ControllerTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/PagesControllerTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/ScaffoldTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Core/AppTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Core/CakePluginTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Core/ConfigureTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Core/ObjectTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Error/ErrorHandlerTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Error/ExceptionRendererTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Event/CakeEventManagerTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Event/CakeEventTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/I18n/I18nTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/I18n/L10nTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/I18n/MultibyteTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Log/CakeLogTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Log/Engine/ConsoleLogTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Log/Engine/FileLogTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/AclNodeTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Behavior/AclBehaviorTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Behavior/ContainableBehaviorTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Behavior/TranslateBehaviorTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Behavior/TreeBehaviorAfterTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Behavior/TreeBehaviorNumberTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Behavior/TreeBehaviorScopedTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Behavior/TreeBehaviorTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Behavior/TreeBehaviorUuidTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/BehaviorCollectionTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/CakeSchemaTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/ConnectionManagerTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Datasource/CakeSessionTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Datasource/DataSourceTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Datasource/Database/MysqlTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Datasource/Database/PostgresTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Datasource/Database/SqliteTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Datasource/Database/SqlserverTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Datasource/DboSourceTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Datasource/Session/CacheSessionTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Datasource/Session/DatabaseSessionTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/ModelCrossSchemaHabtmTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/ModelDeleteTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/ModelIntegrationTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/ModelReadTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/ModelTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/ModelTestBase.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/ModelValidationTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/ModelWriteTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Validator/CakeValidationRuleTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Validator/CakeValidationSetTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/models.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Network/CakeRequestTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Network/CakeResponseTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Network/CakeSocketTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Network/Email/CakeEmailTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Network/Email/DebugTransportTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Network/Email/SmtpTransportTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Network/Http/BasicAuthenticationTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Network/Http/DigestAuthenticationTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Network/Http/HttpResponseTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Network/Http/HttpSocketTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Routing/DispatcherTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Routing/Filter/AssetDispatcherTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Routing/Route/CakeRouteTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Routing/Route/PluginShortRouteTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Routing/Route/RedirectRouteTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Routing/RouterTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/TestSuite/CakeTestCaseTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/TestSuite/CakeTestFixtureTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/TestSuite/CakeTestSuiteTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/TestSuite/ControllerTestCaseTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/TestSuite/HtmlCoverageReportTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Utility/CakeNumberTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Utility/CakeTimeTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Utility/ClassRegistryTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Utility/DebuggerTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Utility/FileTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Utility/FolderTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Utility/HashTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Utility/InflectorTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Utility/ObjectCollectionTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Utility/SanitizeTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Utility/SecurityTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Utility/SetTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Utility/StringTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Utility/ValidationTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Utility/XmlTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/View/Helper/CacheHelperTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/View/Helper/FormHelperTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/View/Helper/HtmlHelperTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/View/Helper/JqueryEngineHelperTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/View/Helper/JsHelperTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/View/Helper/MootoolsEngineHelperTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/View/Helper/NumberHelperTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/View/Helper/PaginatorHelperTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/View/Helper/PrototypeEngineHelperTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/View/Helper/RssHelperTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/View/Helper/SessionHelperTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/View/Helper/TextHelperTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/View/Helper/TimeHelperTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/View/HelperCollectionTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/View/HelperTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/View/JsonViewTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/View/MediaViewTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/View/ScaffoldViewTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/View/ThemeViewTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/View/ViewTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/View/XmlViewTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/AccountFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/AcoActionFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/AcoFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/AcoTwoFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/AdFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/AdvertisementFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/AfterTreeFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/AnotherArticleFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/AppleFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/ArmorFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/ArmorsPlayerFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/AroFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/AroTwoFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/ArosAcoFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/ArosAcoTwoFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/ArticleFeaturedFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/ArticleFeaturedsTagsFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/ArticleFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/ArticlesTagFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/AssertTagsTestCase.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/AttachmentFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/AuthUserCustomFieldFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/AuthUserFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/AuthorFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/BakeArticleFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/BakeArticlesBakeTagFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/BakeCommentFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/BakeTagFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/BasketFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/BidFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/BiddingFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/BiddingMessageFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/BinaryTestFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/BookFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/CacheTestModelFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/CallbackFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/CampaignFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/CategoryFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/CategoryThreadFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/CdFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/CommentFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/ContentAccountFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/ContentFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/CounterCachePostFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/CounterCachePostNonstandardPrimaryKeyFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/CounterCacheUserFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/CounterCacheUserNonstandardPrimaryKeyFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/DataTestFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/DatatypeFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/DependencyFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/DeviceFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/DeviceTypeCategoryFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/DeviceTypeFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/DocumentDirectoryFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/DocumentFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/DomainFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/DomainsSiteFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/ExteriorTypeCategoryFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/FeatureSetFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/FeaturedFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/FilmFileFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/FixturizedTestCase.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/FlagTreeFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/FruitFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/FruitsUuidTagFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/GroupUpdateAllFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/GuildFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/GuildsPlayerFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/HomeFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/ImageFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/InnoFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/ItemFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/ItemsPortfolioFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/JoinABFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/JoinACFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/JoinAFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/JoinBFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/JoinCFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/JoinThingFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/MessageFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/MyCategoriesMyProductsFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/MyCategoriesMyUsersFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/MyCategoryFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/MyProductFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/MyUserFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/NodeFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/NumberTreeFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/NumberTreeTwoFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/NumericArticleFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/OverallFavoriteFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/PersonFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/PlayerFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/PortfolioFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/PostFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/PostsTagFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/PrefixTestFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/PrimaryModelFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/ProductFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/ProductUpdateAllFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/ProjectFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/SampleFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/SecondaryModelFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/SessionFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/SiteFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/SomethingElseFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/SomethingFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/StoriesTagFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/StoryFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/SyfileFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/TagFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/TestPluginArticleFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/TestPluginCommentFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/ThePaperMonkiesFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/ThreadFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/TranslateArticleFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/TranslateFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/TranslateTableFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/TranslateWithPrefixFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/TranslatedArticleFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/TranslatedItemFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/UnconventionalTreeFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/UnderscoreFieldFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/UserFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/UuidFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/UuidTagFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/UuidTreeFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/UuiditemFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/UuiditemsUuidportfolioFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/UuiditemsUuidportfolioNumericidFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/UuidportfolioFixture.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/rss.xml create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/sample.xml create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/soap_request.xml create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Fixture/soap_response.xml create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Config/acl.ini.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Config/acl.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Config/empty.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Config/htmlhelper_minimized.ini create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Config/htmlhelper_tags.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Config/nested.ini create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Config/no_section.ini create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Config/routes.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Config/var_test.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Config/var_test2.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Console/Command/SampleShell.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Console/Command/Task/empty create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Console/Templates/test/classes/test_object.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Console/Templates/test/views/admin_edit.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Controller/AppController.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Controller/Component/empty create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Controller/PagesController.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Controller/TestAppsErrorController.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Controller/TestsAppsController.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Controller/TestsAppsPostsController.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Error/TestAppsExceptionRenderer.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Lib/Cache/Engine/TestAppCacheEngine.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Lib/Library.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Lib/Log/Engine/TestAppLog.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Lib/Utility/TestUtilityClass.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/cache_test_po/LC_MESSAGES/default.po create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/cache_test_po/LC_MESSAGES/dom1.po create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/cache_test_po/LC_MESSAGES/dom2.po create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/eng/LC_MESSAGES/validation_messages.po create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/ja_jp/LC_TIME create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/po/LC_MESSAGES/default.po create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/po/LC_MONETARY/default.po create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/po/LC_TIME create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/rule_0_mo/LC_MESSAGES/core.mo create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/rule_0_mo/LC_MESSAGES/default.mo create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/rule_0_po/LC_MESSAGES/core.po create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/rule_0_po/LC_MESSAGES/default.po create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/rule_10_mo/LC_MESSAGES/core.mo create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/rule_10_mo/LC_MESSAGES/default.mo create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/rule_10_po/LC_MESSAGES/core.po create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/rule_10_po/LC_MESSAGES/default.po create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/rule_11_mo/LC_MESSAGES/core.mo create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/rule_11_mo/LC_MESSAGES/default.mo create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/rule_11_po/LC_MESSAGES/core.po create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/rule_11_po/LC_MESSAGES/default.po create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/rule_12_mo/LC_MESSAGES/core.mo create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/rule_12_mo/LC_MESSAGES/default.mo create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/rule_12_po/LC_MESSAGES/core.po create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/rule_12_po/LC_MESSAGES/default.po create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/rule_13_mo/LC_MESSAGES/core.mo create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/rule_13_mo/LC_MESSAGES/default.mo create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/rule_13_po/LC_MESSAGES/core.po create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/rule_13_po/LC_MESSAGES/default.po create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/rule_14_mo/LC_MESSAGES/core.mo create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/rule_14_mo/LC_MESSAGES/default.mo create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/rule_14_po/LC_MESSAGES/core.po create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/rule_14_po/LC_MESSAGES/default.po create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/rule_1_mo/LC_MESSAGES/core.mo create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/rule_1_mo/LC_MESSAGES/default.mo create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/rule_1_po/LC_MESSAGES/core.po create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/rule_1_po/LC_MESSAGES/default.po create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/rule_2_mo/LC_MESSAGES/core.mo create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/rule_2_mo/LC_MESSAGES/default.mo create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/rule_2_po/LC_MESSAGES/core.po create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/rule_2_po/LC_MESSAGES/default.po create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/rule_3_mo/LC_MESSAGES/core.mo create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/rule_3_mo/LC_MESSAGES/default.mo create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/rule_3_po/LC_MESSAGES/core.po create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/rule_3_po/LC_MESSAGES/default.po create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/rule_4_mo/LC_MESSAGES/core.mo create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/rule_4_mo/LC_MESSAGES/default.mo create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/rule_4_po/LC_MESSAGES/core.po create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/rule_4_po/LC_MESSAGES/default.po create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/rule_5_mo/LC_MESSAGES/core.mo create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/rule_5_mo/LC_MESSAGES/default.mo create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/rule_5_po/LC_MESSAGES/core.po create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/rule_5_po/LC_MESSAGES/default.po create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/rule_6_mo/LC_MESSAGES/core.mo create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/rule_6_mo/LC_MESSAGES/default.mo create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/rule_6_po/LC_MESSAGES/core.po create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/rule_6_po/LC_MESSAGES/default.po create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/rule_7_mo/LC_MESSAGES/core.mo create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/rule_7_mo/LC_MESSAGES/default.mo create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/rule_7_po/LC_MESSAGES/core.po create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/rule_7_po/LC_MESSAGES/default.po create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/rule_8_mo/LC_MESSAGES/core.mo create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/rule_8_mo/LC_MESSAGES/default.mo create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/rule_8_po/LC_MESSAGES/core.po create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/rule_8_po/LC_MESSAGES/default.po create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/rule_9_mo/LC_MESSAGES/core.mo create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/rule_9_mo/LC_MESSAGES/default.mo create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/rule_9_po/LC_MESSAGES/core.po create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/rule_9_po/LC_MESSAGES/default.po create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Locale/time_test/LC_TIME create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Model/AppModel.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Model/Behavior/PersisterOneBehaviorBehavior.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Model/Behavior/PersisterTwoBehaviorBehavior.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Model/Comment.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Model/Datasource/Database/TestLocalDriver.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Model/Datasource/Session/TestAppLibSession.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Model/Datasource/Test2OtherSource.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Model/Datasource/Test2Source.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Model/PersisterOne.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Model/PersisterTwo.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Model/Post.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/PluginJs/Config/bootstrap.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/PluginJs/webroot/js/one/plugin_one.js create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/PluginJs/webroot/js/plugin_js.js create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/Config/Schema/schema.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/Config/bootstrap.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/Config/custom_config.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/Config/load.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/Config/more.load.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/Config/routes.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/Console/Command/ExampleShell.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/Console/Command/Task/OtherTaskTask.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/Console/Templates/empty create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/Controller/Component/OtherComponent.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/Controller/Component/PluginsComponent.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/Controller/Component/TestPluginComponent.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/Controller/Component/TestPluginOtherComponent.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/Controller/TestPluginAppController.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/Controller/TestPluginController.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/Controller/TestsController.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/Lib/Cache/Engine/TestPluginCacheEngine.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/Lib/Custom/Package/CustomLibClass.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/Lib/Error/TestPluginExceptionRenderer.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/Lib/Log/Engine/TestPluginLog.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/Lib/Routing/Filter/Test2DispatcherFilter.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/Lib/Routing/Filter/TestDispatcherFilter.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/Lib/TestPluginLibrary.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/Lib/TestPluginOtherLibrary.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/Locale/po/LC_MESSAGES/test_plugin.po create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/Locale/po/LC_MONETARY/test_plugin.po create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/Model/Behavior/TestPluginPersisterOneBehavior.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/Model/Behavior/TestPluginPersisterTwoBehavior.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/Model/Datasource/Database/DboDummy.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/Model/Datasource/Database/TestDriver.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/Model/Datasource/Session/TestPluginSession.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/Model/Datasource/TestOtherSource.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/Model/Datasource/TestSource.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/Model/TestPluginAppModel.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/Model/TestPluginAuthUser.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/Model/TestPluginAuthors.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/Model/TestPluginComment.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/Model/TestPluginPost.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/Utility/TestPluginEngine.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/Vendor/Example/ExampleExample.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/Vendor/sample/sample_plugin.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/Vendor/welcome.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/View/Elements/plugin_element.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/View/Elements/sub_dir/sub_element.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/View/Elements/test_plugin_element.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/View/Elements/translate.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/View/Emails/text/test_plugin_tpl.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/View/Helper/OtherHelperHelper.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/View/Helper/PluggedHelperHelper.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/View/Helper/TestPluginAppHelper.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/View/Layouts/Emails/text/plug_default.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/View/Layouts/default.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/View/Tests/index.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/View/Tests/scaffold.form.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/webroot/css/test_plugin_asset.css create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/webroot/css/theme_one.htc create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/webroot/css/unknown.extension create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/webroot/flash/plugin_test.swf create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/webroot/img/cake.icon.gif create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/webroot/js/test_plugin/test.js create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/webroot/pdfs/plugin_test.pdf create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPlugin/webroot/root.js create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPluginTwo/Config/bootstrap.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPluginTwo/Console/Command/ExampleShell.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPluginTwo/Console/Command/Task/empty create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPluginTwo/Console/Command/WelcomeShell.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Plugin/TestPluginTwo/Console/Templates/empty create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Utility/TestAppEngine.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Vendor/Test/MyTest.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Vendor/Test/hello.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Vendor/css/test_asset.css create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Vendor/img/test.jpg create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Vendor/img/test_2.JPG create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Vendor/sample/configure_test_vendor_sample.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Vendor/somename/some.name.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/Vendor/welcome.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Elements/extended_element.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Elements/extended_missing_element.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Elements/html_call.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Elements/nocache/contains_nocache.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Elements/nocache/plain.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Elements/nocache/sub1.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Elements/nocache/sub2.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Elements/parent_element.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Elements/session_helper.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Elements/test_element.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Elements/test_element.xml create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Elements/type_check.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Emails/html/custom.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Emails/html/default.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Emails/html/image.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Emails/html/japanese.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Emails/html/nested_element.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Emails/text/custom.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Emails/text/custom_helper.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Emails/text/default.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Emails/text/japanese.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Emails/text/wide.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Errors/error400.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Errors/error500.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Helper/BananaHelper.php create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Layouts/Emails/html/default.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Layouts/Emails/html/japanese.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Layouts/Emails/html/thin.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Layouts/Emails/text/default.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Layouts/Emails/text/japanese.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Layouts/ajax.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Layouts/ajax2.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Layouts/banana.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Layouts/cache_empty_sections.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Layouts/cache_layout.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Layouts/default.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Layouts/flash.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Layouts/js/default.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Layouts/json/default.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Layouts/multi_cache.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Layouts/rss/default.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Layouts/xml/default.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Pages/extract.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Pages/home.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Pages/page.home.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Posts/alt_ext.alt create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Posts/cache_empty_sections.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Posts/cache_form.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Posts/extend_element.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Posts/extend_loop.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Posts/extend_loop_inner.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Posts/extend_missing_element.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Posts/extend_self.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Posts/helper_overwrite.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Posts/index.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Posts/json/index.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Posts/multiple_nocache.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Posts/nested_extends.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Posts/nocache_multiple_element.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Posts/open_block.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Posts/parent_1.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Posts/parent_2.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Posts/parent_view.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Posts/scaffold.form.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Posts/sequencial_nocache.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Posts/test_nocache_tags.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Posts/xml/index.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Scaffolds/empty create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/TestsApps/index.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/TestsApps/json/index.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Themed/TestTheme/Elements/test_element.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Themed/TestTheme/Emails/text/themed.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Themed/TestTheme/Layouts/default.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Themed/TestTheme/Plugin/TestPlugin/Emails/text/test_plugin_tpl.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Themed/TestTheme/Plugin/TestPlugin/Layouts/plugin_default.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Themed/TestTheme/Plugin/TestPlugin/Tests/index.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Themed/TestTheme/Posts/index.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Themed/TestTheme/Posts/scaffold.index.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Themed/TestTheme/Posts/themed.ctp create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Themed/TestTheme/webroot/css/test_asset.css create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Themed/TestTheme/webroot/css/theme_webroot.css create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Themed/TestTheme/webroot/flash/theme_test.swf create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Themed/TestTheme/webroot/img/cake.power.gif create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Themed/TestTheme/webroot/img/test.jpg create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Themed/TestTheme/webroot/js/one/theme_one.js create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Themed/TestTheme/webroot/js/theme.js create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Themed/TestTheme/webroot/pdfs/theme_test.pdf create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/View/Themed/TestTheme/webroot/space image.text create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/tmp/dir_map create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/webroot/img/cake.power.gif create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/webroot/theme/test_theme/css/theme_webroot.css create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/webroot/theme/test_theme/css/webroot_test.css create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/webroot/theme/test_theme/img/cake.power.gif create mode 100644 poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/test_app/webroot/theme/test_theme/img/test.jpg (limited to 'poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test') diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllBehaviorsTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllBehaviorsTest.php new file mode 100644 index 0000000..c2f30af --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllBehaviorsTest.php @@ -0,0 +1,42 @@ +addTestFile(CORE_TEST_CASES . DS . 'Model' . DS . 'BehaviorCollectionTest.php'); + + $suite->addTestDirectory($path); + return $suite; + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllCacheTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllCacheTest.php new file mode 100644 index 0000000..e9c8a3e --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllCacheTest.php @@ -0,0 +1,40 @@ +addTestDirectory(CORE_TEST_CASES . DS . 'Cache'); + $suite->addTestDirectory(CORE_TEST_CASES . DS . 'Cache' . DS . 'Engine'); + return $suite; + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllComponentsTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllComponentsTest.php new file mode 100644 index 0000000..25cf170 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllComponentsTest.php @@ -0,0 +1,42 @@ +addTestFile(CORE_TEST_CASES . DS . 'Controller' . DS . 'ComponentTest.php'); + $suite->addTestFile(CORE_TEST_CASES . DS . 'Controller' . DS . 'ComponentCollectionTest.php'); + $suite->addTestDirectoryRecursive(CORE_TEST_CASES . DS . 'Controller' . DS . 'Component'); + return $suite; + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllConfigureTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllConfigureTest.php new file mode 100644 index 0000000..ff56ee6 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllConfigureTest.php @@ -0,0 +1,40 @@ +addTestDirectory(CORE_TEST_CASES . DS . 'Configure'); + return $suite; + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllConsoleTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllConsoleTest.php new file mode 100644 index 0000000..820d622 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllConsoleTest.php @@ -0,0 +1,44 @@ +addTestFile($path . 'AllConsoleLibsTest.php'); + $suite->addTestFile($path . 'AllTasksTest.php'); + $suite->addTestFile($path . 'AllShellsTest.php'); + return $suite; + } +} \ No newline at end of file diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllControllerTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllControllerTest.php new file mode 100644 index 0000000..0d3a316 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllControllerTest.php @@ -0,0 +1,44 @@ +addTestFile(CORE_TEST_CASES . DS . 'Controller' . DS . 'ControllerTest.php'); + $suite->addTestFile(CORE_TEST_CASES . DS . 'Controller' . DS . 'ScaffoldTest.php'); + $suite->addTestFile(CORE_TEST_CASES . DS . 'Controller' . DS . 'PagesControllerTest.php'); + $suite->addTestFile(CORE_TEST_CASES . DS . 'Controller' . DS . 'ComponentTest.php'); + $suite->addTestFile(CORE_TEST_CASES . DS . 'Controller' . DS . 'ControllerMergeVarsTest.php'); + return $suite; + } +} \ No newline at end of file diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllCoreTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllCoreTest.php new file mode 100644 index 0000000..7964fe1 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllCoreTest.php @@ -0,0 +1,41 @@ +addTestDirectory(CORE_TEST_CASES . DS . 'Core'); + return $suite; + } +} + diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllDatabaseTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllDatabaseTest.php new file mode 100644 index 0000000..6357ab9 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllDatabaseTest.php @@ -0,0 +1,56 @@ +addTestFile($path . $task . 'Test.php'); + } + return $suite; + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllErrorTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllErrorTest.php new file mode 100644 index 0000000..0777ed5 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllErrorTest.php @@ -0,0 +1,42 @@ +addTestDirectory($libs . 'Error'); + return $suite; + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllEventTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllEventTest.php new file mode 100644 index 0000000..9f8ab29 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllEventTest.php @@ -0,0 +1,40 @@ +addTestDirectory(CORE_TEST_CASES . DS . 'Event'); + return $suite; + } +} + diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllHelpersTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllHelpersTest.php new file mode 100644 index 0000000..9c40ad6 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllHelpersTest.php @@ -0,0 +1,42 @@ +addTestFile(CORE_TEST_CASES . DS . 'View' . DS . 'HelperTest.php'); + $suite->addTestFile(CORE_TEST_CASES . DS . 'View' . DS . 'HelperCollectionTest.php'); + $suite->addTestDirectory(CORE_TEST_CASES . DS . 'View' . DS . 'Helper' . DS); + return $suite; + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllI18nTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllI18nTest.php new file mode 100644 index 0000000..b4bfb8b --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllI18nTest.php @@ -0,0 +1,40 @@ +addTestDirectory(CORE_TEST_CASES . DS . 'I18n'); + return $suite; + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllLogTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllLogTest.php new file mode 100644 index 0000000..e6dca95 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllLogTest.php @@ -0,0 +1,41 @@ +addTestDirectory(CORE_TEST_CASES . DS . 'Log'); + $suite->addTestDirectory(CORE_TEST_CASES . DS . 'Log' . DS . 'Engine'); + return $suite; + } +} + diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllNetworkTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllNetworkTest.php new file mode 100644 index 0000000..22809e0 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllNetworkTest.php @@ -0,0 +1,42 @@ +addTestDirectory(CORE_TEST_CASES . DS . 'Network'); + $suite->addTestDirectory(CORE_TEST_CASES . DS . 'Network' . DS . 'Email'); + $suite->addTestDirectory(CORE_TEST_CASES . DS . 'Network' . DS . 'Http'); + return $suite; + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllRoutingTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllRoutingTest.php new file mode 100644 index 0000000..ebd6712 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllRoutingTest.php @@ -0,0 +1,44 @@ +addTestDirectory($libs . 'Routing'); + $suite->addTestDirectory($libs . 'Routing' . DS . 'Route'); + $suite->addTestDirectory($libs . 'Routing' . DS . 'Filter'); + return $suite; + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllTestSuiteTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllTestSuiteTest.php new file mode 100644 index 0000000..1ead825 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllTestSuiteTest.php @@ -0,0 +1,40 @@ +addTestDirectory(CORE_TEST_CASES . DS . 'TestSuite'); + return $suite; + } +} \ No newline at end of file diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllTestsTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllTestsTest.php new file mode 100644 index 0000000..8990359 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllTestsTest.php @@ -0,0 +1,60 @@ +addTestFile($path . 'BasicsTest.php'); + $suite->addTestFile($path . 'AllConsoleTest.php'); + $suite->addTestFile($path . 'AllBehaviorsTest.php'); + $suite->addTestFile($path . 'AllCacheTest.php'); + $suite->addTestFile($path . 'AllComponentsTest.php'); + $suite->addTestFile($path . 'AllConfigureTest.php'); + $suite->addTestFile($path . 'AllCoreTest.php'); + $suite->addTestFile($path . 'AllControllerTest.php'); + $suite->addTestFile($path . 'AllDatabaseTest.php'); + $suite->addTestFile($path . 'AllErrorTest.php'); + $suite->addTestFile($path . 'AllEventTest.php'); + $suite->addTestFile($path . 'AllHelpersTest.php'); + $suite->addTestFile($path . 'AllLogTest.php'); + $suite->addTestFile($path . 'Model' . DS . 'ModelTest.php'); + $suite->addTestFile($path . 'AllRoutingTest.php'); + $suite->addTestFile($path . 'AllNetworkTest.php'); + $suite->addTestFile($path . 'AllTestSuiteTest.php'); + $suite->addTestFile($path . 'AllUtilityTest.php'); + $suite->addTestFile($path . 'AllViewTest.php'); + $suite->addTestFile($path . 'AllI18nTest.php'); + return $suite; + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllUtilityTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllUtilityTest.php new file mode 100644 index 0000000..8b41d8d --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllUtilityTest.php @@ -0,0 +1,39 @@ +addTestDirectory(CORE_TEST_CASES . DS . 'Utility'); + return $suite; + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllViewTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllViewTest.php new file mode 100644 index 0000000..3a9bcd3 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/AllViewTest.php @@ -0,0 +1,40 @@ +addTestDirectory(CORE_TEST_CASES . DS . 'View'); + return $suite; + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/BasicsTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/BasicsTest.php new file mode 100644 index 0000000..c218f1a --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/BasicsTest.php @@ -0,0 +1,942 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case + * @since CakePHP(tm) v 1.2.0.4206 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ + +require_once CAKE . 'basics.php'; +App::uses('Folder', 'Utility'); +App::uses('CakeResponse', 'Network'); + +/** + * BasicsTest class + * + * @package Cake.Test.Case + */ +class BasicsTest extends CakeTestCase { + +/** + * setUp method + * + * @return void + */ + public function setUp() { + parent::setUp(); + App::build(array( + 'Locale' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Locale' . DS) + )); + } + +/** + * test the array_diff_key compatibility function. + * + * @return void + */ + public function testArrayDiffKey() { + $one = array('one' => 1, 'two' => 2, 'three' => 3); + $two = array('one' => 'one', 'two' => 'two'); + $result = array_diff_key($one, $two); + $expected = array('three' => 3); + $this->assertEquals($expected, $result); + + $one = array('one' => array('value', 'value-two'), 'two' => 2, 'three' => 3); + $two = array('two' => 'two'); + $result = array_diff_key($one, $two); + $expected = array('one' => array('value', 'value-two'), 'three' => 3); + $this->assertEquals($expected, $result); + + $one = array('one' => null, 'two' => 2, 'three' => '', 'four' => 0); + $two = array('two' => 'two'); + $result = array_diff_key($one, $two); + $expected = array('one' => null, 'three' => '', 'four' => 0); + $this->assertEquals($expected, $result); + + $one = array('minYear' => null, 'maxYear' => null, 'separator' => '-', 'interval' => 1, 'monthNames' => true); + $two = array('minYear' => null, 'maxYear' => null, 'separator' => '-', 'interval' => 1, 'monthNames' => true); + $result = array_diff_key($one, $two); + $this->assertEquals(array(), $result); + } + +/** + * testHttpBase method + * + * @return void + */ + public function testEnv() { + $this->skipIf(!function_exists('ini_get') || ini_get('safe_mode') === '1', 'Safe mode is on.'); + + $server = $_SERVER; + $env = $_ENV; + + $_SERVER['HTTP_HOST'] = 'localhost'; + $this->assertEquals(env('HTTP_BASE'), '.localhost'); + + $_SERVER['HTTP_HOST'] = 'com.ar'; + $this->assertEquals(env('HTTP_BASE'), '.com.ar'); + + $_SERVER['HTTP_HOST'] = 'example.ar'; + $this->assertEquals(env('HTTP_BASE'), '.example.ar'); + + $_SERVER['HTTP_HOST'] = 'example.com'; + $this->assertEquals(env('HTTP_BASE'), '.example.com'); + + $_SERVER['HTTP_HOST'] = 'www.example.com'; + $this->assertEquals(env('HTTP_BASE'), '.example.com'); + + $_SERVER['HTTP_HOST'] = 'subdomain.example.com'; + $this->assertEquals(env('HTTP_BASE'), '.example.com'); + + $_SERVER['HTTP_HOST'] = 'example.com.ar'; + $this->assertEquals(env('HTTP_BASE'), '.example.com.ar'); + + $_SERVER['HTTP_HOST'] = 'www.example.com.ar'; + $this->assertEquals(env('HTTP_BASE'), '.example.com.ar'); + + $_SERVER['HTTP_HOST'] = 'subdomain.example.com.ar'; + $this->assertEquals(env('HTTP_BASE'), '.example.com.ar'); + + $_SERVER['HTTP_HOST'] = 'double.subdomain.example.com'; + $this->assertEquals(env('HTTP_BASE'), '.subdomain.example.com'); + + $_SERVER['HTTP_HOST'] = 'double.subdomain.example.com.ar'; + $this->assertEquals(env('HTTP_BASE'), '.subdomain.example.com.ar'); + + $_SERVER = $_ENV = array(); + + $_SERVER['SCRIPT_NAME'] = '/a/test/test.php'; + $this->assertEquals(env('SCRIPT_NAME'), '/a/test/test.php'); + + $_SERVER = $_ENV = array(); + + $_ENV['CGI_MODE'] = 'BINARY'; + $_ENV['SCRIPT_URL'] = '/a/test/test.php'; + $this->assertEquals(env('SCRIPT_NAME'), '/a/test/test.php'); + + $_SERVER = $_ENV = array(); + + $this->assertFalse(env('HTTPS')); + + $_SERVER['HTTPS'] = 'on'; + $this->assertTrue(env('HTTPS')); + + $_SERVER['HTTPS'] = '1'; + $this->assertTrue(env('HTTPS')); + + $_SERVER['HTTPS'] = 'I am not empty'; + $this->assertTrue(env('HTTPS')); + + $_SERVER['HTTPS'] = 1; + $this->assertTrue(env('HTTPS')); + + $_SERVER['HTTPS'] = 'off'; + $this->assertFalse(env('HTTPS')); + + $_SERVER['HTTPS'] = false; + $this->assertFalse(env('HTTPS')); + + $_SERVER['HTTPS'] = ''; + $this->assertFalse(env('HTTPS')); + + $_SERVER = array(); + + $_ENV['SCRIPT_URI'] = 'https://domain.test/a/test.php'; + $this->assertTrue(env('HTTPS')); + + $_ENV['SCRIPT_URI'] = 'http://domain.test/a/test.php'; + $this->assertFalse(env('HTTPS')); + + $_SERVER = $_ENV = array(); + + $this->assertNull(env('TEST_ME')); + + $_ENV['TEST_ME'] = 'a'; + $this->assertEquals(env('TEST_ME'), 'a'); + + $_SERVER['TEST_ME'] = 'b'; + $this->assertEquals(env('TEST_ME'), 'b'); + + unset($_ENV['TEST_ME']); + $this->assertEquals(env('TEST_ME'), 'b'); + + $_SERVER = $server; + $_ENV = $env; + } + +/** + * Test h() + * + * @return void + */ + public function testH() { + $string = ''; + $result = h($string); + $this->assertEquals('<foo>', $result); + + $in = array('this & that', '

Which one

'); + $result = h($in); + $expected = array('this & that', '<p>Which one</p>'); + $this->assertEquals($expected, $result); + + $string = ' &  '; + $result = h($string); + $this->assertEquals('<foo> & &nbsp;', $result); + + $string = ' &  '; + $result = h($string, false); + $this->assertEquals('<foo> &  ', $result); + + $string = ' &  '; + $result = h($string, 'UTF-8'); + $this->assertEquals('<foo> & &nbsp;', $result); + + $arr = array('', ' '); + $result = h($arr); + $expected = array( + '<foo>', + '&nbsp;' + ); + $this->assertEquals($expected, $result); + + $arr = array('', ' '); + $result = h($arr, false); + $expected = array( + '<foo>', + ' ' + ); + $this->assertEquals($expected, $result); + + $arr = array('f' => '', 'n' => ' '); + $result = h($arr, false); + $expected = array( + 'f' => '<foo>', + 'n' => ' ' + ); + $this->assertEquals($expected, $result); + + $obj = new stdClass(); + $result = h($obj); + $this->assertEquals('(object)stdClass', $result); + + $obj = new CakeResponse(array('body' => 'Body content')); + $result = h($obj); + $this->assertEquals('Body content', $result); + } + +/** + * Test am() + * + * @return void + */ + public function testAm() { + $result = am(array('one', 'two'), 2, 3, 4); + $expected = array('one', 'two', 2, 3, 4); + $this->assertEquals($expected, $result); + + $result = am(array('one' => array(2, 3), 'two' => array('foo')), array('one' => array(4, 5))); + $expected = array('one' => array(4, 5), 'two' => array('foo')); + $this->assertEquals($expected, $result); + } + +/** + * test cache() + * + * @return void + */ + public function testCache() { + $_cacheDisable = Configure::read('Cache.disable'); + $this->skipIf($_cacheDisable, 'Cache is disabled, skipping cache() tests.'); + + Configure::write('Cache.disable', true); + $result = cache('basics_test', 'simple cache write'); + $this->assertNull($result); + + $result = cache('basics_test'); + $this->assertNull($result); + + Configure::write('Cache.disable', false); + $result = cache('basics_test', 'simple cache write'); + $this->assertTrue((boolean)$result); + $this->assertTrue(file_exists(CACHE . 'basics_test')); + + $result = cache('basics_test'); + $this->assertEquals('simple cache write', $result); + @unlink(CACHE . 'basics_test'); + + cache('basics_test', 'expired', '+1 second'); + sleep(2); + $result = cache('basics_test', null, '+1 second'); + $this->assertNull($result); + + Configure::write('Cache.disable', $_cacheDisable); + } + +/** + * test clearCache() + * + * @return void + */ + public function testClearCache() { + $cacheOff = Configure::read('Cache.disable'); + $this->skipIf($cacheOff, 'Cache is disabled, skipping clearCache() tests.'); + + cache('views' . DS . 'basics_test.cache', 'simple cache write'); + $this->assertTrue(file_exists(CACHE . 'views' . DS . 'basics_test.cache')); + + cache('views' . DS . 'basics_test_2.cache', 'simple cache write 2'); + $this->assertTrue(file_exists(CACHE . 'views' . DS . 'basics_test_2.cache')); + + cache('views' . DS . 'basics_test_3.cache', 'simple cache write 3'); + $this->assertTrue(file_exists(CACHE . 'views' . DS . 'basics_test_3.cache')); + + $result = clearCache(array('basics_test', 'basics_test_2'), 'views', '.cache'); + $this->assertTrue($result); + $this->assertFalse(file_exists(CACHE . 'views' . DS . 'basics_test.cache')); + $this->assertFalse(file_exists(CACHE . 'views' . DS . 'basics_test.cache')); + $this->assertTrue(file_exists(CACHE . 'views' . DS . 'basics_test_3.cache')); + + $result = clearCache(null, 'views', '.cache'); + $this->assertTrue($result); + $this->assertFalse(file_exists(CACHE . 'views' . DS . 'basics_test_3.cache')); + + // Different path from views and with prefix + cache('models' . DS . 'basics_test.cache', 'simple cache write'); + $this->assertTrue(file_exists(CACHE . 'models' . DS . 'basics_test.cache')); + + cache('models' . DS . 'basics_test_2.cache', 'simple cache write 2'); + $this->assertTrue(file_exists(CACHE . 'models' . DS . 'basics_test_2.cache')); + + cache('models' . DS . 'basics_test_3.cache', 'simple cache write 3'); + $this->assertTrue(file_exists(CACHE . 'models' . DS . 'basics_test_3.cache')); + + $result = clearCache('basics', 'models', '.cache'); + $this->assertTrue($result); + $this->assertFalse(file_exists(CACHE . 'models' . DS . 'basics_test.cache')); + $this->assertFalse(file_exists(CACHE . 'models' . DS . 'basics_test_2.cache')); + $this->assertFalse(file_exists(CACHE . 'models' . DS . 'basics_test_3.cache')); + + // checking if empty files were not removed + $emptyExists = file_exists(CACHE . 'views' . DS . 'empty'); + if (!$emptyExists) { + cache('views' . DS . 'empty', ''); + } + cache('views' . DS . 'basics_test.php', 'simple cache write'); + $this->assertTrue(file_exists(CACHE . 'views' . DS . 'basics_test.php')); + $this->assertTrue(file_exists(CACHE . 'views' . DS . 'empty')); + + $result = clearCache(); + $this->assertTrue($result); + $this->assertTrue(file_exists(CACHE . 'views' . DS . 'empty')); + $this->assertFalse(file_exists(CACHE . 'views' . DS . 'basics_test.php')); + if (!$emptyExists) { + unlink(CACHE . 'views' . DS . 'empty'); + } + } + +/** + * test __() + * + * @return void + */ + public function testTranslate() { + Configure::write('Config.language', 'rule_1_po'); + + $result = __('Plural Rule 1'); + $expected = 'Plural Rule 1 (translated)'; + $this->assertEquals($expected, $result); + + $result = __('Plural Rule 1 (from core)'); + $expected = 'Plural Rule 1 (from core translated)'; + $this->assertEquals($expected, $result); + + $result = __('Some string with %s', 'arguments'); + $expected = 'Some string with arguments'; + $this->assertEquals($expected, $result); + + $result = __('Some string with %s %s', 'multiple', 'arguments'); + $expected = 'Some string with multiple arguments'; + $this->assertEquals($expected, $result); + + $result = __('Some string with %s %s', array('multiple', 'arguments')); + $expected = 'Some string with multiple arguments'; + $this->assertEquals($expected, $result); + + $result = __('Testing %2$s %1$s', 'order', 'different'); + $expected = 'Testing different order'; + $this->assertEquals($expected, $result); + + $result = __('Testing %2$s %1$s', array('order', 'different')); + $expected = 'Testing different order'; + $this->assertEquals($expected, $result); + + $result = __('Testing %.2f number', 1.2345); + $expected = 'Testing 1.23 number'; + $this->assertEquals($expected, $result); + } + +/** + * test __n() + * + * @return void + */ + public function testTranslatePlural() { + Configure::write('Config.language', 'rule_1_po'); + + $result = __n('%d = 1', '%d = 0 or > 1', 0); + $expected = '%d = 0 or > 1 (translated)'; + $this->assertEquals($expected, $result); + + $result = __n('%d = 1', '%d = 0 or > 1', 1); + $expected = '%d = 1 (translated)'; + $this->assertEquals($expected, $result); + + $result = __n('%d = 1 (from core)', '%d = 0 or > 1 (from core)', 2); + $expected = '%d = 0 or > 1 (from core translated)'; + $this->assertEquals($expected, $result); + + $result = __n('%d item.', '%d items.', 1, 1); + $expected = '1 item.'; + $this->assertEquals($expected, $result); + + $result = __n('%d item for id %s', '%d items for id %s', 2, 2, '1234'); + $expected = '2 items for id 1234'; + $this->assertEquals($expected, $result); + + $result = __n('%d item for id %s', '%d items for id %s', 2, array(2, '1234')); + $expected = '2 items for id 1234'; + $this->assertEquals($expected, $result); + } + +/** + * test __d() + * + * @return void + */ + public function testTranslateDomain() { + Configure::write('Config.language', 'rule_1_po'); + + $result = __d('default', 'Plural Rule 1'); + $expected = 'Plural Rule 1 (translated)'; + $this->assertEquals($expected, $result); + + $result = __d('core', 'Plural Rule 1'); + $expected = 'Plural Rule 1'; + $this->assertEquals($expected, $result); + + $result = __d('core', 'Plural Rule 1 (from core)'); + $expected = 'Plural Rule 1 (from core translated)'; + $this->assertEquals($expected, $result); + + $result = __d('core', 'Some string with %s', 'arguments'); + $expected = 'Some string with arguments'; + $this->assertEquals($expected, $result); + + $result = __d('core', 'Some string with %s %s', 'multiple', 'arguments'); + $expected = 'Some string with multiple arguments'; + $this->assertEquals($expected, $result); + + $result = __d('core', 'Some string with %s %s', array('multiple', 'arguments')); + $expected = 'Some string with multiple arguments'; + $this->assertEquals($expected, $result); + } + +/** + * test __dn() + * + * @return void + */ + public function testTranslateDomainPlural() { + Configure::write('Config.language', 'rule_1_po'); + + $result = __dn('default', '%d = 1', '%d = 0 or > 1', 0); + $expected = '%d = 0 or > 1 (translated)'; + $this->assertEquals($expected, $result); + + $result = __dn('core', '%d = 1', '%d = 0 or > 1', 0); + $expected = '%d = 0 or > 1'; + $this->assertEquals($expected, $result); + + $result = __dn('core', '%d = 1 (from core)', '%d = 0 or > 1 (from core)', 0); + $expected = '%d = 0 or > 1 (from core translated)'; + $this->assertEquals($expected, $result); + + $result = __dn('default', '%d = 1', '%d = 0 or > 1', 1); + $expected = '%d = 1 (translated)'; + $this->assertEquals($expected, $result); + + $result = __dn('core', '%d item.', '%d items.', 1, 1); + $expected = '1 item.'; + $this->assertEquals($expected, $result); + + $result = __dn('core', '%d item for id %s', '%d items for id %s', 2, 2, '1234'); + $expected = '2 items for id 1234'; + $this->assertEquals($expected, $result); + + $result = __dn('core', '%d item for id %s', '%d items for id %s', 2, array(2, '1234')); + $expected = '2 items for id 1234'; + $this->assertEquals($expected, $result); + } + +/** + * test __c() + * + * @return void + */ + public function testTranslateCategory() { + Configure::write('Config.language', 'rule_1_po'); + + $result = __c('Plural Rule 1', 6); + $expected = 'Plural Rule 1 (translated)'; + $this->assertEquals($expected, $result); + + $result = __c('Plural Rule 1 (from core)', 6); + $expected = 'Plural Rule 1 (from core translated)'; + $this->assertEquals($expected, $result); + + $result = __c('Some string with %s', 6, 'arguments'); + $expected = 'Some string with arguments'; + $this->assertEquals($expected, $result); + + $result = __c('Some string with %s %s', 6, 'multiple', 'arguments'); + $expected = 'Some string with multiple arguments'; + $this->assertEquals($expected, $result); + + $result = __c('Some string with %s %s', 6, array('multiple', 'arguments')); + $expected = 'Some string with multiple arguments'; + $this->assertEquals($expected, $result); + } + +/** + * test __dc() + * + * @return void + */ + public function testTranslateDomainCategory() { + Configure::write('Config.language', 'rule_1_po'); + + $result = __dc('default', 'Plural Rule 1', 6); + $expected = 'Plural Rule 1 (translated)'; + $this->assertEquals($expected, $result); + + $result = __dc('default', 'Plural Rule 1 (from core)', 6); + $expected = 'Plural Rule 1 (from core translated)'; + $this->assertEquals($expected, $result); + + $result = __dc('core', 'Plural Rule 1', 6); + $expected = 'Plural Rule 1'; + $this->assertEquals($expected, $result); + + $result = __dc('core', 'Plural Rule 1 (from core)', 6); + $expected = 'Plural Rule 1 (from core translated)'; + $this->assertEquals($expected, $result); + + $result = __dc('core', 'Some string with %s', 6, 'arguments'); + $expected = 'Some string with arguments'; + $this->assertEquals($expected, $result); + + $result = __dc('core', 'Some string with %s %s', 6, 'multiple', 'arguments'); + $expected = 'Some string with multiple arguments'; + $this->assertEquals($expected, $result); + + $result = __dc('core', 'Some string with %s %s', 6, array('multiple', 'arguments')); + $expected = 'Some string with multiple arguments'; + $this->assertEquals($expected, $result); + } + +/** + * test __dcn() + * + * @return void + */ + public function testTranslateDomainCategoryPlural() { + Configure::write('Config.language', 'rule_1_po'); + + $result = __dcn('default', '%d = 1', '%d = 0 or > 1', 0, 6); + $expected = '%d = 0 or > 1 (translated)'; + $this->assertEquals($expected, $result); + + $result = __dcn('default', '%d = 1 (from core)', '%d = 0 or > 1 (from core)', 1, 6); + $expected = '%d = 1 (from core translated)'; + $this->assertEquals($expected, $result); + + $result = __dcn('core', '%d = 1', '%d = 0 or > 1', 0, 6); + $expected = '%d = 0 or > 1'; + $this->assertEquals($expected, $result); + + $result = __dcn('core', '%d item.', '%d items.', 1, 6, 1); + $expected = '1 item.'; + $this->assertEquals($expected, $result); + + $result = __dcn('core', '%d item for id %s', '%d items for id %s', 2, 6, 2, '1234'); + $expected = '2 items for id 1234'; + $this->assertEquals($expected, $result); + + $result = __dcn('core', '%d item for id %s', '%d items for id %s', 2, 6, array(2, '1234')); + $expected = '2 items for id 1234'; + $this->assertEquals($expected, $result); + } + +/** + * test LogError() + * + * @return void + */ + public function testLogError() { + @unlink(LOGS . 'error.log'); + + // disable stderr output for this test + if (CakeLog::stream('stderr')) { + CakeLog::disable('stderr'); + } + + LogError('Testing LogError() basic function'); + LogError("Testing with\nmulti-line\nstring"); + + if (CakeLog::stream('stderr')) { + CakeLog::enable('stderr'); + } + + $result = file_get_contents(LOGS . 'error.log'); + $this->assertRegExp('/Error: Testing LogError\(\) basic function/', $result); + $this->assertNotRegExp("/Error: Testing with\nmulti-line\nstring/", $result); + $this->assertRegExp('/Error: Testing with multi-line string/', $result); + } + +/** + * test fileExistsInPath() + * + * @return void + */ + public function testFileExistsInPath() { + if (!function_exists('ini_set')) { + $this->markTestSkipped('%s ini_set function not available'); + } + + $_includePath = ini_get('include_path'); + + $path = TMP . 'basics_test'; + $folder1 = $path . DS . 'folder1'; + $folder2 = $path . DS . 'folder2'; + $file1 = $path . DS . 'file1.php'; + $file2 = $folder1 . DS . 'file2.php'; + $file3 = $folder1 . DS . 'file3.php'; + $file4 = $folder2 . DS . 'file4.php'; + + new Folder($path, true); + new Folder($folder1, true); + new Folder($folder2, true); + touch($file1); + touch($file2); + touch($file3); + touch($file4); + + ini_set('include_path', $path . PATH_SEPARATOR . $folder1); + + $this->assertEquals(fileExistsInPath('file1.php'), $file1); + $this->assertEquals(fileExistsInPath('file2.php'), $file2); + $this->assertEquals(fileExistsInPath('folder1' . DS . 'file2.php'), $file2); + $this->assertEquals(fileExistsInPath($file2), $file2); + $this->assertEquals(fileExistsInPath('file3.php'), $file3); + $this->assertEquals(fileExistsInPath($file4), $file4); + + $this->assertFalse(fileExistsInPath('file1')); + $this->assertFalse(fileExistsInPath('file4.php')); + + $Folder = new Folder($path); + $Folder->delete(); + + ini_set('include_path', $_includePath); + } + +/** + * test convertSlash() + * + * @return void + */ + public function testConvertSlash() { + $result = convertSlash('\path\to\location\\'); + $expected = '\path\to\location\\'; + $this->assertEquals($expected, $result); + + $result = convertSlash('/path/to/location/'); + $expected = 'path_to_location'; + $this->assertEquals($expected, $result); + } + +/** + * test debug() + * + * @return void + */ + public function testDebug() { + ob_start(); + debug('this-is-a-test', false); + $result = ob_get_clean(); + $expectedText = <<assertEquals($expected, $result); + + ob_start(); + debug('
this-is-a-test
', true); + $result = ob_get_clean(); + $expectedHtml = << +%s (line %d) +
+'<div>this-is-a-test</div>'
+
+ +EXPECTED; + $expected = sprintf($expectedHtml, str_replace(CAKE_CORE_INCLUDE_PATH, '', __FILE__), __LINE__ - 10); + $this->assertEquals($expected, $result); + + ob_start(); + debug('
this-is-a-test
', true, true); + $result = ob_get_clean(); + $expected = << +%s (line %d) +
+'<div>this-is-a-test</div>'
+
+ +EXPECTED; + $expected = sprintf($expected, str_replace(CAKE_CORE_INCLUDE_PATH, '', __FILE__), __LINE__ - 10); + $this->assertEquals($expected, $result); + + ob_start(); + debug('
this-is-a-test
', true, false); + $result = ob_get_clean(); + $expected = << + +
+'<div>this-is-a-test</div>'
+
+ +EXPECTED; + $expected = sprintf($expected, str_replace(CAKE_CORE_INCLUDE_PATH, '', __FILE__), __LINE__ - 10); + $this->assertEquals($expected, $result); + + ob_start(); + debug('
this-is-a-test
', null); + $result = ob_get_clean(); + $expectedHtml = << +%s (line %d) +
+'<div>this-is-a-test</div>'
+
+ +EXPECTED; + $expectedText = <<this-is-a-test' +########################### +EXPECTED; + if (php_sapi_name() == 'cli') { + $expected = sprintf($expectedText, str_replace(CAKE_CORE_INCLUDE_PATH, '', __FILE__), __LINE__ - 17); + } else { + $expected = sprintf($expectedHtml, str_replace(CAKE_CORE_INCLUDE_PATH, '', __FILE__), __LINE__ - 19); + } + $this->assertEquals($expected, $result); + + ob_start(); + debug('
this-is-a-test
', null, false); + $result = ob_get_clean(); + $expectedHtml = << + +
+'<div>this-is-a-test</div>'
+
+ +EXPECTED; + $expectedText = <<this-is-a-test' +########################### +EXPECTED; + if (php_sapi_name() == 'cli') { + $expected = sprintf($expectedText, str_replace(CAKE_CORE_INCLUDE_PATH, '', __FILE__), __LINE__ - 17); + } else { + $expected = sprintf($expectedHtml, str_replace(CAKE_CORE_INCLUDE_PATH, '', __FILE__), __LINE__ - 19); + } + $this->assertEquals($expected, $result); + + ob_start(); + debug('
this-is-a-test
', false); + $result = ob_get_clean(); + $expected = <<this-is-a-test' +########################### +EXPECTED; + $expected = sprintf($expected, str_replace(CAKE_CORE_INCLUDE_PATH, '', __FILE__), __LINE__ - 8); + $this->assertEquals($expected, $result); + + ob_start(); + debug('
this-is-a-test
', false, true); + $result = ob_get_clean(); + $expected = <<this-is-a-test' +########################### +EXPECTED; + $expected = sprintf($expected, str_replace(CAKE_CORE_INCLUDE_PATH, '', __FILE__), __LINE__ - 8); + $this->assertEquals($expected, $result); + + ob_start(); + debug('
this-is-a-test
', false, false); + $result = ob_get_clean(); + $expected = <<this-is-a-test' +########################### +EXPECTED; + $expected = sprintf($expected, str_replace(CAKE_CORE_INCLUDE_PATH, '', __FILE__), __LINE__ - 8); + $this->assertEquals($expected, $result); + } + +/** + * test pr() + * + * @return void + */ + public function testPr() { + ob_start(); + pr('this is a test'); + $result = ob_get_clean(); + $expected = "
this is a test
"; + $this->assertEquals($expected, $result); + + ob_start(); + pr(array('this' => 'is', 'a' => 'test')); + $result = ob_get_clean(); + $expected = "
Array\n(\n    [this] => is\n    [a] => test\n)\n
"; + $this->assertEquals($expected, $result); + } + +/** + * test stripslashes_deep() + * + * @return void + */ + public function testStripslashesDeep() { + $this->skipIf(ini_get('magic_quotes_sybase') === '1', 'magic_quotes_sybase is on.'); + + $this->assertEquals(stripslashes_deep("tes\'t"), "tes't"); + $this->assertEquals(stripslashes_deep('tes\\' . chr(0) . 't'), 'tes' . chr(0) . 't'); + $this->assertEquals(stripslashes_deep('tes\"t'), 'tes"t'); + $this->assertEquals(stripslashes_deep("tes\'t"), "tes't"); + $this->assertEquals(stripslashes_deep('te\\st'), 'test'); + + $nested = array( + 'a' => "tes\'t", + 'b' => 'tes\\' . chr(0) . 't', + 'c' => array( + 'd' => 'tes\"t', + 'e' => "te\'s\'t", + array('f' => "tes\'t") + ), + 'g' => 'te\\st' + ); + $expected = array( + 'a' => "tes't", + 'b' => 'tes' . chr(0) . 't', + 'c' => array( + 'd' => 'tes"t', + 'e' => "te's't", + array('f' => "tes't") + ), + 'g' => 'test' + ); + $this->assertEquals($expected, stripslashes_deep($nested)); + } + +/** + * test stripslashes_deep() with magic_quotes_sybase on + * + * @return void + */ + public function testStripslashesDeepSybase() { + if (!(ini_get('magic_quotes_sybase') === '1')) { + $this->markTestSkipped('magic_quotes_sybase is off'); + } + + $this->assertEquals(stripslashes_deep("tes\'t"), "tes\'t"); + + $nested = array( + 'a' => "tes't", + 'b' => "tes''t", + 'c' => array( + 'd' => "tes'''t", + 'e' => "tes''''t", + array('f' => "tes''t") + ), + 'g' => "te'''''st" + ); + $expected = array( + 'a' => "tes't", + 'b' => "tes't", + 'c' => array( + 'd' => "tes''t", + 'e' => "tes''t", + array('f' => "tes't") + ), + 'g' => "te'''st" + ); + $this->assertEquals($expected, stripslashes_deep($nested)); + } + +/** + * test pluginSplit + * + * @return void + */ + public function testPluginSplit() { + $result = pluginSplit('Something.else'); + $this->assertEquals(array('Something', 'else'), $result); + + $result = pluginSplit('Something.else.more.dots'); + $this->assertEquals(array('Something', 'else.more.dots'), $result); + + $result = pluginSplit('Somethingelse'); + $this->assertEquals(array(null, 'Somethingelse'), $result); + + $result = pluginSplit('Something.else', true); + $this->assertEquals(array('Something.', 'else'), $result); + + $result = pluginSplit('Something.else.more.dots', true); + $this->assertEquals(array('Something.', 'else.more.dots'), $result); + + $result = pluginSplit('Post', false, 'Blog'); + $this->assertEquals(array('Blog', 'Post'), $result); + + $result = pluginSplit('Blog.Post', false, 'Ultimate'); + $this->assertEquals(array('Blog', 'Post'), $result); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Cache/CacheTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Cache/CacheTest.php new file mode 100644 index 0000000..b4cb358 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Cache/CacheTest.php @@ -0,0 +1,412 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Cache + * @since CakePHP(tm) v 1.2.0.5432 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ + +App::uses('Cache', 'Cache'); + +/** + * CacheTest class + * + * @package Cake.Test.Case.Cache + */ +class CacheTest extends CakeTestCase { + +/** + * setUp method + * + * @return void + */ + public function setUp() { + parent::setUp(); + $this->_cacheDisable = Configure::read('Cache.disable'); + Configure::write('Cache.disable', false); + + $this->_defaultCacheConfig = Cache::config('default'); + Cache::config('default', array('engine' => 'File', 'path' => TMP . 'tests')); + } + +/** + * tearDown method + * + * @return void + */ + public function tearDown() { + parent::tearDown(); + Configure::write('Cache.disable', $this->_cacheDisable); + Cache::config('default', $this->_defaultCacheConfig['settings']); + } + +/** + * testConfig method + * + * @return void + */ + public function testConfig() { + $settings = array('engine' => 'File', 'path' => TMP . 'tests', 'prefix' => 'cake_test_'); + $results = Cache::config('new', $settings); + $this->assertEquals(Cache::config('new'), $results); + $this->assertTrue(isset($results['engine'])); + $this->assertTrue(isset($results['settings'])); + } + +/** + * Check that no fatal errors are issued doing normal things when Cache.disable is true. + * + * @return void + */ + public function testNonFatalErrorsWithCachedisable() { + Configure::write('Cache.disable', true); + Cache::config('test', array('engine' => 'File', 'path' => TMP, 'prefix' => 'error_test_')); + + Cache::write('no_save', 'Noooo!', 'test'); + Cache::read('no_save', 'test'); + Cache::delete('no_save', 'test'); + Cache::set('duration', '+10 minutes'); + + Configure::write('Cache.disable', false); + } + +/** + * test configuring CacheEngines in App/libs + * + * @return void + */ + public function testConfigWithLibAndPluginEngines() { + App::build(array( + 'Lib' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Lib' . DS), + 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS) + ), App::RESET); + CakePlugin::load('TestPlugin'); + + $settings = array('engine' => 'TestAppCache', 'path' => TMP, 'prefix' => 'cake_test_'); + $result = Cache::config('libEngine', $settings); + $this->assertEquals(Cache::config('libEngine'), $result); + + $settings = array('engine' => 'TestPlugin.TestPluginCache', 'path' => TMP, 'prefix' => 'cake_test_'); + $result = Cache::config('pluginLibEngine', $settings); + $this->assertEquals(Cache::config('pluginLibEngine'), $result); + + Cache::drop('libEngine'); + Cache::drop('pluginLibEngine'); + + App::build(); + CakePlugin::unload(); + } + +/** + * testInvalidConfig method + * + * Test that the cache class doesn't cause fatal errors with a partial path + * + * @expectedException PHPUnit_Framework_Error_Warning + * @return void + */ + public function testInvalidConfig() { + Cache::config('invalid', array( + 'engine' => 'File', + 'duration' => '+1 year', + 'prefix' => 'testing_invalid_', + 'path' => 'data/', + 'serialize' => true, + 'random' => 'wii' + )); + $read = Cache::read('Test', 'invalid'); + } + +/** + * Test reading from a config that is undefined. + * + * @return void + */ + public function testReadNonExistingConfig() { + $this->assertFalse(Cache::read('key', 'totally fake')); + $this->assertFalse(Cache::write('key', 'value', 'totally fake')); + $this->assertFalse(Cache::increment('key', 1, 'totally fake')); + $this->assertFalse(Cache::decrement('key', 1, 'totally fake')); + } + +/** + * test that trying to configure classes that don't extend CacheEngine fail. + * + * @expectedException CacheException + * @return void + */ + public function testAttemptingToConfigureANonCacheEngineClass() { + $this->getMock('StdClass', array(), array(), 'RubbishEngine'); + Cache::config('Garbage', array( + 'engine' => 'Rubbish' + )); + } + +/** + * testConfigChange method + * + * @return void + */ + public function testConfigChange() { + $_cacheConfigSessions = Cache::config('sessions'); + $_cacheConfigTests = Cache::config('tests'); + + $result = Cache::config('sessions', array('engine' => 'File', 'path' => TMP . 'sessions')); + $this->assertEquals(Cache::settings('sessions'), $result['settings']); + + $result = Cache::config('tests', array('engine' => 'File', 'path' => TMP . 'tests')); + $this->assertEquals(Cache::settings('tests'), $result['settings']); + + Cache::config('sessions', $_cacheConfigSessions['settings']); + Cache::config('tests', $_cacheConfigTests['settings']); + } + +/** + * test that calling config() sets the 'default' configuration up. + * + * @return void + */ + public function testConfigSettingDefaultConfigKey() { + Cache::config('test_name', array('engine' => 'File', 'prefix' => 'test_name_')); + + Cache::write('value_one', 'I am cached', 'test_name'); + $result = Cache::read('value_one', 'test_name'); + $this->assertEquals('I am cached', $result); + + $result = Cache::read('value_one'); + $this->assertEquals(null, $result); + + Cache::write('value_one', 'I am in default config!'); + $result = Cache::read('value_one'); + $this->assertEquals('I am in default config!', $result); + + $result = Cache::read('value_one', 'test_name'); + $this->assertEquals('I am cached', $result); + + Cache::delete('value_one', 'test_name'); + Cache::delete('value_one', 'default'); + } + +/** + * testWritingWithConfig method + * + * @return void + */ + public function testWritingWithConfig() { + $_cacheConfigSessions = Cache::config('sessions'); + + Cache::write('test_something', 'this is the test data', 'tests'); + + $expected = array( + 'path' => TMP . 'sessions' . DS, + 'prefix' => 'cake_', + 'lock' => true, + 'serialize' => true, + 'duration' => 3600, + 'probability' => 100, + 'engine' => 'File', + 'isWindows' => DIRECTORY_SEPARATOR == '\\', + 'mask' => 0664, + 'groups' => array() + ); + $this->assertEquals($expected, Cache::settings('sessions')); + + Cache::config('sessions', $_cacheConfigSessions['settings']); + } + +/** + * test that configured returns an array of the currently configured cache + * settings + * + * @return void + */ + public function testConfigured() { + $result = Cache::configured(); + $this->assertTrue(in_array('_cake_core_', $result)); + $this->assertTrue(in_array('default', $result)); + } + +/** + * testInitSettings method + * + * @return void + */ + public function testInitSettings() { + $initial = Cache::settings(); + $override = array('engine' => 'File', 'path' => TMP . 'tests'); + Cache::config('for_test', $override); + + $settings = Cache::settings(); + $expecting = $override + $initial; + $this->assertEquals($settings, $expecting); + } + +/** + * test that drop removes cache configs, and that further attempts to use that config + * do not work. + * + * @return void + */ + public function testDrop() { + App::build(array( + 'Lib' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Lib' . DS), + 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS) + ), App::RESET); + + $result = Cache::drop('some_config_that_does_not_exist'); + $this->assertFalse($result); + + $_testsConfig = Cache::config('tests'); + $result = Cache::drop('tests'); + $this->assertTrue($result); + + Cache::config('unconfigTest', array( + 'engine' => 'TestAppCache' + )); + $this->assertTrue(Cache::isInitialized('unconfigTest')); + + $this->assertTrue(Cache::drop('unconfigTest')); + $this->assertFalse(Cache::isInitialized('TestAppCache')); + + Cache::config('tests', $_testsConfig); + App::build(); + } + +/** + * testWriteEmptyValues method + * + * @return void + */ + public function testWriteEmptyValues() { + Cache::write('App.falseTest', false); + $this->assertSame(Cache::read('App.falseTest'), false); + + Cache::write('App.trueTest', true); + $this->assertSame(Cache::read('App.trueTest'), true); + + Cache::write('App.nullTest', null); + $this->assertSame(Cache::read('App.nullTest'), null); + + Cache::write('App.zeroTest', 0); + $this->assertSame(Cache::read('App.zeroTest'), 0); + + Cache::write('App.zeroTest2', '0'); + $this->assertSame(Cache::read('App.zeroTest2'), '0'); + } + +/** + * Test that failed writes cause errors to be triggered. + * + * @return void + */ + public function testWriteTriggerError() { + App::build(array( + 'Lib' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Lib' . DS), + 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS) + ), App::RESET); + + Cache::config('test_trigger', array('engine' => 'TestAppCache', 'prefix' => '')); + try { + Cache::write('fail', 'value', 'test_trigger'); + $this->fail('No exception thrown'); + } catch (PHPUnit_Framework_Error $e) { + $this->assertTrue(true); + } + Cache::drop('test_trigger'); + App::build(); + } + +/** + * testCacheDisable method + * + * Check that the "Cache.disable" configuration and a change to it + * (even after a cache config has been setup) is taken into account. + * + * @return void + */ + public function testCacheDisable() { + Configure::write('Cache.disable', false); + Cache::config('test_cache_disable_1', array('engine' => 'File', 'path' => TMP . 'tests')); + + $this->assertTrue(Cache::write('key_1', 'hello', 'test_cache_disable_1')); + $this->assertSame(Cache::read('key_1', 'test_cache_disable_1'), 'hello'); + + Configure::write('Cache.disable', true); + + $this->assertFalse(Cache::write('key_2', 'hello', 'test_cache_disable_1')); + $this->assertFalse(Cache::read('key_2', 'test_cache_disable_1')); + + Configure::write('Cache.disable', false); + + $this->assertTrue(Cache::write('key_3', 'hello', 'test_cache_disable_1')); + $this->assertSame(Cache::read('key_3', 'test_cache_disable_1'), 'hello'); + + Configure::write('Cache.disable', true); + Cache::config('test_cache_disable_2', array('engine' => 'File', 'path' => TMP . 'tests')); + + $this->assertFalse(Cache::write('key_4', 'hello', 'test_cache_disable_2')); + $this->assertFalse(Cache::read('key_4', 'test_cache_disable_2')); + + Configure::write('Cache.disable', false); + + $this->assertTrue(Cache::write('key_5', 'hello', 'test_cache_disable_2')); + $this->assertSame(Cache::read('key_5', 'test_cache_disable_2'), 'hello'); + + Configure::write('Cache.disable', true); + + $this->assertFalse(Cache::write('key_6', 'hello', 'test_cache_disable_2')); + $this->assertFalse(Cache::read('key_6', 'test_cache_disable_2')); + } + +/** + * testSet method + * + * @return void + */ + public function testSet() { + $_cacheSet = Cache::set(); + + Cache::set(array('duration' => '+1 year')); + $data = Cache::read('test_cache'); + $this->assertFalse($data); + + $data = 'this is just a simple test of the cache system'; + $write = Cache::write('test_cache', $data); + $this->assertTrue($write); + + Cache::set(array('duration' => '+1 year')); + $data = Cache::read('test_cache'); + $this->assertEquals('this is just a simple test of the cache system', $data); + + Cache::delete('test_cache'); + + $global = Cache::settings(); + + Cache::set($_cacheSet); + } + +/** + * test set() parameter handling for user cache configs. + * + * @return void + */ + public function testSetOnAlternateConfigs() { + Cache::config('file_config', array('engine' => 'File', 'prefix' => 'test_file_')); + Cache::set(array('duration' => '+1 year'), 'file_config'); + $settings = Cache::settings('file_config'); + + $this->assertEquals('test_file_', $settings['prefix']); + $this->assertEquals(strtotime('+1 year') - time(), $settings['duration']); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Cache/Engine/ApcEngineTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Cache/Engine/ApcEngineTest.php new file mode 100644 index 0000000..d1e7605 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Cache/Engine/ApcEngineTest.php @@ -0,0 +1,273 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Cache.Engine + * @since CakePHP(tm) v 1.2.0.5434 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ + +App::uses('Cache', 'Cache'); + +/** + * ApcEngineTest class + * + * @package Cake.Test.Case.Cache.Engine + */ +class ApcEngineTest extends CakeTestCase { + +/** + * setUp method + * + * @return void + */ + public function setUp() { + parent::setUp(); + $this->skipIf(!function_exists('apc_store'), 'Apc is not installed or configured properly.'); + + $this->_cacheDisable = Configure::read('Cache.disable'); + Configure::write('Cache.disable', false); + Cache::config('apc', array('engine' => 'Apc', 'prefix' => 'cake_')); + } + +/** + * tearDown method + * + * @return void + */ + public function tearDown() { + parent::tearDown(); + Configure::write('Cache.disable', $this->_cacheDisable); + Cache::drop('apc'); + Cache::drop('apc_groups'); + Cache::config('default'); + } + +/** + * testReadAndWriteCache method + * + * @return void + */ + public function testReadAndWriteCache() { + Cache::set(array('duration' => 1), 'apc'); + + $result = Cache::read('test', 'apc'); + $expecting = ''; + $this->assertEquals($expecting, $result); + + $data = 'this is a test of the emergency broadcasting system'; + $result = Cache::write('test', $data, 'apc'); + $this->assertTrue($result); + + $result = Cache::read('test', 'apc'); + $expecting = $data; + $this->assertEquals($expecting, $result); + + Cache::delete('test', 'apc'); + } + +/** + * Writing cache entries with duration = 0 (forever) should work. + * + * @return void + */ + public function testReadWriteDurationZero() { + Cache::config('apc', array('engine' => 'Apc', 'duration' => 0, 'prefix' => 'cake_')); + Cache::write('zero', 'Should save', 'apc'); + sleep(1); + + $result = Cache::read('zero', 'apc'); + $this->assertEquals('Should save', $result); + } + +/** + * testExpiry method + * + * @return void + */ + public function testExpiry() { + Cache::set(array('duration' => 1), 'apc'); + + $result = Cache::read('test', 'apc'); + $this->assertFalse($result); + + $data = 'this is a test of the emergency broadcasting system'; + $result = Cache::write('other_test', $data, 'apc'); + $this->assertTrue($result); + + sleep(2); + $result = Cache::read('other_test', 'apc'); + $this->assertFalse($result); + + Cache::set(array('duration' => 1), 'apc'); + + $data = 'this is a test of the emergency broadcasting system'; + $result = Cache::write('other_test', $data, 'apc'); + $this->assertTrue($result); + + sleep(2); + $result = Cache::read('other_test', 'apc'); + $this->assertFalse($result); + + sleep(2); + $result = Cache::read('other_test', 'apc'); + $this->assertFalse($result); + } + +/** + * testDeleteCache method + * + * @return void + */ + public function testDeleteCache() { + $data = 'this is a test of the emergency broadcasting system'; + $result = Cache::write('delete_test', $data, 'apc'); + $this->assertTrue($result); + + $result = Cache::delete('delete_test', 'apc'); + $this->assertTrue($result); + } + +/** + * testDecrement method + * + * @return void + */ + public function testDecrement() { + $this->skipIf(!function_exists('apc_dec'), 'No apc_dec() function, cannot test decrement().'); + + $result = Cache::write('test_decrement', 5, 'apc'); + $this->assertTrue($result); + + $result = Cache::decrement('test_decrement', 1, 'apc'); + $this->assertEquals(4, $result); + + $result = Cache::read('test_decrement', 'apc'); + $this->assertEquals(4, $result); + + $result = Cache::decrement('test_decrement', 2, 'apc'); + $this->assertEquals(2, $result); + + $result = Cache::read('test_decrement', 'apc'); + $this->assertEquals(2, $result); + } + +/** + * testIncrement method + * + * @return void + */ + public function testIncrement() { + $this->skipIf(!function_exists('apc_inc'), 'No apc_inc() function, cannot test increment().'); + + $result = Cache::write('test_increment', 5, 'apc'); + $this->assertTrue($result); + + $result = Cache::increment('test_increment', 1, 'apc'); + $this->assertEquals(6, $result); + + $result = Cache::read('test_increment', 'apc'); + $this->assertEquals(6, $result); + + $result = Cache::increment('test_increment', 2, 'apc'); + $this->assertEquals(8, $result); + + $result = Cache::read('test_increment', 'apc'); + $this->assertEquals(8, $result); + } + +/** + * test the clearing of cache keys + * + * @return void + */ + public function testClear() { + apc_store('not_cake', 'survive'); + Cache::write('some_value', 'value', 'apc'); + + $result = Cache::clear(false, 'apc'); + $this->assertTrue($result); + $this->assertFalse(Cache::read('some_value', 'apc')); + $this->assertEquals('survive', apc_fetch('not_cake')); + apc_delete('not_cake'); + } + +/** + * Tests that configuring groups for stored keys return the correct values when read/written + * Shows that altering the group value is equivalent to deleting all keys under the same + * group + * + * @return void + */ + public function testGroupsReadWrite() { + Cache::config('apc_groups', array( + 'engine' => 'Apc', + 'duration' => 0, + 'groups' => array('group_a', 'group_b'), + 'prefix' => 'test_' + )); + $this->assertTrue(Cache::write('test_groups', 'value', 'apc_groups')); + $this->assertEquals('value', Cache::read('test_groups', 'apc_groups')); + + apc_inc('test_group_a'); + $this->assertFalse(Cache::read('test_groups', 'apc_groups')); + $this->assertTrue(Cache::write('test_groups', 'value2', 'apc_groups')); + $this->assertEquals('value2', Cache::read('test_groups', 'apc_groups')); + + apc_inc('test_group_b'); + $this->assertFalse(Cache::read('test_groups', 'apc_groups')); + $this->assertTrue(Cache::write('test_groups', 'value3', 'apc_groups')); + $this->assertEquals('value3', Cache::read('test_groups', 'apc_groups')); + } + +/** + * Tests that deleteing from a groups-enabled config is possible + * + * @return void + */ + public function testGroupDelete() { + Cache::config('apc_groups', array( + 'engine' => 'Apc', + 'duration' => 0, + 'groups' => array('group_a', 'group_b'), + 'prefix' => 'test_' + )); + $this->assertTrue(Cache::write('test_groups', 'value', 'apc_groups')); + $this->assertEquals('value', Cache::read('test_groups', 'apc_groups')); + $this->assertTrue(Cache::delete('test_groups', 'apc_groups')); + + $this->assertFalse(Cache::read('test_groups', 'apc_groups')); + } + +/** + * Test clearing a cache group + * + * @return void + **/ + public function testGroupClear() { + Cache::config('apc_groups', array( + 'engine' => 'Apc', + 'duration' => 0, + 'groups' => array('group_a', 'group_b'), + 'prefix' => 'test_' + )); + + $this->assertTrue(Cache::write('test_groups', 'value', 'apc_groups')); + $this->assertTrue(Cache::clearGroup('group_a', 'apc_groups')); + $this->assertFalse(Cache::read('test_groups', 'apc_groups')); + + $this->assertTrue(Cache::write('test_groups', 'value2', 'apc_groups')); + $this->assertTrue(Cache::clearGroup('group_b', 'apc_groups')); + $this->assertFalse(Cache::read('test_groups', 'apc_groups')); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Cache/Engine/FileEngineTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Cache/Engine/FileEngineTest.php new file mode 100644 index 0000000..a091fbd --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Cache/Engine/FileEngineTest.php @@ -0,0 +1,455 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Cache.Engine + * @since CakePHP(tm) v 1.2.0.5434 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ + +App::uses('Cache', 'Cache'); + +/** + * FileEngineTest class + * + * @package Cake.Test.Case.Cache.Engine + */ +class FileEngineTest extends CakeTestCase { + +/** + * config property + * + * @var array + */ + public $config = array(); + +/** + * setUp method + * + * @return void + */ + public function setUp() { + parent::setUp(); + Configure::write('Cache.disable', false); + Cache::config('file_test', array('engine' => 'File', 'path' => CACHE)); + } + +/** + * tearDown method + * + * @return void + */ + public function tearDown() { + parent::tearDown(); + Cache::clear(false, 'file_test'); + Cache::drop('file_test'); + Cache::drop('file_groups'); + Cache::drop('file_groups2'); + Cache::drop('file_groups3'); + } + +/** + * testCacheDirChange method + * + * @return void + */ + public function testCacheDirChange() { + $result = Cache::config('sessions', array('engine' => 'File', 'path' => TMP . 'sessions')); + $this->assertEquals(Cache::settings('sessions'), $result['settings']); + + $result = Cache::config('sessions', array('engine' => 'File', 'path' => TMP . 'tests')); + $this->assertEquals(Cache::settings('sessions'), $result['settings']); + $this->assertNotEquals(Cache::settings('default'), $result['settings']); + } + +/** + * testReadAndWriteCache method + * + * @return void + */ + public function testReadAndWriteCache() { + Cache::config('default'); + + $result = Cache::write(null, 'here', 'file_test'); + $this->assertFalse($result); + + Cache::set(array('duration' => 1), 'file_test'); + + $result = Cache::read('test', 'file_test'); + $expecting = ''; + $this->assertEquals($expecting, $result); + + $data = 'this is a test of the emergency broadcasting system'; + $result = Cache::write('test', $data, 'file_test'); + $this->assertTrue(file_exists(CACHE . 'cake_test')); + + $result = Cache::read('test', 'file_test'); + $expecting = $data; + $this->assertEquals($expecting, $result); + + Cache::delete('test', 'file_test'); + } + +/** + * Test read/write on the same cache key. Ensures file handles are re-wound. + * + * @return void + */ + public function testConsecutiveReadWrite() { + Cache::write('rw', 'first write', 'file_test'); + $result = Cache::read('rw', 'file_test'); + + Cache::write('rw', 'second write', 'file_test'); + $resultB = Cache::read('rw', 'file_test'); + + Cache::delete('rw', 'file_test'); + $this->assertEquals('first write', $result); + $this->assertEquals('second write', $resultB); + } + +/** + * testExpiry method + * + * @return void + */ + public function testExpiry() { + Cache::set(array('duration' => 1), 'file_test'); + + $result = Cache::read('test', 'file_test'); + $this->assertFalse($result); + + $data = 'this is a test of the emergency broadcasting system'; + $result = Cache::write('other_test', $data, 'file_test'); + $this->assertTrue($result); + + sleep(2); + $result = Cache::read('other_test', 'file_test'); + $this->assertFalse($result); + + Cache::set(array('duration' => "+1 second"), 'file_test'); + + $data = 'this is a test of the emergency broadcasting system'; + $result = Cache::write('other_test', $data, 'file_test'); + $this->assertTrue($result); + + sleep(2); + $result = Cache::read('other_test', 'file_test'); + $this->assertFalse($result); + } + +/** + * testDeleteCache method + * + * @return void + */ + public function testDeleteCache() { + $data = 'this is a test of the emergency broadcasting system'; + $result = Cache::write('delete_test', $data, 'file_test'); + $this->assertTrue($result); + + $result = Cache::delete('delete_test', 'file_test'); + $this->assertTrue($result); + $this->assertFalse(file_exists(TMP . 'tests' . DS . 'delete_test')); + + $result = Cache::delete('delete_test', 'file_test'); + $this->assertFalse($result); + } + +/** + * testSerialize method + * + * @return void + */ + public function testSerialize() { + Cache::config('file_test', array('engine' => 'File', 'serialize' => true)); + $data = 'this is a test of the emergency broadcasting system'; + $write = Cache::write('serialize_test', $data, 'file_test'); + $this->assertTrue($write); + + Cache::config('file_test', array('serialize' => false)); + $read = Cache::read('serialize_test', 'file_test'); + + $newread = Cache::read('serialize_test', 'file_test'); + + $delete = Cache::delete('serialize_test', 'file_test'); + + $this->assertSame($read, serialize($data)); + + $this->assertSame(unserialize($newread), $data); + } + +/** + * testClear method + * + * @return void + */ + public function testClear() { + Cache::config('file_test', array('engine' => 'File', 'duration' => 1)); + + $data = 'this is a test of the emergency broadcasting system'; + $write = Cache::write('serialize_test1', $data, 'file_test'); + $write = Cache::write('serialize_test2', $data, 'file_test'); + $write = Cache::write('serialize_test3', $data, 'file_test'); + $this->assertTrue(file_exists(CACHE . 'cake_serialize_test1')); + $this->assertTrue(file_exists(CACHE . 'cake_serialize_test2')); + $this->assertTrue(file_exists(CACHE . 'cake_serialize_test3')); + sleep(2); + $result = Cache::clear(true, 'file_test'); + $this->assertTrue($result); + $this->assertFalse(file_exists(CACHE . 'cake_serialize_test1')); + $this->assertFalse(file_exists(CACHE . 'cake_serialize_test2')); + $this->assertFalse(file_exists(CACHE . 'cake_serialize_test3')); + + $data = 'this is a test of the emergency broadcasting system'; + $write = Cache::write('serialize_test1', $data, 'file_test'); + $write = Cache::write('serialize_test2', $data, 'file_test'); + $write = Cache::write('serialize_test3', $data, 'file_test'); + $this->assertTrue(file_exists(CACHE . 'cake_serialize_test1')); + $this->assertTrue(file_exists(CACHE . 'cake_serialize_test2')); + $this->assertTrue(file_exists(CACHE . 'cake_serialize_test3')); + + $result = Cache::clear(false, 'file_test'); + $this->assertTrue($result); + $this->assertFalse(file_exists(CACHE . 'cake_serialize_test1')); + $this->assertFalse(file_exists(CACHE . 'cake_serialize_test2')); + $this->assertFalse(file_exists(CACHE . 'cake_serialize_test3')); + } + +/** + * test that clear() doesn't wipe files not in the current engine's prefix. + * + * @return void + */ + public function testClearWithPrefixes() { + $FileOne = new FileEngine(); + $FileOne->init(array( + 'prefix' => 'prefix_one_', + 'duration' => DAY + )); + $FileTwo = new FileEngine(); + $FileTwo->init(array( + 'prefix' => 'prefix_two_', + 'duration' => DAY + )); + + $dataOne = $dataTwo = $expected = 'content to cache'; + $FileOne->write('prefix_one_key_one', $dataOne, DAY); + $FileTwo->write('prefix_two_key_two', $dataTwo, DAY); + + $this->assertEquals($expected, $FileOne->read('prefix_one_key_one')); + $this->assertEquals($expected, $FileTwo->read('prefix_two_key_two')); + + $FileOne->clear(false); + $this->assertEquals($expected, $FileTwo->read('prefix_two_key_two'), 'secondary config was cleared by accident.'); + $FileTwo->clear(false); + } + +/** + * testKeyPath method + * + * @return void + */ + public function testKeyPath() { + $result = Cache::write('views.countries.something', 'here', 'file_test'); + $this->assertTrue($result); + $this->assertTrue(file_exists(CACHE . 'cake_views_countries_something')); + + $result = Cache::read('views.countries.something', 'file_test'); + $this->assertEquals('here', $result); + + $result = Cache::clear(false, 'file_test'); + $this->assertTrue($result); + } + +/** + * testRemoveWindowsSlashesFromCache method + * + * @return void + */ + public function testRemoveWindowsSlashesFromCache() { + Cache::config('windows_test', array('engine' => 'File', 'isWindows' => true, 'prefix' => null, 'path' => TMP)); + + $expected = array( + 'C:\dev\prj2\sites\cake\libs' => array( + 0 => 'C:\dev\prj2\sites\cake\libs', 1 => 'C:\dev\prj2\sites\cake\libs\view', + 2 => 'C:\dev\prj2\sites\cake\libs\view\scaffolds', 3 => 'C:\dev\prj2\sites\cake\libs\view\pages', + 4 => 'C:\dev\prj2\sites\cake\libs\view\layouts', 5 => 'C:\dev\prj2\sites\cake\libs\view\layouts\xml', + 6 => 'C:\dev\prj2\sites\cake\libs\view\layouts\rss', 7 => 'C:\dev\prj2\sites\cake\libs\view\layouts\js', + 8 => 'C:\dev\prj2\sites\cake\libs\view\layouts\email', 9 => 'C:\dev\prj2\sites\cake\libs\view\layouts\email\text', + 10 => 'C:\dev\prj2\sites\cake\libs\view\layouts\email\html', 11 => 'C:\dev\prj2\sites\cake\libs\view\helpers', + 12 => 'C:\dev\prj2\sites\cake\libs\view\errors', 13 => 'C:\dev\prj2\sites\cake\libs\view\elements', + 14 => 'C:\dev\prj2\sites\cake\libs\view\elements\email', 15 => 'C:\dev\prj2\sites\cake\libs\view\elements\email\text', + 16 => 'C:\dev\prj2\sites\cake\libs\view\elements\email\html', 17 => 'C:\dev\prj2\sites\cake\libs\model', + 18 => 'C:\dev\prj2\sites\cake\libs\model\datasources', 19 => 'C:\dev\prj2\sites\cake\libs\model\datasources\dbo', + 20 => 'C:\dev\prj2\sites\cake\libs\model\behaviors', 21 => 'C:\dev\prj2\sites\cake\libs\controller', + 22 => 'C:\dev\prj2\sites\cake\libs\controller\components', 23 => 'C:\dev\prj2\sites\cake\libs\cache'), + 'C:\dev\prj2\sites\main_site\vendors' => array( + 0 => 'C:\dev\prj2\sites\main_site\vendors', 1 => 'C:\dev\prj2\sites\main_site\vendors\shells', + 2 => 'C:\dev\prj2\sites\main_site\vendors\shells\templates', 3 => 'C:\dev\prj2\sites\main_site\vendors\shells\templates\cdc_project', + 4 => 'C:\dev\prj2\sites\main_site\vendors\shells\tasks', 5 => 'C:\dev\prj2\sites\main_site\vendors\js', + 6 => 'C:\dev\prj2\sites\main_site\vendors\css'), + 'C:\dev\prj2\sites\vendors' => array( + 0 => 'C:\dev\prj2\sites\vendors', 1 => 'C:\dev\prj2\sites\vendors\simpletest', + 2 => 'C:\dev\prj2\sites\vendors\simpletest\test', 3 => 'C:\dev\prj2\sites\vendors\simpletest\test\support', + 4 => 'C:\dev\prj2\sites\vendors\simpletest\test\support\collector', 5 => 'C:\dev\prj2\sites\vendors\simpletest\extensions', + 6 => 'C:\dev\prj2\sites\vendors\simpletest\extensions\testdox', 7 => 'C:\dev\prj2\sites\vendors\simpletest\docs', + 8 => 'C:\dev\prj2\sites\vendors\simpletest\docs\fr', 9 => 'C:\dev\prj2\sites\vendors\simpletest\docs\en'), + 'C:\dev\prj2\sites\main_site\views\helpers' => array( + 0 => 'C:\dev\prj2\sites\main_site\views\helpers') + ); + + Cache::write('test_dir_map', $expected, 'windows_test'); + $data = Cache::read('test_dir_map', 'windows_test'); + Cache::delete('test_dir_map', 'windows_test'); + $this->assertEquals($expected, $data); + + Cache::drop('windows_test'); + } + +/** + * testWriteQuotedString method + * + * @return void + */ + public function testWriteQuotedString() { + Cache::config('file_test', array('engine' => 'File', 'path' => TMP . 'tests')); + Cache::write('App.doubleQuoteTest', '"this is a quoted string"', 'file_test'); + $this->assertSame(Cache::read('App.doubleQuoteTest', 'file_test'), '"this is a quoted string"'); + Cache::write('App.singleQuoteTest', "'this is a quoted string'", 'file_test'); + $this->assertSame(Cache::read('App.singleQuoteTest', 'file_test'), "'this is a quoted string'"); + + Cache::config('file_test', array('isWindows' => true, 'path' => TMP . 'tests')); + $this->assertSame(Cache::read('App.doubleQuoteTest', 'file_test'), '"this is a quoted string"'); + Cache::write('App.singleQuoteTest', "'this is a quoted string'", 'file_test'); + $this->assertSame(Cache::read('App.singleQuoteTest', 'file_test'), "'this is a quoted string'"); + Cache::delete('App.singleQuoteTest', 'file_test'); + Cache::delete('App.doubleQuoteTest', 'file_test'); + } + +/** + * check that FileEngine generates an error when a configured Path does not exist. + * + * @expectedException PHPUnit_Framework_Error_Warning + * @return void + */ + public function testErrorWhenPathDoesNotExist() { + $this->skipIf(is_dir(TMP . 'tests' . DS . 'file_failure'), 'Cannot run test directory exists.'); + + Cache::config('failure', array( + 'engine' => 'File', + 'path' => TMP . 'tests' . DS . 'file_failure' + )); + + Cache::drop('failure'); + } + +/** + * Testing the mask setting in FileEngine + * + * @return void + */ + public function testMaskSetting() { + if (DS === '\\') { + $this->markTestSkipped('File permission testing does not work on Windows.'); + } + Cache::config('mask_test', array('engine' => 'File', 'path' => TMP . 'tests')); + $data = 'This is some test content'; + $write = Cache::write('masking_test', $data, 'mask_test'); + $result = substr(sprintf('%o',fileperms(TMP . 'tests' . DS . 'cake_masking_test')), -4); + $expected = '0664'; + $this->assertEquals($expected, $result); + Cache::delete('masking_test', 'mask_test'); + Cache::drop('mask_test'); + + Cache::config('mask_test', array('engine' => 'File', 'mask' => 0666, 'path' => TMP . 'tests')); + $write = Cache::write('masking_test', $data, 'mask_test'); + $result = substr(sprintf('%o',fileperms(TMP . 'tests' . DS . 'cake_masking_test')), -4); + $expected = '0666'; + $this->assertEquals($expected, $result); + Cache::delete('masking_test', 'mask_test'); + Cache::drop('mask_test'); + + Cache::config('mask_test', array('engine' => 'File', 'mask' => 0644, 'path' => TMP . 'tests')); + $write = Cache::write('masking_test', $data, 'mask_test'); + $result = substr(sprintf('%o',fileperms(TMP . 'tests' . DS . 'cake_masking_test')), -4); + $expected = '0644'; + $this->assertEquals($expected, $result); + Cache::delete('masking_test', 'mask_test'); + Cache::drop('mask_test'); + + Cache::config('mask_test', array('engine' => 'File', 'mask' => 0640, 'path' => TMP . 'tests')); + $write = Cache::write('masking_test', $data, 'mask_test'); + $result = substr(sprintf('%o',fileperms(TMP . 'tests' . DS . 'cake_masking_test')), -4); + $expected = '0640'; + $this->assertEquals($expected, $result); + Cache::delete('masking_test', 'mask_test'); + Cache::drop('mask_test'); + } + +/** + * Tests that configuring groups for stored keys return the correct values when read/written + * + * @return void + */ + public function testGroupsReadWrite() { + Cache::config('file_groups', array('engine' => 'File', 'duration' => 3600, 'groups' => array('group_a', 'group_b'))); + $this->assertTrue(Cache::write('test_groups', 'value', 'file_groups')); + $this->assertEquals('value', Cache::read('test_groups', 'file_groups')); + + $this->assertTrue(Cache::write('test_groups2', 'value2', 'file_groups')); + $this->assertTrue(Cache::write('test_groups3', 'value3', 'file_groups')); + } + +/** + * Tests that deleteing from a groups-enabled config is possible + * + * @return void + */ + public function testGroupDelete() { + Cache::config('file_groups', array('engine' => 'File', 'duration' => 3600, 'groups' => array('group_a', 'group_b'))); + $this->assertTrue(Cache::write('test_groups', 'value', 'file_groups')); + $this->assertEquals('value', Cache::read('test_groups', 'file_groups')); + $this->assertTrue(Cache::delete('test_groups', 'file_groups')); + + $this->assertFalse(Cache::read('test_groups', 'file_groups')); + } + +/** + * Test clearing a cache group + * + * @return void + **/ + public function testGroupClear() { + Cache::config('file_groups', array('engine' => 'File', 'duration' => 3600, 'groups' => array('group_a', 'group_b'))); + Cache::config('file_groups2', array('engine' => 'File', 'duration' => 3600, 'groups' => array('group_b'))); + Cache::config('file_groups3', array('engine' => 'File', 'duration' => 3600, 'groups' => array('group_a'))); + + $this->assertTrue(Cache::write('test_groups', 'value', 'file_groups')); + $this->assertTrue(Cache::write('test_groups2', 'value', 'file_groups2')); + $this->assertTrue(Cache::write('test_groups3', 'value', 'file_groups3')); + + $this->assertTrue(Cache::clearGroup('group_a', 'file_groups')); + $this->assertFalse(Cache::read('test_groups', 'file_groups')); + $this->assertEquals('value', Cache::read('test_groups2', 'file_groups2')); + $this->assertFalse(Cache::read('test_groups3', 'file_groups3')); + + $this->assertTrue(Cache::write('test_groups4', 'value', 'file_groups')); + $this->assertTrue(Cache::write('test_groups5', 'value', 'file_groups2')); + $this->assertTrue(Cache::write('test_groups6', 'value', 'file_groups3')); + + $this->assertTrue(Cache::clearGroup('group_b', 'file_groups')); + $this->assertFalse(Cache::read('test_groups4', 'file_groups')); + $this->assertFalse(Cache::read('test_groups5', 'file_groups2')); + $this->assertEquals('value', Cache::read('test_groups6', 'file_groups3')); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Cache/Engine/MemcacheEngineTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Cache/Engine/MemcacheEngineTest.php new file mode 100644 index 0000000..a1c2abd --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Cache/Engine/MemcacheEngineTest.php @@ -0,0 +1,479 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Cache.Engine + * @since CakePHP(tm) v 1.2.0.5434 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ + +App::uses('Cache', 'Cache'); +App::uses('MemcacheEngine', 'Cache/Engine'); + +class TestMemcacheEngine extends MemcacheEngine { + +/** + * public accessor to _parseServerString + * + * @param string $server + * @return array + */ + public function parseServerString($server) { + return $this->_parseServerString($server); + } + + public function setMemcache($memcache) { + $this->_Memcache = $memcache; + } + +} + +/** + * MemcacheEngineTest class + * + * @package Cake.Test.Case.Cache.Engine + */ +class MemcacheEngineTest extends CakeTestCase { + +/** + * setUp method + * + * @return void + */ + public function setUp() { + parent::setUp(); + $this->skipIf(!class_exists('Memcache'), 'Memcache is not installed or configured properly.'); + + $this->_cacheDisable = Configure::read('Cache.disable'); + Configure::write('Cache.disable', false); + Cache::config('memcache', array( + 'engine' => 'Memcache', + 'prefix' => 'cake_', + 'duration' => 3600 + )); + } + +/** + * tearDown method + * + * @return void + */ + public function tearDown() { + parent::tearDown(); + Configure::write('Cache.disable', $this->_cacheDisable); + Cache::drop('memcache'); + Cache::drop('memcache_groups'); + Cache::drop('memcache_helper'); + Cache::config('default'); + } + +/** + * testSettings method + * + * @return void + */ + public function testSettings() { + $settings = Cache::settings('memcache'); + unset($settings['serialize'], $settings['path']); + $expecting = array( + 'prefix' => 'cake_', + 'duration' => 3600, + 'probability' => 100, + 'servers' => array('127.0.0.1'), + 'persistent' => true, + 'compress' => false, + 'engine' => 'Memcache', + 'persistent' => true, + 'groups' => array() + ); + $this->assertEquals($expecting, $settings); + } + +/** + * testSettings method + * + * @return void + */ + public function testMultipleServers() { + $servers = array('127.0.0.1:11211', '127.0.0.1:11222'); + $available = true; + $Memcache = new Memcache(); + + foreach ($servers as $server) { + list($host, $port) = explode(':', $server); + if (!@$Memcache->connect($host, $port)) { + $available = false; + } + } + + $this->skipIf(!$available, 'Need memcache servers at ' . implode(', ', $servers) . ' to run this test.'); + + $Memcache = new MemcacheEngine(); + $Memcache->init(array('engine' => 'Memcache', 'servers' => $servers)); + + $servers = array_keys($Memcache->__Memcache->getExtendedStats()); + $settings = $Memcache->settings(); + $this->assertEquals($settings['servers'], $servers); + Cache::drop('dual_server'); + } + +/** + * testConnect method + * + * @return void + */ + public function testConnect() { + $Memcache = new MemcacheEngine(); + $Memcache->init(Cache::settings('memcache')); + $result = $Memcache->connect('127.0.0.1'); + $this->assertTrue($result); + } + +/** + * test connecting to an ipv6 server. + * + * @return void + */ + public function testConnectIpv6() { + $Memcache = new MemcacheEngine(); + $result = $Memcache->init(array( + 'prefix' => 'cake_', + 'duration' => 200, + 'engine' => 'Memcache', + 'servers' => array( + '[::1]:11211' + ) + )); + $this->assertTrue($result); + } + +/** + * test non latin domains. + * + * @return void + */ + public function testParseServerStringNonLatin() { + $Memcache = new TestMemcacheEngine(); + $result = $Memcache->parseServerString('schülervz.net:13211'); + $this->assertEquals(array('schülervz.net', '13211'), $result); + + $result = $Memcache->parseServerString('sülül:1111'); + $this->assertEquals(array('sülül', '1111'), $result); + } + +/** + * test unix sockets. + * + * @return void + */ + public function testParseServerStringUnix() { + $Memcache = new TestMemcacheEngine(); + $result = $Memcache->parseServerString('unix:///path/to/memcached.sock'); + $this->assertEquals(array('unix:///path/to/memcached.sock', 0), $result); + } + +/** + * testReadAndWriteCache method + * + * @return void + */ + public function testReadAndWriteCache() { + Cache::set(array('duration' => 1), null, 'memcache'); + + $result = Cache::read('test', 'memcache'); + $expecting = ''; + $this->assertEquals($expecting, $result); + + $data = 'this is a test of the emergency broadcasting system'; + $result = Cache::write('test', $data, 'memcache'); + $this->assertTrue($result); + + $result = Cache::read('test', 'memcache'); + $expecting = $data; + $this->assertEquals($expecting, $result); + + Cache::delete('test', 'memcache'); + } + +/** + * testExpiry method + * + * @return void + */ + public function testExpiry() { + Cache::set(array('duration' => 1), 'memcache'); + + $result = Cache::read('test', 'memcache'); + $this->assertFalse($result); + + $data = 'this is a test of the emergency broadcasting system'; + $result = Cache::write('other_test', $data, 'memcache'); + $this->assertTrue($result); + + sleep(2); + $result = Cache::read('other_test', 'memcache'); + $this->assertFalse($result); + + Cache::set(array('duration' => "+1 second"), 'memcache'); + + $data = 'this is a test of the emergency broadcasting system'; + $result = Cache::write('other_test', $data, 'memcache'); + $this->assertTrue($result); + + sleep(2); + $result = Cache::read('other_test', 'memcache'); + $this->assertFalse($result); + + Cache::config('memcache', array('duration' => '+1 second')); + sleep(2); + + $result = Cache::read('other_test', 'memcache'); + $this->assertFalse($result); + + Cache::config('memcache', array('duration' => '+29 days')); + $data = 'this is a test of the emergency broadcasting system'; + $result = Cache::write('long_expiry_test', $data, 'memcache'); + $this->assertTrue($result); + + sleep(2); + $result = Cache::read('long_expiry_test', 'memcache'); + $expecting = $data; + $this->assertEquals($expecting, $result); + + Cache::config('memcache', array('duration' => 3600)); + } + +/** + * testDeleteCache method + * + * @return void + */ + public function testDeleteCache() { + $data = 'this is a test of the emergency broadcasting system'; + $result = Cache::write('delete_test', $data, 'memcache'); + $this->assertTrue($result); + + $result = Cache::delete('delete_test', 'memcache'); + $this->assertTrue($result); + } + +/** + * testDecrement method + * + * @return void + */ + public function testDecrement() { + $result = Cache::write('test_decrement', 5, 'memcache'); + $this->assertTrue($result); + + $result = Cache::decrement('test_decrement', 1, 'memcache'); + $this->assertEquals(4, $result); + + $result = Cache::read('test_decrement', 'memcache'); + $this->assertEquals(4, $result); + + $result = Cache::decrement('test_decrement', 2, 'memcache'); + $this->assertEquals(2, $result); + + $result = Cache::read('test_decrement', 'memcache'); + $this->assertEquals(2, $result); + } + +/** + * testIncrement method + * + * @return void + */ + public function testIncrement() { + $result = Cache::write('test_increment', 5, 'memcache'); + $this->assertTrue($result); + + $result = Cache::increment('test_increment', 1, 'memcache'); + $this->assertEquals(6, $result); + + $result = Cache::read('test_increment', 'memcache'); + $this->assertEquals(6, $result); + + $result = Cache::increment('test_increment', 2, 'memcache'); + $this->assertEquals(8, $result); + + $result = Cache::read('test_increment', 'memcache'); + $this->assertEquals(8, $result); + } + +/** + * test that configurations don't conflict, when a file engine is declared after a memcache one. + * + * @return void + */ + public function testConfigurationConflict() { + Cache::config('long_memcache', array( + 'engine' => 'Memcache', + 'duration' => '+2 seconds', + 'servers' => array('127.0.0.1:11211'), + )); + Cache::config('short_memcache', array( + 'engine' => 'Memcache', + 'duration' => '+1 seconds', + 'servers' => array('127.0.0.1:11211'), + )); + Cache::config('some_file', array('engine' => 'File')); + + $this->assertTrue(Cache::write('duration_test', 'yay', 'long_memcache')); + $this->assertTrue(Cache::write('short_duration_test', 'boo', 'short_memcache')); + + $this->assertEquals('yay', Cache::read('duration_test', 'long_memcache'), 'Value was not read %s'); + $this->assertEquals('boo', Cache::read('short_duration_test', 'short_memcache'), 'Value was not read %s'); + + sleep(1); + $this->assertEquals('yay', Cache::read('duration_test', 'long_memcache'), 'Value was not read %s'); + + sleep(2); + $this->assertFalse(Cache::read('short_duration_test', 'short_memcache'), 'Cache was not invalidated %s'); + $this->assertFalse(Cache::read('duration_test', 'long_memcache'), 'Value did not expire %s'); + + Cache::delete('duration_test', 'long_memcache'); + Cache::delete('short_duration_test', 'short_memcache'); + } + +/** + * test clearing memcache. + * + * @return void + */ + public function testClear() { + Cache::config('memcache2', array( + 'engine' => 'Memcache', + 'prefix' => 'cake2_', + 'duration' => 3600 + )); + + Cache::write('some_value', 'cache1', 'memcache'); + $result = Cache::clear(true, 'memcache'); + $this->assertTrue($result); + $this->assertEquals('cache1', Cache::read('some_value', 'memcache')); + + Cache::write('some_value', 'cache2', 'memcache2'); + $result = Cache::clear(false, 'memcache'); + $this->assertTrue($result); + $this->assertFalse(Cache::read('some_value', 'memcache')); + $this->assertEquals('cache2', Cache::read('some_value', 'memcache2')); + + Cache::clear(false, 'memcache2'); + } + +/** + * test that a 0 duration can successfully write. + * + * @return void + */ + public function testZeroDuration() { + Cache::config('memcache', array('duration' => 0)); + $result = Cache::write('test_key', 'written!', 'memcache'); + + $this->assertTrue($result); + $result = Cache::read('test_key', 'memcache'); + $this->assertEquals('written!', $result); + } + +/** + * test that durations greater than 30 days never expire + * + * @return void + */ + public function testLongDurationEqualToZero() { + $memcache = new TestMemcacheEngine(); + $memcache->settings['compress'] = false; + + $mock = $this->getMock('Memcache'); + $memcache->setMemcache($mock); + $mock->expects($this->once()) + ->method('set') + ->with('key', 'value', false, 0); + + $value = 'value'; + $memcache->write('key', $value, 50 * DAY); + } + +/** + * Tests that configuring groups for stored keys return the correct values when read/written + * Shows that altering the group value is equivalent to deleting all keys under the same + * group + * + * @return void + */ + public function testGroupReadWrite() { + Cache::config('memcache_groups', array( + 'engine' => 'Memcache', + 'duration' => 3600, + 'groups' => array('group_a', 'group_b'), + 'prefix' => 'test_' + )); + Cache::config('memcache_helper', array( + 'engine' => 'Memcache', + 'duration' => 3600, + 'prefix' => 'test_' + )); + $this->assertTrue(Cache::write('test_groups', 'value', 'memcache_groups')); + $this->assertEquals('value', Cache::read('test_groups', 'memcache_groups')); + + Cache::increment('group_a', 1, 'memcache_helper'); + $this->assertFalse(Cache::read('test_groups', 'memcache_groups')); + $this->assertTrue(Cache::write('test_groups', 'value2', 'memcache_groups')); + $this->assertEquals('value2', Cache::read('test_groups', 'memcache_groups')); + + Cache::increment('group_b', 1, 'memcache_helper'); + $this->assertFalse(Cache::read('test_groups', 'memcache_groups')); + $this->assertTrue(Cache::write('test_groups', 'value3', 'memcache_groups')); + $this->assertEquals('value3', Cache::read('test_groups', 'memcache_groups')); + } + +/** + * Tests that deleteing from a groups-enabled config is possible + * + * @return void + */ + public function testGroupDelete() { + Cache::config('memcache_groups', array( + 'engine' => 'Memcache', + 'duration' => 3600, + 'groups' => array('group_a', 'group_b') + )); + $this->assertTrue(Cache::write('test_groups', 'value', 'memcache_groups')); + $this->assertEquals('value', Cache::read('test_groups', 'memcache_groups')); + $this->assertTrue(Cache::delete('test_groups', 'memcache_groups')); + + $this->assertFalse(Cache::read('test_groups', 'memcache_groups')); + } + +/** + * Test clearing a cache group + * + * @return void + **/ + public function testGroupClear() { + Cache::config('memcache_groups', array( + 'engine' => 'Memcache', + 'duration' => 3600, + 'groups' => array('group_a', 'group_b') + )); + + $this->assertTrue(Cache::write('test_groups', 'value', 'memcache_groups')); + $this->assertTrue(Cache::clearGroup('group_a', 'memcache_groups')); + $this->assertFalse(Cache::read('test_groups', 'memcache_groups')); + + $this->assertTrue(Cache::write('test_groups', 'value2', 'memcache_groups')); + $this->assertTrue(Cache::clearGroup('group_b', 'memcache_groups')); + $this->assertFalse(Cache::read('test_groups', 'memcache_groups')); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Cache/Engine/RedisEngineTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Cache/Engine/RedisEngineTest.php new file mode 100644 index 0000000..de4c50d --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Cache/Engine/RedisEngineTest.php @@ -0,0 +1,335 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/view/1196/Testing CakePHP(tm) Tests + * @package Cake.Test.Case.Cache.Engine + * @since CakePHP(tm) v 2.2 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ + +App::uses('Cache', 'Cache'); +App::uses('RedisEngine', 'Cache/Engine'); + +/** + * RedisEngineTest class + * + * @package Cake.Test.Case.Cache.Engine + */ +class RegisEngineTest extends CakeTestCase { + +/** + * setUp method + * + * @return void + */ + public function setUp() { + $this->skipIf(!class_exists('Redis'), 'Redis is not installed or configured properly.'); + + $this->_cacheDisable = Configure::read('Cache.disable'); + Configure::write('Cache.disable', false); + Cache::config('redis', array( + 'engine' => 'Redis', + 'prefix' => 'cake_', + 'duration' => 3600 + )); + } + +/** + * tearDown method + * + * @return void + */ + public function tearDown() { + Configure::write('Cache.disable', $this->_cacheDisable); + Cache::drop(''); + Cache::drop('redis_groups'); + Cache::drop('redis_helper'); + Cache::config('default'); + } + +/** + * testSettings method + * + * @return void + */ + public function testSettings() { + $settings = Cache::settings('redis'); + $expecting = array( + 'prefix' => 'cake_', + 'duration' => 3600, + 'probability' => 100, + 'groups' => array(), + 'engine' => 'Redis', + 'server' => '127.0.0.1', + 'port' => 6379, + 'timeout' => 0, + 'persistent' => true + ); + $this->assertEquals($expecting, $settings); + } + +/** + * testConnect method + * + * @return void + */ + public function testConnect() { + $Redis = new RedisEngine(); + $this->assertTrue($Redis->init(Cache::settings('redis'))); + } + +/** + * testReadAndWriteCache method + * + * @return void + */ + public function testReadAndWriteCache() { + Cache::set(array('duration' => 1), null, 'redis'); + + $result = Cache::read('test', 'redis'); + $expecting = ''; + $this->assertEquals($expecting, $result); + + $data = 'this is a test of the emergency broadcasting system'; + $result = Cache::write('test', $data, 'redis'); + $this->assertTrue($result); + + $result = Cache::read('test', 'redis'); + $expecting = $data; + $this->assertEquals($expecting, $result); + + $data = array(1, 2, 3); + $this->assertTrue(Cache::write('array_data', $data, 'redis')); + $this->assertEquals($data, Cache::read('array_data', 'redis')); + + Cache::delete('test', 'redis'); + } + +/** + * testExpiry method + * + * @return void + */ + public function testExpiry() { + Cache::set(array('duration' => 1), 'redis'); + + $result = Cache::read('test', 'redis'); + $this->assertFalse($result); + + $data = 'this is a test of the emergency broadcasting system'; + $result = Cache::write('other_test', $data, 'redis'); + $this->assertTrue($result); + + sleep(2); + $result = Cache::read('other_test', 'redis'); + $this->assertFalse($result); + + Cache::set(array('duration' => "+1 second"), 'redis'); + + $data = 'this is a test of the emergency broadcasting system'; + $result = Cache::write('other_test', $data, 'redis'); + $this->assertTrue($result); + + sleep(2); + $result = Cache::read('other_test', 'redis'); + $this->assertFalse($result); + + Cache::config('redis', array('duration' => '+1 second')); + sleep(2); + + $result = Cache::read('other_test', 'redis'); + $this->assertFalse($result); + + Cache::config('redis', array('duration' => '+29 days')); + $data = 'this is a test of the emergency broadcasting system'; + $result = Cache::write('long_expiry_test', $data, 'redis'); + $this->assertTrue($result); + + sleep(2); + $result = Cache::read('long_expiry_test', 'redis'); + $expecting = $data; + $this->assertEquals($expecting, $result); + + Cache::config('redis', array('duration' => 3600)); + } + +/** + * testDeleteCache method + * + * @return void + */ + public function testDeleteCache() { + $data = 'this is a test of the emergency broadcasting system'; + $result = Cache::write('delete_test', $data, 'redis'); + $this->assertTrue($result); + + $result = Cache::delete('delete_test', 'redis'); + $this->assertTrue($result); + } + +/** + * testDecrement method + * + * @return void + */ + public function testDecrement() { + Cache::delete('test_decrement', 'redis'); + $result = Cache::write('test_decrement', 5, 'redis'); + $this->assertTrue($result); + + $result = Cache::decrement('test_decrement', 1, 'redis'); + $this->assertEquals(4, $result); + + $result = Cache::read('test_decrement', 'redis'); + $this->assertEquals(4, $result); + + $result = Cache::decrement('test_decrement', 2, 'redis'); + $this->assertEquals(2, $result); + + $result = Cache::read('test_decrement', 'redis'); + $this->assertEquals(2, $result); + } + +/** + * testIncrement method + * + * @return void + */ + public function testIncrement() { + Cache::delete('test_increment', 'redis'); + $result = Cache::increment('test_increment', 1, 'redis'); + $this->assertEquals(1, $result); + + $result = Cache::read('test_increment', 'redis'); + $this->assertEquals(1, $result); + + $result = Cache::increment('test_increment', 2, 'redis'); + $this->assertEquals(3, $result); + + $result = Cache::read('test_increment', 'redis'); + $this->assertEquals(3, $result); + } + +/** + * test clearing redis. + * + * @return void + */ + public function testClear() { + Cache::config('redis2', array( + 'engine' => 'Redis', + 'prefix' => 'cake2_', + 'duration' => 3600 + )); + + Cache::write('some_value', 'cache1', 'redis'); + $result = Cache::clear(true, 'redis'); + $this->assertTrue($result); + $this->assertEquals('cache1', Cache::read('some_value', 'redis')); + + Cache::write('some_value', 'cache2', 'redis2'); + $result = Cache::clear(false, 'redis'); + $this->assertTrue($result); + $this->assertFalse(Cache::read('some_value', 'redis')); + $this->assertEquals('cache2', Cache::read('some_value', 'redis2')); + + Cache::clear(false, 'redis2'); + } + +/** + * test that a 0 duration can successfully write. + * + * @return void + */ + public function testZeroDuration() { + Cache::config('redis', array('duration' => 0)); + $result = Cache::write('test_key', 'written!', 'redis'); + + $this->assertTrue($result); + $result = Cache::read('test_key', 'redis'); + $this->assertEquals('written!', $result); + } + +/** + * Tests that configuring groups for stored keys return the correct values when read/written + * Shows that altering the group value is equivalent to deleting all keys under the same + * group + * + * @return void + */ + public function testGroupReadWrite() { + Cache::config('redis_groups', array( + 'engine' => 'Redis', + 'duration' => 3600, + 'groups' => array('group_a', 'group_b'), + 'prefix' => 'test_' + )); + Cache::config('redis_helper', array( + 'engine' => 'Redis', + 'duration' => 3600, + 'prefix' => 'test_' + )); + $this->assertTrue(Cache::write('test_groups', 'value', 'redis_groups')); + $this->assertEquals('value', Cache::read('test_groups', 'redis_groups')); + + Cache::increment('group_a', 1, 'redis_helper'); + $this->assertFalse(Cache::read('test_groups', 'redis_groups')); + $this->assertTrue(Cache::write('test_groups', 'value2', 'redis_groups')); + $this->assertEquals('value2', Cache::read('test_groups', 'redis_groups')); + + Cache::increment('group_b', 1, 'redis_helper'); + $this->assertFalse(Cache::read('test_groups', 'redis_groups')); + $this->assertTrue(Cache::write('test_groups', 'value3', 'redis_groups')); + $this->assertEquals('value3', Cache::read('test_groups', 'redis_groups')); + } + +/** + * Tests that deleteing from a groups-enabled config is possible + * + * @return void + */ + public function testGroupDelete() { + Cache::config('redis_groups', array( + 'engine' => 'Redis', + 'duration' => 3600, + 'groups' => array('group_a', 'group_b') + )); + $this->assertTrue(Cache::write('test_groups', 'value', 'redis_groups')); + $this->assertEquals('value', Cache::read('test_groups', 'redis_groups')); + $this->assertTrue(Cache::delete('test_groups', 'redis_groups')); + + $this->assertFalse(Cache::read('test_groups', 'redis_groups')); + } + +/** + * Test clearing a cache group + * + * @return void + **/ + public function testGroupClear() { + Cache::config('redis_groups', array( + 'engine' => 'Redis', + 'duration' => 3600, + 'groups' => array('group_a', 'group_b') + )); + + $this->assertTrue(Cache::write('test_groups', 'value', 'redis_groups')); + $this->assertTrue(Cache::clearGroup('group_a', 'redis_groups')); + $this->assertFalse(Cache::read('test_groups', 'redis_groups')); + + $this->assertTrue(Cache::write('test_groups', 'value2', 'redis_groups')); + $this->assertTrue(Cache::clearGroup('group_b', 'redis_groups')); + $this->assertFalse(Cache::read('test_groups', 'redis_groups')); + } + +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Cache/Engine/WincacheEngineTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Cache/Engine/WincacheEngineTest.php new file mode 100644 index 0000000..12eed53 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Cache/Engine/WincacheEngineTest.php @@ -0,0 +1,263 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Cache.Engine + * @since CakePHP(tm) v 1.2.0.5434 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ + +App::uses('Cache', 'Cache'); + +/** + * WincacheEngineTest class + * + * @package Cake.Test.Case.Cache.Engine + */ +class WincacheEngineTest extends CakeTestCase { + +/** + * setUp method + * + * @return void + */ + public function setUp() { + parent::setUp(); + $this->skipIf(!function_exists('wincache_ucache_set'), 'Wincache is not installed or configured properly.'); + $this->_cacheDisable = Configure::read('Cache.disable'); + Configure::write('Cache.disable', false); + Cache::config('wincache', array('engine' => 'Wincache', 'prefix' => 'cake_')); + } + +/** + * tearDown method + * + * @return void + */ + public function tearDown() { + parent::tearDown(); + Configure::write('Cache.disable', $this->_cacheDisable); + Cache::drop('wincache'); + Cache::drop('wincache_groups'); + Cache::config('default'); + } + +/** + * testReadAndWriteCache method + * + * @return void + */ + public function testReadAndWriteCache() { + Cache::set(array('duration' => 1), 'wincache'); + + $result = Cache::read('test', 'wincache'); + $expecting = ''; + $this->assertEquals($expecting, $result); + + $data = 'this is a test of the emergency broadcasting system'; + $result = Cache::write('test', $data, 'wincache'); + $this->assertTrue($result); + + $result = Cache::read('test', 'wincache'); + $expecting = $data; + $this->assertEquals($expecting, $result); + + Cache::delete('test', 'wincache'); + } + +/** + * testExpiry method + * + * @return void + */ + public function testExpiry() { + Cache::set(array('duration' => 1), 'wincache'); + + $result = Cache::read('test', 'wincache'); + $this->assertFalse($result); + + $data = 'this is a test of the emergency broadcasting system'; + $result = Cache::write('other_test', $data, 'wincache'); + $this->assertTrue($result); + + sleep(2); + $result = Cache::read('other_test', 'wincache'); + $this->assertFalse($result); + + Cache::set(array('duration' => 1), 'wincache'); + + $data = 'this is a test of the emergency broadcasting system'; + $result = Cache::write('other_test', $data, 'wincache'); + $this->assertTrue($result); + + sleep(2); + $result = Cache::read('other_test', 'wincache'); + $this->assertFalse($result); + + sleep(2); + $result = Cache::read('other_test', 'wincache'); + $this->assertFalse($result); + } + +/** + * testDeleteCache method + * + * @return void + */ + public function testDeleteCache() { + $data = 'this is a test of the emergency broadcasting system'; + $result = Cache::write('delete_test', $data, 'wincache'); + $this->assertTrue($result); + + $result = Cache::delete('delete_test', 'wincache'); + $this->assertTrue($result); + } + +/** + * testDecrement method + * + * @return void + */ + public function testDecrement() { + $this->skipIf( + !function_exists('wincache_ucache_dec'), + 'No wincache_ucache_dec() function, cannot test decrement().' + ); + + $result = Cache::write('test_decrement', 5, 'wincache'); + $this->assertTrue($result); + + $result = Cache::decrement('test_decrement', 1, 'wincache'); + $this->assertEquals(4, $result); + + $result = Cache::read('test_decrement', 'wincache'); + $this->assertEquals(4, $result); + + $result = Cache::decrement('test_decrement', 2, 'wincache'); + $this->assertEquals(2, $result); + + $result = Cache::read('test_decrement', 'wincache'); + $this->assertEquals(2, $result); + } + +/** + * testIncrement method + * + * @return void + */ + public function testIncrement() { + $this->skipIf( + !function_exists('wincache_ucache_inc'), + 'No wincache_inc() function, cannot test increment().' + ); + + $result = Cache::write('test_increment', 5, 'wincache'); + $this->assertTrue($result); + + $result = Cache::increment('test_increment', 1, 'wincache'); + $this->assertEquals(6, $result); + + $result = Cache::read('test_increment', 'wincache'); + $this->assertEquals(6, $result); + + $result = Cache::increment('test_increment', 2, 'wincache'); + $this->assertEquals(8, $result); + + $result = Cache::read('test_increment', 'wincache'); + $this->assertEquals(8, $result); + } + +/** + * test the clearing of cache keys + * + * @return void + */ + public function testClear() { + wincache_ucache_set('not_cake', 'safe'); + Cache::write('some_value', 'value', 'wincache'); + + $result = Cache::clear(false, 'wincache'); + $this->assertTrue($result); + $this->assertFalse(Cache::read('some_value', 'wincache')); + $this->assertEquals('safe', wincache_ucache_get('not_cake')); + } + +/** + * Tests that configuring groups for stored keys return the correct values when read/written + * Shows that altering the group value is equivalent to deleting all keys under the same + * group + * + * @return void + */ + public function testGroupsReadWrite() { + Cache::config('wincache_groups', array( + 'engine' => 'Wincache', + 'duration' => 0, + 'groups' => array('group_a', 'group_b'), + 'prefix' => 'test_' + )); + $this->assertTrue(Cache::write('test_groups', 'value', 'wincache_groups')); + $this->assertEquals('value', Cache::read('test_groups', 'wincache_groups')); + + wincache_ucache_inc('test_group_a'); + $this->assertFalse(Cache::read('test_groups', 'wincache_groups')); + $this->assertTrue(Cache::write('test_groups', 'value2', 'wincache_groups')); + $this->assertEquals('value2', Cache::read('test_groups', 'wincache_groups')); + + wincache_ucache_inc('test_group_b'); + $this->assertFalse(Cache::read('test_groups', 'wincache_groups')); + $this->assertTrue(Cache::write('test_groups', 'value3', 'wincache_groups')); + $this->assertEquals('value3', Cache::read('test_groups', 'wincache_groups')); + } + +/** + * Tests that deleteing from a groups-enabled config is possible + * + * @return void + */ + public function testGroupDelete() { + Cache::config('wincache_groups', array( + 'engine' => 'Wincache', + 'duration' => 0, + 'groups' => array('group_a', 'group_b'), + 'prefix' => 'test_' + )); + $this->assertTrue(Cache::write('test_groups', 'value', 'wincache_groups')); + $this->assertEquals('value', Cache::read('test_groups', 'wincache_groups')); + $this->assertTrue(Cache::delete('test_groups', 'wincache_groups')); + + $this->assertFalse(Cache::read('test_groups', 'wincache_groups')); + } + +/** + * Test clearing a cache group + * + * @return void + **/ + public function testGroupClear() { + Cache::config('wincache_groups', array( + 'engine' => 'Wincache', + 'duration' => 0, + 'groups' => array('group_a', 'group_b'), + 'prefix' => 'test_' + )); + + $this->assertTrue(Cache::write('test_groups', 'value', 'wincache_groups')); + $this->assertTrue(Cache::clearGroup('group_a', 'wincache_groups')); + $this->assertFalse(Cache::read('test_groups', 'wincache_groups')); + + $this->assertTrue(Cache::write('test_groups', 'value2', 'wincache_groups')); + $this->assertTrue(Cache::clearGroup('group_b', 'wincache_groups')); + $this->assertFalse(Cache::read('test_groups', 'wincache_groups')); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Cache/Engine/XcacheEngineTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Cache/Engine/XcacheEngineTest.php new file mode 100644 index 0000000..985977e --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Cache/Engine/XcacheEngineTest.php @@ -0,0 +1,272 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Cache.Engine + * @since CakePHP(tm) v 1.2.0.5434 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ + +App::uses('Cache', 'Cache'); + +/** + * XcacheEngineTest class + * + * @package Cake.Test.Case.Cache.Engine + */ +class XcacheEngineTest extends CakeTestCase { + +/** + * setUp method + * + * @return void + */ + public function setUp() { + parent::setUp(); + if (!function_exists('xcache_set')) { + $this->markTestSkipped('Xcache is not installed or configured properly'); + } + $this->_cacheDisable = Configure::read('Cache.disable'); + Configure::write('Cache.disable', false); + Cache::config('xcache', array('engine' => 'Xcache', 'prefix' => 'cake_')); + } + +/** + * tearDown method + * + * @return void + */ + public function tearDown() { + parent::tearDown(); + Configure::write('Cache.disable', $this->_cacheDisable); + Cache::drop('xcache'); + Cache::drop('xcache_groups'); + Cache::config('default'); + } + +/** + * testSettings method + * + * @return void + */ + public function testSettings() { + $settings = Cache::settings(); + $expecting = array( + 'prefix' => 'cake_', + 'duration' => 3600, + 'probability' => 100, + 'engine' => 'Xcache', + ); + $this->assertTrue(isset($settings['PHP_AUTH_USER'])); + $this->assertTrue(isset($settings['PHP_AUTH_PW'])); + + unset($settings['PHP_AUTH_USER'], $settings['PHP_AUTH_PW']); + $this->assertEquals($settings, $expecting); + } + +/** + * testReadAndWriteCache method + * + * @return void + */ + public function testReadAndWriteCache() { + Cache::set(array('duration' => 1)); + + $result = Cache::read('test'); + $expecting = ''; + $this->assertEquals($expecting, $result); + + $data = 'this is a test of the emergency broadcasting system'; + $result = Cache::write('test', $data); + $this->assertTrue($result); + + $result = Cache::read('test'); + $expecting = $data; + $this->assertEquals($expecting, $result); + + Cache::delete('test'); + } + +/** + * testExpiry method + * + * @return void + */ + public function testExpiry() { + Cache::set(array('duration' => 1)); + $result = Cache::read('test'); + $this->assertFalse($result); + + $data = 'this is a test of the emergency broadcasting system'; + $result = Cache::write('other_test', $data); + $this->assertTrue($result); + + sleep(2); + $result = Cache::read('other_test'); + $this->assertFalse($result); + + Cache::set(array('duration' => "+1 second")); + + $data = 'this is a test of the emergency broadcasting system'; + $result = Cache::write('other_test', $data); + $this->assertTrue($result); + + sleep(2); + $result = Cache::read('other_test'); + $this->assertFalse($result); + } + +/** + * testDeleteCache method + * + * @return void + */ + public function testDeleteCache() { + $data = 'this is a test of the emergency broadcasting system'; + $result = Cache::write('delete_test', $data); + $this->assertTrue($result); + + $result = Cache::delete('delete_test'); + $this->assertTrue($result); + } + +/** + * testClearCache method + * + * @return void + */ + public function testClearCache() { + $data = 'this is a test of the emergency broadcasting system'; + $result = Cache::write('clear_test_1', $data); + $this->assertTrue($result); + + $result = Cache::write('clear_test_2', $data); + $this->assertTrue($result); + + $result = Cache::clear(); + $this->assertTrue($result); + } + +/** + * testDecrement method + * + * @return void + */ + public function testDecrement() { + $result = Cache::write('test_decrement', 5); + $this->assertTrue($result); + + $result = Cache::decrement('test_decrement'); + $this->assertEquals(4, $result); + + $result = Cache::read('test_decrement'); + $this->assertEquals(4, $result); + + $result = Cache::decrement('test_decrement', 2); + $this->assertEquals(2, $result); + + $result = Cache::read('test_decrement'); + $this->assertEquals(2, $result); + } + +/** + * testIncrement method + * + * @return void + */ + public function testIncrement() { + $result = Cache::write('test_increment', 5); + $this->assertTrue($result); + + $result = Cache::increment('test_increment'); + $this->assertEquals(6, $result); + + $result = Cache::read('test_increment'); + $this->assertEquals(6, $result); + + $result = Cache::increment('test_increment', 2); + $this->assertEquals(8, $result); + + $result = Cache::read('test_increment'); + $this->assertEquals(8, $result); + } + +/** + * Tests that configuring groups for stored keys return the correct values when read/written + * Shows that altering the group value is equivalent to deleting all keys under the same + * group + * + * @return void + */ + public function testGroupsReadWrite() { + Cache::config('xcache_groups', array( + 'engine' => 'Xcache', + 'duration' => 0, + 'groups' => array('group_a', 'group_b'), + 'prefix' => 'test_' + )); + $this->assertTrue(Cache::write('test_groups', 'value', 'xcache_groups')); + $this->assertEquals('value', Cache::read('test_groups', 'xcache_groups')); + + xcache_inc('test_group_a', 1); + $this->assertFalse(Cache::read('test_groups', 'xcache_groups')); + $this->assertTrue(Cache::write('test_groups', 'value2', 'xcache_groups')); + $this->assertEquals('value2', Cache::read('test_groups', 'xcache_groups')); + + xcache_inc('test_group_b', 1); + $this->assertFalse(Cache::read('test_groups', 'xcache_groups')); + $this->assertTrue(Cache::write('test_groups', 'value3', 'xcache_groups')); + $this->assertEquals('value3', Cache::read('test_groups', 'xcache_groups')); + } + +/** + * Tests that deleteing from a groups-enabled config is possible + * + * @return void + */ + public function testGroupDelete() { + Cache::config('xcache_groups', array( + 'engine' => 'Xcache', + 'duration' => 0, + 'groups' => array('group_a', 'group_b'), + 'prefix' => 'test_' + )); + $this->assertTrue(Cache::write('test_groups', 'value', 'xcache_groups')); + $this->assertEquals('value', Cache::read('test_groups', 'xcache_groups')); + $this->assertTrue(Cache::delete('test_groups', 'xcache_groups')); + + $this->assertFalse(Cache::read('test_groups', 'xcache_groups')); + } + +/** + * Test clearing a cache group + * + * @return void + **/ + public function testGroupClear() { + Cache::config('xcache_groups', array( + 'engine' => 'Xcache', + 'duration' => 0, + 'groups' => array('group_a', 'group_b'), + 'prefix' => 'test_' + )); + + $this->assertTrue(Cache::write('test_groups', 'value', 'xcache_groups')); + $this->assertTrue(Cache::clearGroup('group_a', 'xcache_groups')); + $this->assertFalse(Cache::read('test_groups', 'xcache_groups')); + + $this->assertTrue(Cache::write('test_groups', 'value2', 'xcache_groups')); + $this->assertTrue(Cache::clearGroup('group_b', 'xcache_groups')); + $this->assertFalse(Cache::read('test_groups', 'xcache_groups')); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Configure/IniReaderTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Configure/IniReaderTest.php new file mode 100644 index 0000000..e4b4634 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Configure/IniReaderTest.php @@ -0,0 +1,188 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Configure + * @since CakePHP(tm) v 2.0 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ +App::uses('IniReader', 'Configure'); + +class IniReaderTest extends CakeTestCase { + +/** + * Test data to serialize and unserialize. + * + * @var array + */ + public $testData = array( + 'One' => array( + 'two' => 'value', + 'three' => array( + 'four' => 'value four' + ), + 'is_null' => null, + 'bool_false' => false, + 'bool_true' => true, + ), + 'Asset' => array( + 'timestamp' => 'force' + ), + ); + +/** + * setup + * + * @return void + */ + public function setUp() { + parent::setUp(); + $this->path = CAKE . 'Test' . DS . 'test_app' . DS . 'Config' . DS; + } + +/** + * test construct + * + * @return void + */ + public function testConstruct() { + $reader = new IniReader($this->path); + $config = $reader->read('acl.ini.php'); + + $this->assertTrue(isset($config['admin'])); + $this->assertTrue(isset($config['paul']['groups'])); + $this->assertEquals('ads', $config['admin']['deny']); + } + +/** + * no other sections should exist. + * + * @return void + */ + public function testReadingOnlyOneSection() { + $reader = new IniReader($this->path, 'admin'); + $config = $reader->read('acl.ini.php'); + + $this->assertTrue(isset($config['groups'])); + $this->assertEquals('administrators', $config['groups']); + } + +/** + * test without section + * + * @return void + */ + public function testReadingWithoutSection() { + $reader = new IniReader($this->path); + $config = $reader->read('no_section.ini'); + + $expected = array( + 'some_key' => 'some_value', + 'bool_key' => true + ); + $this->assertEquals($expected, $config); + } + +/** + * test that names with .'s get exploded into arrays. + * + * @return void + */ + public function testReadingValuesWithDots() { + $reader = new IniReader($this->path); + $config = $reader->read('nested.ini'); + + $this->assertTrue(isset($config['database']['db']['username'])); + $this->assertEquals('mark', $config['database']['db']['username']); + $this->assertEquals(3, $config['nesting']['one']['two']['three']); + $this->assertFalse(isset($config['database.db.username'])); + $this->assertFalse(isset($config['database']['db.username'])); + } + +/** + * test boolean reading + * + * @return void + */ + public function testBooleanReading() { + $reader = new IniReader($this->path); + $config = $reader->read('nested.ini'); + + $this->assertTrue($config['bools']['test_on']); + $this->assertFalse($config['bools']['test_off']); + + $this->assertTrue($config['bools']['test_yes']); + $this->assertFalse($config['bools']['test_no']); + + $this->assertTrue($config['bools']['test_true']); + $this->assertFalse($config['bools']['test_false']); + + $this->assertFalse($config['bools']['test_null']); + } + +/** + * test read file without extension + * + * @return void + */ + public function testReadingWithoutExtension() { + $reader = new IniReader($this->path); + $config = $reader->read('nested'); + $this->assertTrue($config['bools']['test_on']); + } + +/** + * test dump method. + * + * @return void + */ + public function testDump() { + $reader = new IniReader(TMP); + $result = $reader->dump('test.ini', $this->testData); + $this->assertTrue($result > 0); + + $expected = <<assertTextEquals($expected, $result); + } + +/** + * Test that dump() makes files read() can read. + * + * @return void + */ + public function testDumpRead() { + $reader = new IniReader(TMP); + $reader->dump('test.ini', $this->testData); + $result = $reader->read('test.ini'); + unlink(TMP . 'test.ini'); + + $expected = $this->testData; + $expected['One']['is_null'] = false; + + $this->assertEquals($expected, $result); + } + +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Configure/PhpReaderTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Configure/PhpReaderTest.php new file mode 100644 index 0000000..08982cb --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Configure/PhpReaderTest.php @@ -0,0 +1,170 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Configure + * @since CakePHP(tm) v 2.0 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ +App::uses('PhpReader', 'Configure'); + +class PhpReaderTest extends CakeTestCase { + +/** + * Test data to serialize and unserialize. + * + * @var array + */ + public $testData = array( + 'One' => array( + 'two' => 'value', + 'three' => array( + 'four' => 'value four' + ), + 'is_null' => null, + 'bool_false' => false, + 'bool_true' => true, + ), + 'Asset' => array( + 'timestamp' => 'force' + ), + ); + +/** + * setup + * + * @return void + */ + public function setUp() { + parent::setUp(); + $this->path = CAKE . 'Test' . DS . 'test_app' . DS . 'Config' . DS; + } + +/** + * test reading files + * + * @return void + */ + public function testRead() { + $reader = new PhpReader($this->path); + $values = $reader->read('var_test'); + $this->assertEquals('value', $values['Read']); + $this->assertEquals('buried', $values['Deep']['Deeper']['Deepest']); + + $values = $reader->read('var_test.php'); + $this->assertEquals('value', $values['Read']); + } + +/** + * Test an exception is thrown by reading files that don't exist. + * + * @expectedException ConfigureException + * @return void + */ + public function testReadWithNonExistantFile() { + $reader = new PhpReader($this->path); + $reader->read('fake_values'); + } + +/** + * test reading an empty file. + * + * @expectedException RuntimeException + * @return void + */ + public function testReadEmptyFile() { + $reader = new PhpReader($this->path); + $reader->read('empty'); + } + +/** + * test reading keys with ../ doesn't work + * + * @expectedException ConfigureException + * @return void + */ + public function testReadWithDots() { + $reader = new PhpReader($this->path); + $reader->read('../empty'); + } + +/** + * test reading from plugins + * + * @return void + */ + public function testReadPluginValue() { + App::build(array( + 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS) + ), App::RESET); + CakePlugin::load('TestPlugin'); + $reader = new PhpReader($this->path); + $result = $reader->read('TestPlugin.load'); + $this->assertTrue(isset($result['plugin_load'])); + + $result = $reader->read('TestPlugin.load.php'); + $this->assertTrue(isset($result['plugin_load'])); + CakePlugin::unload(); + } + +/** + * Test dumping data to PHP format. + * + * @return void + */ + public function testDump() { + $reader = new PhpReader(TMP); + $result = $reader->dump('test.php', $this->testData); + $this->assertTrue($result > 0); + $expected = << + array ( + 'two' => 'value', + 'three' => + array ( + 'four' => 'value four', + ), + 'is_null' => NULL, + 'bool_false' => false, + 'bool_true' => true, + ), + 'Asset' => + array ( + 'timestamp' => 'force', + ), +); +PHP; + $file = TMP . 'test.php'; + $contents = file_get_contents($file); + + unlink($file); + $this->assertTextEquals($expected, $contents); + } + +/** + * Test that dump() makes files read() can read. + * + * @return void + */ + public function testDumpRead() { + $reader = new PhpReader(TMP); + $reader->dump('test.php', $this->testData); + $result = $reader->read('test.php'); + unlink(TMP . 'test.php'); + + $this->assertEquals($this->testData, $result); + } + +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/AllConsoleLibsTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/AllConsoleLibsTest.php new file mode 100644 index 0000000..5a6846b --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/AllConsoleLibsTest.php @@ -0,0 +1,48 @@ +isFile() || strpos($file, 'All') === 0) { + continue; + } + $fileName = $file->getRealPath(); + if (substr($fileName, -4) === '.php') { + $suite->addTestFile($file->getRealPath()); + } + } + return $suite; + } +} \ No newline at end of file diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/AllConsoleTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/AllConsoleTest.php new file mode 100644 index 0000000..e284479 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/AllConsoleTest.php @@ -0,0 +1,44 @@ +addTestFile($path . 'AllConsoleLibsTest.php'); + $suite->addTestFile($path . 'AllTasksTest.php'); + $suite->addTestFile($path . 'AllShellsTest.php'); + return $suite; + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/AllShellsTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/AllShellsTest.php new file mode 100644 index 0000000..8842d61 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/AllShellsTest.php @@ -0,0 +1,42 @@ +addTestDirectory($path); + return $suite; + } +} \ No newline at end of file diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/AllTasksTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/AllTasksTest.php new file mode 100644 index 0000000..dcdce73 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/AllTasksTest.php @@ -0,0 +1,42 @@ +addTestDirectory($path); + return $suite; + } +} + diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/AclShellTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/AclShellTest.php new file mode 100644 index 0000000..7dfbbc0 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/AclShellTest.php @@ -0,0 +1,311 @@ +getMock('ConsoleOutput', array(), array(), '', false); + $in = $this->getMock('ConsoleInput', array(), array(), '', false); + + $this->Task = $this->getMock( + 'AclShell', + array('in', 'out', 'hr', 'createFile', 'error', 'err', 'clear', 'dispatchShell'), + array($out, $out, $in) + ); + $collection = new ComponentCollection(); + $this->Task->Acl = new AclComponent($collection); + $this->Task->params['datasource'] = 'test'; + } + +/** + * test that model.foreign_key output works when looking at acl rows + * + * @return void + */ + public function testViewWithModelForeignKeyOutput() { + $this->Task->command = 'view'; + $this->Task->startup(); + $data = array( + 'parent_id' => null, + 'model' => 'MyModel', + 'foreign_key' => 2, + ); + $this->Task->Acl->Aro->create($data); + $this->Task->Acl->Aro->save(); + $this->Task->args[0] = 'aro'; + + $this->Task->expects($this->at(0))->method('out')->with('Aro tree:'); + $this->Task->expects($this->at(2))->method('out') + ->with($this->stringContains('[1] ROOT')); + + $this->Task->expects($this->at(4))->method('out') + ->with($this->stringContains('[3] Gandalf')); + + $this->Task->expects($this->at(6))->method('out') + ->with($this->stringContains('[5] MyModel.2')); + + $this->Task->view(); + } + +/** + * test view with an argument + * + * @return void + */ + public function testViewWithArgument() { + $this->Task->args = array('aro', 'admins'); + + $this->Task->expects($this->at(0))->method('out')->with('Aro tree:'); + $this->Task->expects($this->at(2))->method('out')->with(' [2] admins'); + $this->Task->expects($this->at(3))->method('out')->with(' [3] Gandalf'); + $this->Task->expects($this->at(4))->method('out')->with(' [4] Elrond'); + + $this->Task->view(); + } + +/** + * test the method that splits model.foreign key. and that it returns an array. + * + * @return void + */ + public function testParsingModelAndForeignKey() { + $result = $this->Task->parseIdentifier('Model.foreignKey'); + $expected = array('model' => 'Model', 'foreign_key' => 'foreignKey'); + + $result = $this->Task->parseIdentifier('mySuperUser'); + $this->assertEquals('mySuperUser', $result); + + $result = $this->Task->parseIdentifier('111234'); + $this->assertEquals('111234', $result); + } + +/** + * test creating aro/aco nodes + * + * @return void + */ + public function testCreate() { + $this->Task->args = array('aro', 'root', 'User.1'); + $this->Task->expects($this->at(0))->method('out')->with("New Aro 'User.1' created.", 2); + $this->Task->expects($this->at(1))->method('out')->with("New Aro 'User.3' created.", 2); + $this->Task->expects($this->at(2))->method('out')->with("New Aro 'somealias' created.", 2); + + $this->Task->create(); + + $Aro = ClassRegistry::init('Aro'); + $Aro->cacheQueries = false; + $result = $Aro->read(); + $this->assertEquals('User', $result['Aro']['model']); + $this->assertEquals(1, $result['Aro']['foreign_key']); + $this->assertEquals(null, $result['Aro']['parent_id']); + $id = $result['Aro']['id']; + + $this->Task->args = array('aro', 'User.1', 'User.3'); + $this->Task->create(); + + $Aro = ClassRegistry::init('Aro'); + $result = $Aro->read(); + $this->assertEquals('User', $result['Aro']['model']); + $this->assertEquals(3, $result['Aro']['foreign_key']); + $this->assertEquals($id, $result['Aro']['parent_id']); + + $this->Task->args = array('aro', 'root', 'somealias'); + $this->Task->create(); + + $Aro = ClassRegistry::init('Aro'); + $result = $Aro->read(); + $this->assertEquals('somealias', $result['Aro']['alias']); + $this->assertEquals(null, $result['Aro']['model']); + $this->assertEquals(null, $result['Aro']['foreign_key']); + $this->assertEquals(null, $result['Aro']['parent_id']); + } + +/** + * test the delete method with different node types. + * + * @return void + */ + public function testDelete() { + $this->Task->args = array('aro', 'AuthUser.1'); + $this->Task->expects($this->at(0))->method('out') + ->with("Aro deleted.", 2); + $this->Task->delete(); + + $Aro = ClassRegistry::init('Aro'); + $result = $Aro->findById(3); + $this->assertFalse($result); + } + +/** + * test setParent method. + * + * @return void + */ + public function testSetParent() { + $this->Task->args = array('aro', 'AuthUser.2', 'root'); + $this->Task->setParent(); + + $Aro = ClassRegistry::init('Aro'); + $result = $Aro->read(null, 4); + $this->assertEquals(null, $result['Aro']['parent_id']); + } + +/** + * test grant + * + * @return void + */ + public function testGrant() { + $this->Task->args = array('AuthUser.2', 'ROOT/Controller1', 'create'); + $this->Task->expects($this->at(0))->method('out') + ->with($this->matchesRegularExpression('/granted/'), true); + $this->Task->grant(); + $node = $this->Task->Acl->Aro->node(array('model' => 'AuthUser', 'foreign_key' => 2)); + $node = $this->Task->Acl->Aro->read(null, $node[0]['Aro']['id']); + + $this->assertFalse(empty($node['Aco'][0])); + $this->assertEquals(1, $node['Aco'][0]['Permission']['_create']); + } + +/** + * test deny + * + * @return void + */ + public function testDeny() { + $this->Task->args = array('AuthUser.2', 'ROOT/Controller1', 'create'); + $this->Task->expects($this->at(0))->method('out') + ->with($this->stringContains('Permission denied'), true); + + $this->Task->deny(); + + $node = $this->Task->Acl->Aro->node(array('model' => 'AuthUser', 'foreign_key' => 2)); + $node = $this->Task->Acl->Aro->read(null, $node[0]['Aro']['id']); + $this->assertFalse(empty($node['Aco'][0])); + $this->assertEquals(-1, $node['Aco'][0]['Permission']['_create']); + } + +/** + * test checking allowed and denied perms + * + * @return void + */ + public function testCheck() { + $this->Task->expects($this->at(0))->method('out') + ->with($this->matchesRegularExpression('/not allowed/'), true); + $this->Task->expects($this->at(1))->method('out') + ->with($this->matchesRegularExpression('/granted/'), true); + $this->Task->expects($this->at(2))->method('out') + ->with($this->matchesRegularExpression('/is.*allowed/'), true); + $this->Task->expects($this->at(3))->method('out') + ->with($this->matchesRegularExpression('/not.*allowed/'), true); + + $this->Task->args = array('AuthUser.2', 'ROOT/Controller1', '*'); + $this->Task->check(); + + $this->Task->args = array('AuthUser.2', 'ROOT/Controller1', 'create'); + $this->Task->grant(); + + $this->Task->args = array('AuthUser.2', 'ROOT/Controller1', 'create'); + $this->Task->check(); + + $this->Task->args = array('AuthUser.2', 'ROOT/Controller1', '*'); + $this->Task->check(); + } + +/** + * test inherit and that it 0's the permission fields. + * + * @return void + */ + public function testInherit() { + $this->Task->expects($this->at(0))->method('out') + ->with($this->matchesRegularExpression('/Permission .*granted/'), true); + $this->Task->expects($this->at(1))->method('out') + ->with($this->matchesRegularExpression('/Permission .*inherited/'), true); + + $this->Task->args = array('AuthUser.2', 'ROOT/Controller1', 'create'); + $this->Task->grant(); + + $this->Task->args = array('AuthUser.2', 'ROOT/Controller1', 'all'); + $this->Task->inherit(); + + $node = $this->Task->Acl->Aro->node(array('model' => 'AuthUser', 'foreign_key' => 2)); + $node = $this->Task->Acl->Aro->read(null, $node[0]['Aro']['id']); + $this->assertFalse(empty($node['Aco'][0])); + $this->assertEquals(0, $node['Aco'][0]['Permission']['_create']); + } + +/** + * test getting the path for an aro/aco + * + * @return void + */ + public function testGetPath() { + $this->Task->args = array('aro', 'AuthUser.2'); + $node = $this->Task->Acl->Aro->node(array('model' => 'AuthUser', 'foreign_key' => 2)); + $first = $node[0]['Aro']['id']; + $second = $node[1]['Aro']['id']; + $last = $node[2]['Aro']['id']; + $this->Task->expects($this->at(2))->method('out')->with('[' . $last . '] ROOT'); + $this->Task->expects($this->at(3))->method('out')->with(' [' . $second . '] admins'); + $this->Task->expects($this->at(4))->method('out')->with(' [' . $first . '] Elrond'); + $this->Task->getPath(); + } + +/** + * test that initdb makes the correct call. + * + * @return void + */ + public function testInitDb() { + $this->Task->expects($this->once())->method('dispatchShell') + ->with('schema create DbAcl'); + + $this->Task->initdb(); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/ApiShellTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/ApiShellTest.php new file mode 100644 index 0000000..f5d2fbe --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/ApiShellTest.php @@ -0,0 +1,96 @@ +getMock('ConsoleOutput', array(), array(), '', false); + $in = $this->getMock('ConsoleInput', array(), array(), '', false); + + $this->Shell = $this->getMock( + 'ApiShell', + array('in', 'out', 'createFile', 'hr', '_stop'), + array( $out, $out, $in) + ); + } + +/** + * Test that method names are detected properly including those with no arguments. + * + * @return void + */ + public function testMethodNameDetection() { + $this->Shell->expects($this->any())->method('in')->will($this->returnValue('q')); + $this->Shell->expects($this->at(0))->method('out')->with('Controller'); + + $expected = array( + '1. afterFilter()', + '2. afterScaffoldSave($method)', + '3. afterScaffoldSaveError($method)', + '4. beforeFilter()', + '5. beforeRedirect($url, $status = NULL, $exit = true)', + '6. beforeRender()', + '7. beforeScaffold($method)', + '8. constructClasses()', + '9. disableCache()', + '10. flash($message, $url, $pause = 1, $layout = \'flash\')', + '11. getEventManager()', + '12. header($status)', + '13. httpCodes($code = NULL)', + '14. implementedEvents()', + '15. invokeAction($request)', + '16. loadModel($modelClass = NULL, $id = NULL)', + '17. paginate($object = NULL, $scope = array (), $whitelist = array ())', + '18. postConditions($data = array (), $op = NULL, $bool = \'AND\', $exclusive = false)', + '19. redirect($url, $status = NULL, $exit = true)', + '20. referer($default = NULL, $local = false)', + '21. render($view = NULL, $layout = NULL)', + '22. scaffoldError($method)', + '23. set($one, $two = NULL)', + '24. setAction($action)', + '25. setRequest($request)', + '26. shutdownProcess()', + '27. startupProcess()', + '28. validate()', + '29. validateErrors()' + ); + $this->Shell->expects($this->at(2))->method('out')->with($expected); + + $this->Shell->args = array('controller'); + $this->Shell->paths['controller'] = CAKE . 'Controller' . DS; + $this->Shell->main(); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/BakeShellTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/BakeShellTest.php new file mode 100644 index 0000000..8991674 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/BakeShellTest.php @@ -0,0 +1,124 @@ +getMock('ConsoleOutput', array(), array(), '', false); + $in = $this->getMock('ConsoleInput', array(), array(), '', false); + + $this->Shell = $this->getMock( + 'BakeShell', + array('in', 'out', 'hr', 'err', 'createFile', '_stop', '_checkUnitTest'), + array($out, $out, $in) + ); + } + +/** + * tearDown method + * + * @return void + */ + public function tearDown() { + parent::tearDown(); + unset($this->Dispatch, $this->Shell); + } + +/** + * test bake all + * + * @return void + */ + public function testAllWithModelName() { + App::uses('User', 'Model'); + $userExists = class_exists('User'); + $this->skipIf($userExists, 'User class exists, cannot test `bake all [param]`.'); + + $this->Shell->Model = $this->getMock('ModelTask', array(), array(&$this->Dispatcher)); + $this->Shell->Controller = $this->getMock('ControllerTask', array(), array(&$this->Dispatcher)); + $this->Shell->View = $this->getMock('ModelTask', array(), array(&$this->Dispatcher)); + $this->Shell->DbConfig = $this->getMock('DbConfigTask', array(), array(&$this->Dispatcher)); + + $this->Shell->DbConfig->expects($this->once()) + ->method('getConfig') + ->will($this->returnValue('test')); + + $this->Shell->Model->expects($this->never()) + ->method('getName'); + + $this->Shell->Model->expects($this->once()) + ->method('bake') + ->will($this->returnValue(true)); + + $this->Shell->Controller->expects($this->once()) + ->method('bake') + ->will($this->returnValue(true)); + + $this->Shell->View->expects($this->once()) + ->method('execute'); + + $this->Shell->expects($this->once())->method('_stop'); + $this->Shell->expects($this->at(0)) + ->method('out') + ->with('Bake All'); + + $this->Shell->expects($this->at(5)) + ->method('out') + ->with('Bake All complete'); + + $this->Shell->connection = ''; + $this->Shell->params = array(); + $this->Shell->args = array('User'); + $this->Shell->all(); + + $this->assertEquals('User', $this->Shell->View->args[0]); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/CommandListShellTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/CommandListShellTest.php new file mode 100644 index 0000000..22eed19 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/CommandListShellTest.php @@ -0,0 +1,118 @@ +output .= $message; + } + +} + +class CommandListShellTest extends CakeTestCase { + +/** + * setUp method + * + * @return void + */ + public function setUp() { + parent::setUp(); + App::build(array( + 'Plugin' => array( + CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS + ), + 'Console/Command' => array( + CAKE . 'Test' . DS . 'test_app' . DS . 'Console' . DS . 'Command' . DS + ) + ), App::RESET); + CakePlugin::load(array('TestPlugin', 'TestPluginTwo')); + + $out = new TestStringOutput(); + $in = $this->getMock('ConsoleInput', array(), array(), '', false); + + $this->Shell = $this->getMock( + 'CommandListShell', + array('in', '_stop', 'clear'), + array($out, $out, $in) + ); + } + +/** + * tearDown + * + * @return void + */ + public function tearDown() { + parent::tearDown(); + unset($this->Shell); + CakePlugin::unload(); + } + +/** + * test that main finds core shells. + * + * @return void + */ + public function testMain() { + $this->Shell->main(); + $output = $this->Shell->stdout->output; + + $expected = "/\[.*TestPlugin.*\] example/"; + $this->assertRegExp($expected, $output); + + $expected = "/\[.*TestPluginTwo.*\] example, welcome/"; + $this->assertRegExp($expected, $output); + + $expected = "/\[.*CORE.*\] acl, api, bake, command_list, console, i18n, schema, test, testsuite, upgrade/"; + $this->assertRegExp($expected, $output); + + $expected = "/\[.*app.*\] sample/"; + $this->assertRegExp($expected, $output); + } + +/** + * test xml output. + * + * @return void + */ + public function testMainXml() { + $this->Shell->params['xml'] = true; + $this->Shell->main(); + + $output = $this->Shell->stdout->output; + + $find = ''; + $this->assertContains($find, $output); + + $find = ''; + $this->assertContains($find, $output); + + $find = ''; + $this->assertContains($find, $output); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/SchemaShellTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/SchemaShellTest.php new file mode 100644 index 0000000..7d21753 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/SchemaShellTest.php @@ -0,0 +1,492 @@ + array('type' => 'integer', 'null' => false, 'default' => 0, 'key' => 'primary'), + 'post_id' => array('type' => 'integer', 'null' => false, 'default' => 0), + 'user_id' => array('type' => 'integer', 'null' => false), + 'title' => array('type' => 'string', 'null' => false, 'length' => 100), + 'comment' => array('type' => 'text', 'null' => false, 'default' => null), + 'published' => array('type' => 'string', 'null' => true, 'default' => 'N', 'length' => 1), + 'created' => array('type' => 'datetime', 'null' => true, 'default' => null), + 'updated' => array('type' => 'datetime', 'null' => true, 'default' => null), + 'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => true)), + ); + +/** + * posts property + * + * @var array + */ + public $articles = array( + 'id' => array('type' => 'integer', 'null' => false, 'default' => 0, 'key' => 'primary'), + 'user_id' => array('type' => 'integer', 'null' => true, 'default' => ''), + 'title' => array('type' => 'string', 'null' => false, 'default' => 'Title'), + 'body' => array('type' => 'text', 'null' => true, 'default' => null), + 'summary' => array('type' => 'text', 'null' => true), + 'published' => array('type' => 'string', 'null' => true, 'default' => 'Y', 'length' => 1), + 'created' => array('type' => 'datetime', 'null' => true, 'default' => null), + 'updated' => array('type' => 'datetime', 'null' => true, 'default' => null), + 'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => true)), + ); +} + +/** + * SchemaShellTest class + * + * @package Cake.Test.Case.Console.Command + */ +class SchemaShellTest extends CakeTestCase { + +/** + * Fixtures + * + * @var array + */ + public $fixtures = array('core.article', 'core.user', 'core.post', 'core.auth_user', 'core.author', + 'core.comment', 'core.test_plugin_comment' + ); + +/** + * setUp method + * + * @return void + */ + public function setUp() { + parent::setUp(); + + $out = $this->getMock('ConsoleOutput', array(), array(), '', false); + $in = $this->getMock('ConsoleInput', array(), array(), '', false); + $this->Shell = $this->getMock( + 'SchemaShell', + array('in', 'out', 'hr', 'createFile', 'error', 'err', '_stop'), + array($out, $out, $in) + ); + } + +/** + * tearDown method + * + * @return void + */ + public function tearDown() { + parent::tearDown(); + if (!empty($this->file) && $this->file instanceof File) { + $this->file->delete(); + unset($this->file); + } + } + +/** + * test startup method + * + * @return void + */ + public function testStartup() { + $this->Shell->startup(); + $this->assertTrue(isset($this->Shell->Schema)); + $this->assertTrue(is_a($this->Shell->Schema, 'CakeSchema')); + $this->assertEquals(Inflector::camelize(Inflector::slug(APP_DIR)), $this->Shell->Schema->name); + $this->assertEquals('schema.php', $this->Shell->Schema->file); + + $this->Shell->Schema = null; + $this->Shell->params = array( + 'name' => 'TestSchema' + ); + $this->Shell->startup(); + $this->assertEquals('TestSchema', $this->Shell->Schema->name); + $this->assertEquals('test_schema.php', $this->Shell->Schema->file); + $this->assertEquals('default', $this->Shell->Schema->connection); + $this->assertEquals(APP . 'Config' . DS . 'Schema', $this->Shell->Schema->path); + + $this->Shell->Schema = null; + $this->Shell->params = array( + 'file' => 'other_file.php', + 'connection' => 'test', + 'path' => '/test/path' + ); + $this->Shell->startup(); + $this->assertEquals(Inflector::camelize(Inflector::slug(APP_DIR)), $this->Shell->Schema->name); + $this->assertEquals('other_file.php', $this->Shell->Schema->file); + $this->assertEquals('test', $this->Shell->Schema->connection); + $this->assertEquals('/test/path', $this->Shell->Schema->path); + } + +/** + * Test View - and that it dumps the schema file to stdout + * + * @return void + */ + public function testView() { + $this->Shell->startup(); + $this->Shell->Schema->path = APP . 'Config' . DS . 'Schema'; + $this->Shell->params['file'] = 'i18n.php'; + $this->Shell->expects($this->once())->method('_stop'); + $this->Shell->expects($this->once())->method('out'); + $this->Shell->view(); + } + +/** + * test that view() can find plugin schema files. + * + * @return void + */ + public function testViewWithPlugins() { + App::build(array( + 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS) + )); + CakePlugin::load('TestPlugin'); + $this->Shell->args = array('TestPlugin.schema'); + $this->Shell->startup(); + $this->Shell->expects($this->exactly(2))->method('_stop'); + $this->Shell->expects($this->atLeastOnce())->method('out'); + $this->Shell->view(); + + $this->Shell->args = array(); + $this->Shell->params = array('plugin' => 'TestPlugin'); + $this->Shell->startup(); + $this->Shell->view(); + + App::build(); + CakePlugin::unload(); + } + +/** + * test dump() with sql file generation + * + * @return void + */ + public function testDumpWithFileWriting() { + $this->Shell->params = array( + 'name' => 'i18n', + 'connection' => 'test', + 'write' => TMP . 'tests' . DS . 'i18n.sql' + ); + $this->Shell->expects($this->once())->method('_stop'); + $this->Shell->startup(); + $this->Shell->dump(); + + $this->file = new File(TMP . 'tests' . DS . 'i18n.sql'); + $contents = $this->file->read(); + $this->assertRegExp('/DROP TABLE/', $contents); + $this->assertRegExp('/CREATE TABLE.*?i18n/', $contents); + $this->assertRegExp('/id/', $contents); + $this->assertRegExp('/model/', $contents); + $this->assertRegExp('/field/', $contents); + $this->assertRegExp('/locale/', $contents); + $this->assertRegExp('/foreign_key/', $contents); + $this->assertRegExp('/content/', $contents); + } + +/** + * test that dump() can find and work with plugin schema files. + * + * @return void + */ + public function testDumpFileWritingWithPlugins() { + App::build(array( + 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS) + )); + CakePlugin::load('TestPlugin'); + $this->Shell->args = array('TestPlugin.TestPluginApp'); + $this->Shell->params = array( + 'connection' => 'test', + 'write' => TMP . 'tests' . DS . 'dump_test.sql' + ); + $this->Shell->startup(); + $this->Shell->expects($this->once())->method('_stop'); + $this->Shell->dump(); + + $this->file = new File(TMP . 'tests' . DS . 'dump_test.sql'); + $contents = $this->file->read(); + + $this->assertRegExp('/CREATE TABLE.*?test_plugin_acos/', $contents); + $this->assertRegExp('/id/', $contents); + $this->assertRegExp('/model/', $contents); + + $this->file->delete(); + App::build(); + CakePlugin::unload(); + } + +/** + * test generate with snapshot generation + * + * @return void + */ + public function testGenerateSnapshot() { + $this->Shell->path = TMP; + $this->Shell->params['file'] = 'schema.php'; + $this->Shell->params['force'] = false; + $this->Shell->args = array('snapshot'); + $this->Shell->Schema = $this->getMock('CakeSchema'); + $this->Shell->Schema->expects($this->at(0))->method('read')->will($this->returnValue(array('schema data'))); + $this->Shell->Schema->expects($this->at(0))->method('write')->will($this->returnValue(true)); + + $this->Shell->Schema->expects($this->at(1))->method('read'); + $this->Shell->Schema->expects($this->at(1))->method('write')->with(array('schema data', 'file' => 'schema_0.php')); + + $this->Shell->generate(); + } + +/** + * test generate without a snapshot. + * + * @return void + */ + public function testGenerateNoOverwrite() { + touch(TMP . 'schema.php'); + $this->Shell->params['file'] = 'schema.php'; + $this->Shell->params['force'] = false; + $this->Shell->args = array(); + + $this->Shell->expects($this->once())->method('in')->will($this->returnValue('q')); + $this->Shell->Schema = $this->getMock('CakeSchema'); + $this->Shell->Schema->path = TMP; + $this->Shell->Schema->expects($this->never())->method('read'); + + $result = $this->Shell->generate(); + unlink(TMP . 'schema.php'); + } + +/** + * test generate with overwriting of the schema files. + * + * @return void + */ + public function testGenerateOverwrite() { + touch(TMP . 'schema.php'); + $this->Shell->params['file'] = 'schema.php'; + $this->Shell->params['force'] = false; + $this->Shell->args = array(); + + $this->Shell->expects($this->once())->method('in')->will($this->returnValue('o')); + + $this->Shell->expects($this->at(2))->method('out') + ->with(new PHPUnit_Framework_Constraint_PCREMatch('/Schema file:\s[a-z\.]+\sgenerated/')); + + $this->Shell->Schema = $this->getMock('CakeSchema'); + $this->Shell->Schema->path = TMP; + $this->Shell->Schema->expects($this->once())->method('read')->will($this->returnValue(array('schema data'))); + $this->Shell->Schema->expects($this->once())->method('write')->will($this->returnValue(true)); + + $this->Shell->Schema->expects($this->once())->method('read'); + $this->Shell->Schema->expects($this->once())->method('write') + ->with(array('schema data', 'file' => 'schema.php')); + + $this->Shell->generate(); + unlink(TMP . 'schema.php'); + } + +/** + * test that generate() can read plugin dirs and generate schema files for the models + * in a plugin. + * + * @return void + */ + public function testGenerateWithPlugins() { + App::build(array( + 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS) + ), App::RESET); + CakePlugin::load('TestPlugin'); + + $this->db->cacheSources = false; + $this->Shell->params = array( + 'plugin' => 'TestPlugin', + 'connection' => 'test', + 'force' => false + ); + $this->Shell->startup(); + $this->Shell->Schema->path = TMP . 'tests' . DS; + + $this->Shell->generate(); + $this->file = new File(TMP . 'tests' . DS . 'schema.php'); + $contents = $this->file->read(); + + $this->assertRegExp('/class TestPluginSchema/', $contents); + $this->assertRegExp('/public \$posts/', $contents); + $this->assertRegExp('/public \$auth_users/', $contents); + $this->assertRegExp('/public \$authors/', $contents); + $this->assertRegExp('/public \$test_plugin_comments/', $contents); + $this->assertNotRegExp('/public \$users/', $contents); + $this->assertNotRegExp('/public \$articles/', $contents); + CakePlugin::unload(); + } + +/** + * Test schema run create with no table args. + * + * @return void + */ + public function testCreateNoArgs() { + $this->Shell->params = array( + 'connection' => 'test' + ); + $this->Shell->args = array('i18n'); + $this->Shell->startup(); + $this->Shell->expects($this->any())->method('in')->will($this->returnValue('y')); + $this->Shell->create(); + + $db = ConnectionManager::getDataSource('test'); + + $db->cacheSources = false; + $sources = $db->listSources(); + $this->assertTrue(in_array($db->config['prefix'] . 'i18n', $sources)); + + $schema = new i18nSchema(); + $db->execute($db->dropSchema($schema)); + } + +/** + * Test schema run create with no table args. + * + * @return void + */ + public function testCreateWithTableArgs() { + $db = ConnectionManager::getDataSource('test'); + $sources = $db->listSources(); + if (in_array('acos', $sources)) { + $this->markTestSkipped('acos table already exists, cannot try to create it again.'); + } + $this->Shell->params = array( + 'connection' => 'test', + 'name' => 'DbAcl', + 'path' => APP . 'Config' . DS . 'Schema' + ); + $this->Shell->args = array('DbAcl', 'acos'); + $this->Shell->startup(); + $this->Shell->expects($this->any())->method('in')->will($this->returnValue('y')); + $this->Shell->create(); + + $db = ConnectionManager::getDataSource('test'); + $db->cacheSources = false; + $sources = $db->listSources(); + $this->assertTrue(in_array($db->config['prefix'] . 'acos', $sources), 'acos should be present.'); + $this->assertFalse(in_array($db->config['prefix'] . 'aros', $sources), 'aros should not be found.'); + $this->assertFalse(in_array('aros_acos', $sources), 'aros_acos should not be found.'); + + $schema = new DbAclSchema(); + $db->execute($db->dropSchema($schema, 'acos')); + } + +/** + * test run update with a table arg. + * + * @return void + */ + public function testUpdateWithTable() { + $this->Shell = $this->getMock( + 'SchemaShell', + array('in', 'out', 'hr', 'createFile', 'error', 'err', '_stop', '_run'), + array(&$this->Dispatcher) + ); + + $this->Shell->params = array( + 'connection' => 'test', + 'force' => true + ); + $this->Shell->args = array('SchemaShellTest', 'articles'); + $this->Shell->startup(); + $this->Shell->expects($this->any())->method('in')->will($this->returnValue('y')); + $this->Shell->expects($this->once())->method('_run') + ->with($this->arrayHasKey('articles'), 'update', $this->isInstanceOf('CakeSchema')); + + $this->Shell->update(); + } + +/** + * test that the plugin param creates the correct path in the schema object. + * + * @return void + */ + public function testPluginParam() { + App::build(array( + 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS) + )); + CakePlugin::load('TestPlugin'); + $this->Shell->params = array( + 'plugin' => 'TestPlugin', + 'connection' => 'test' + ); + $this->Shell->startup(); + $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS . 'TestPlugin' . DS . 'Config' . DS . 'Schema'; + $this->assertEquals($expected, $this->Shell->Schema->path); + CakePlugin::unload(); + } + +/** + * test that using Plugin.name with write. + * + * @return void + */ + public function testPluginDotSyntaxWithCreate() { + App::build(array( + 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS) + )); + CakePlugin::load('TestPlugin'); + $this->Shell->params = array( + 'connection' => 'test' + ); + $this->Shell->args = array('TestPlugin.TestPluginApp'); + $this->Shell->startup(); + $this->Shell->expects($this->any())->method('in')->will($this->returnValue('y')); + $this->Shell->create(); + + $db = ConnectionManager::getDataSource('test'); + $sources = $db->listSources(); + $this->assertTrue(in_array($db->config['prefix'] . 'test_plugin_acos', $sources)); + + $schema = new TestPluginAppSchema(); + $db->execute($db->dropSchema($schema, 'test_plugin_acos')); + CakePlugin::unload(); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/Task/ControllerTaskTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/Task/ControllerTaskTest.php new file mode 100644 index 0000000..b17c862 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/Task/ControllerTaskTest.php @@ -0,0 +1,652 @@ +getMock('ConsoleOutput', array(), array(), '', false); + $in = $this->getMock('ConsoleInput', array(), array(), '', false); + $this->Task = $this->getMock('ControllerTask', + array('in', 'out', 'err', 'hr', 'createFile', '_stop', '_checkUnitTest'), + array($out, $out, $in) + ); + $this->Task->name = 'Controller'; + $this->Task->Template = new TemplateTask($out, $out, $in); + $this->Task->Template->params['theme'] = 'default'; + + $this->Task->Model = $this->getMock('ModelTask', + array('in', 'out', 'err', 'createFile', '_stop', '_checkUnitTest'), + array($out, $out, $in) + ); + $this->Task->Project = $this->getMock('ProjectTask', + array('in', 'out', 'err', 'createFile', '_stop', '_checkUnitTest', 'getPrefix'), + array($out, $out, $in) + ); + $this->Task->Test = $this->getMock('TestTask', array(), array($out, $out, $in)); + } + +/** + * tearDown method + * + * @return void + */ + public function tearDown() { + unset($this->Task); + ClassRegistry::flush(); + App::build(); + parent::tearDown(); + } + +/** + * test ListAll + * + * @return void + */ + public function testListAll() { + $count = count($this->Task->listAll('test')); + if ($count != count($this->fixtures)) { + $this->markTestSkipped('Additional tables detected.'); + } + + $this->Task->connection = 'test'; + $this->Task->interactive = true; + $this->Task->expects($this->at(1))->method('out')->with('1. BakeArticles'); + $this->Task->expects($this->at(2))->method('out')->with('2. BakeArticlesBakeTags'); + $this->Task->expects($this->at(3))->method('out')->with('3. BakeComments'); + $this->Task->expects($this->at(4))->method('out')->with('4. BakeTags'); + + $expected = array('BakeArticles', 'BakeArticlesBakeTags', 'BakeComments', 'BakeTags'); + $result = $this->Task->listAll('test'); + $this->assertEquals($expected, $result); + + $this->Task->interactive = false; + $result = $this->Task->listAll(); + + $expected = array('bake_articles', 'bake_articles_bake_tags', 'bake_comments', 'bake_tags'); + $this->assertEquals($expected, $result); + } + +/** + * Test that getName interacts with the user and returns the controller name. + * + * @return void + */ + public function testGetNameValidIndex() { + $count = count($this->Task->listAll('test')); + if ($count != count($this->fixtures)) { + $this->markTestSkipped('Additional tables detected.'); + } + $this->Task->interactive = true; + $this->Task->expects($this->any())->method('in')->will( + $this->onConsecutiveCalls(3, 1) + ); + + $result = $this->Task->getName('test'); + $expected = 'BakeComments'; + $this->assertEquals($expected, $result); + + $result = $this->Task->getName('test'); + $expected = 'BakeArticles'; + $this->assertEquals($expected, $result); + } + +/** + * test getting invalid indexes. + * + * @return void + */ + public function testGetNameInvalidIndex() { + $this->Task->interactive = true; + $this->Task->expects($this->any())->method('in') + ->will($this->onConsecutiveCalls(50, 'q')); + + $this->Task->expects($this->once())->method('err'); + $this->Task->expects($this->once())->method('_stop'); + + $this->Task->getName('test'); + } + +/** + * test helper interactions + * + * @return void + */ + public function testDoHelpersNo() { + $this->Task->expects($this->any())->method('in')->will($this->returnValue('n')); + $result = $this->Task->doHelpers(); + $this->assertEquals(array(), $result); + } + +/** + * test getting helper values + * + * @return void + */ + public function testDoHelpersTrailingSpace() { + $this->Task->expects($this->at(0))->method('in')->will($this->returnValue('y')); + $this->Task->expects($this->at(1))->method('in')->will($this->returnValue(' Javascript, Ajax, CustomOne ')); + $result = $this->Task->doHelpers(); + $expected = array('Javascript', 'Ajax', 'CustomOne'); + $this->assertEquals($expected, $result); + } + +/** + * test doHelpers with extra commas + * + * @return void + */ + public function testDoHelpersTrailingCommas() { + $this->Task->expects($this->at(0))->method('in')->will($this->returnValue('y')); + $this->Task->expects($this->at(1))->method('in')->will($this->returnValue(' Javascript, Ajax, CustomOne, , ')); + $result = $this->Task->doHelpers(); + $expected = array('Javascript', 'Ajax', 'CustomOne'); + $this->assertEquals($expected, $result); + } + +/** + * test component interactions + * + * @return void + */ + public function testDoComponentsNo() { + $this->Task->expects($this->any())->method('in')->will($this->returnValue('n')); + $result = $this->Task->doComponents(); + $this->assertEquals(array(), $result); + } + +/** + * test components with spaces + * + * @return void + */ + public function testDoComponentsTrailingSpaces() { + $this->Task->expects($this->at(0))->method('in')->will($this->returnValue('y')); + $this->Task->expects($this->at(1))->method('in')->will($this->returnValue(' RequestHandler, Security ')); + + $result = $this->Task->doComponents(); + $expected = array('RequestHandler', 'Security'); + $this->assertEquals($expected, $result); + } + +/** + * test components with commas + * + * @return void + */ + public function testDoComponentsTrailingCommas() { + $this->Task->expects($this->at(0))->method('in')->will($this->returnValue('y')); + $this->Task->expects($this->at(1))->method('in')->will($this->returnValue(' RequestHandler, Security, , ')); + + $result = $this->Task->doComponents(); + $expected = array('RequestHandler', 'Security'); + $this->assertEquals($expected, $result); + } + +/** + * test Confirming controller user interaction + * + * @return void + */ + public function testConfirmController() { + $controller = 'Posts'; + $scaffold = false; + $helpers = array('Ajax', 'Time'); + $components = array('Acl', 'Auth'); + + $this->Task->expects($this->at(4))->method('out')->with("Controller Name:\n\t$controller"); + $this->Task->expects($this->at(5))->method('out')->with("Helpers:\n\tAjax, Time"); + $this->Task->expects($this->at(6))->method('out')->with("Components:\n\tAcl, Auth"); + $this->Task->confirmController($controller, $scaffold, $helpers, $components); + } + +/** + * test the bake method + * + * @return void + */ + public function testBake() { + $helpers = array('Ajax', 'Time'); + $components = array('Acl', 'Auth'); + $this->Task->expects($this->any())->method('createFile')->will($this->returnValue(true)); + + $result = $this->Task->bake('Articles', '--actions--', $helpers, $components); + $this->assertContains(' * @property Article $Article', $result); + $this->assertContains(' * @property AclComponent $Acl', $result); + $this->assertContains(' * @property AuthComponent $Auth', $result); + $this->assertContains('class ArticlesController extends AppController', $result); + $this->assertContains("public \$components = array('Acl', 'Auth')", $result); + $this->assertContains("public \$helpers = array('Ajax', 'Time')", $result); + $this->assertContains("--actions--", $result); + + $result = $this->Task->bake('Articles', 'scaffold', $helpers, $components); + $this->assertContains("class ArticlesController extends AppController", $result); + $this->assertContains("public \$scaffold", $result); + $this->assertNotContains('@property', $result); + $this->assertNotContains('helpers', $result); + $this->assertNotContains('components', $result); + + $result = $this->Task->bake('Articles', '--actions--', array(), array()); + $this->assertContains('class ArticlesController extends AppController', $result); + $this->assertSame(substr_count($result, '@property'), 1); + $this->assertNotContains('components', $result); + $this->assertNotContains('helpers', $result); + $this->assertContains('--actions--', $result); + } + +/** + * test bake() with a -plugin param + * + * @return void + */ + public function testBakeWithPlugin() { + $this->Task->plugin = 'ControllerTest'; + + //fake plugin path + CakePlugin::load('ControllerTest', array('path' => APP . 'Plugin' . DS . 'ControllerTest' . DS)); + $path = APP . 'Plugin' . DS . 'ControllerTest' . DS . 'Controller' . DS . 'ArticlesController.php'; + + $this->Task->expects($this->at(1))->method('createFile')->with( + $path, + new PHPUnit_Framework_Constraint_IsAnything() + ); + $this->Task->expects($this->at(3))->method('createFile')->with( + $path, + $this->stringContains('ArticlesController extends ControllerTestAppController') + )->will($this->returnValue(true)); + + $this->Task->bake('Articles', '--actions--', array(), array(), array()); + + $this->Task->plugin = 'ControllerTest'; + $path = APP . 'Plugin' . DS . 'ControllerTest' . DS . 'Controller' . DS . 'ArticlesController.php'; + $result = $this->Task->bake('Articles', '--actions--', array(), array(), array()); + + $this->assertContains("App::uses('ControllerTestAppController', 'ControllerTest.Controller');", $result); + $this->assertEquals('ControllerTest', $this->Task->Template->templateVars['plugin']); + $this->assertEquals('ControllerTest.', $this->Task->Template->templateVars['pluginPath']); + + CakePlugin::unload(); + } + +/** + * test that bakeActions is creating the correct controller Code. (Using sessions) + * + * @return void + */ + public function testBakeActionsUsingSessions() { + $this->skipIf(!defined('ARTICLE_MODEL_CREATED'), 'Testing bakeActions requires Article, Comment & Tag Model to be undefined.'); + + $result = $this->Task->bakeActions('BakeArticles', null, true); + + $this->assertContains('function index() {', $result); + $this->assertContains('$this->BakeArticle->recursive = 0;', $result); + $this->assertContains("\$this->set('bakeArticles', \$this->paginate());", $result); + + $this->assertContains('function view($id = null)', $result); + $this->assertContains("throw new NotFoundException(__('Invalid bake article'));", $result); + $this->assertContains("\$this->set('bakeArticle', \$this->BakeArticle->read(null, \$id)", $result); + + $this->assertContains('function add()', $result); + $this->assertContains("if (\$this->request->is('post'))", $result); + $this->assertContains('if ($this->BakeArticle->save($this->request->data))', $result); + $this->assertContains("\$this->Session->setFlash(__('The bake article has been saved'));", $result); + + $this->assertContains('function edit($id = null)', $result); + $this->assertContains("\$this->Session->setFlash(__('The bake article could not be saved. Please, try again.'));", $result); + + $this->assertContains('function delete($id = null)', $result); + $this->assertContains('if ($this->BakeArticle->delete())', $result); + $this->assertContains("\$this->Session->setFlash(__('Bake article deleted'));", $result); + + $result = $this->Task->bakeActions('BakeArticles', 'admin_', true); + + $this->assertContains('function admin_index() {', $result); + $this->assertContains('function admin_add()', $result); + $this->assertContains('function admin_view($id = null)', $result); + $this->assertContains('function admin_edit($id = null)', $result); + $this->assertContains('function admin_delete($id = null)', $result); + } + +/** + * Test baking with Controller::flash() or no sessions. + * + * @return void + */ + public function testBakeActionsWithNoSessions() { + $this->skipIf(!defined('ARTICLE_MODEL_CREATED'), 'Testing bakeActions requires Article, Tag, Comment Models to be undefined.'); + + $result = $this->Task->bakeActions('BakeArticles', null, false); + + $this->assertContains('function index() {', $result); + $this->assertContains('$this->BakeArticle->recursive = 0;', $result); + $this->assertContains("\$this->set('bakeArticles', \$this->paginate());", $result); + + $this->assertContains('function view($id = null)', $result); + $this->assertContains("throw new NotFoundException(__('Invalid bake article'));", $result); + $this->assertContains("\$this->set('bakeArticle', \$this->BakeArticle->read(null, \$id)", $result); + + $this->assertContains('function add()', $result); + $this->assertContains("if (\$this->request->is('post'))", $result); + $this->assertContains('if ($this->BakeArticle->save($this->request->data))', $result); + + $this->assertContains("\$this->flash(__('The bake article has been saved.'), array('action' => 'index'))", $result); + + $this->assertContains('function edit($id = null)', $result); + $this->assertContains("\$this->BakeArticle->BakeTag->find('list')", $result); + $this->assertContains("\$this->set(compact('bakeTags'))", $result); + + $this->assertContains('function delete($id = null)', $result); + $this->assertContains('if ($this->BakeArticle->delete())', $result); + $this->assertContains("\$this->flash(__('Bake article deleted'), array('action' => 'index'))", $result); + } + +/** + * test baking a test + * + * @return void + */ + public function testBakeTest() { + $this->Task->plugin = 'ControllerTest'; + $this->Task->connection = 'test'; + $this->Task->interactive = false; + + $this->Task->Test->expects($this->once())->method('bake')->with('Controller', 'BakeArticles'); + $this->Task->bakeTest('BakeArticles'); + + $this->assertEquals($this->Task->plugin, $this->Task->Test->plugin); + $this->assertEquals($this->Task->connection, $this->Task->Test->connection); + $this->assertEquals($this->Task->interactive, $this->Task->Test->interactive); + } + +/** + * test Interactive mode. + * + * @return void + */ + public function testInteractive() { + $count = count($this->Task->listAll('test')); + if ($count != count($this->fixtures)) { + $this->markTestSkipped('Additional tables detected.'); + } + + $this->Task->connection = 'test'; + $this->Task->path = '/my/path/'; + + $this->Task->expects($this->any())->method('in') + ->will($this->onConsecutiveCalls( + '1', + 'y', // build interactive + 'n', // build no scaffolds + 'y', // build normal methods + 'n', // build admin methods + 'n', // helpers? + 'n', // components? + 'y', // sessions ? + 'y' // looks good? + )); + + $filename = '/my/path/BakeArticlesController.php'; + $this->Task->expects($this->once())->method('createFile')->with( + $filename, + $this->stringContains('class BakeArticlesController') + ); + $this->Task->execute(); + } + +/** + * test Interactive mode. + * + * @return void + */ + public function testInteractiveAdminMethodsNotInteractive() { + $count = count($this->Task->listAll('test')); + if ($count != count($this->fixtures)) { + $this->markTestSkipped('Additional tables detected.'); + } + + $this->Task->connection = 'test'; + $this->Task->interactive = true; + $this->Task->path = '/my/path/'; + + $this->Task->expects($this->any())->method('in') + ->will($this->onConsecutiveCalls( + '1', + 'y', // build interactive + 'n', // build no scaffolds + 'y', // build normal methods + 'y', // build admin methods + 'n', // helpers? + 'n', // components? + 'y', // sessions ? + 'y' // looks good? + )); + + $this->Task->Project->expects($this->any()) + ->method('getPrefix') + ->will($this->returnValue('admin_')); + + $filename = '/my/path/BakeArticlesController.php'; + $this->Task->expects($this->once())->method('createFile')->with( + $filename, + $this->stringContains('class BakeArticlesController') + )->will($this->returnValue(true)); + + $result = $this->Task->execute(); + $this->assertRegExp('/admin_index/', $result); + } + +/** + * test that execute runs all when the first arg == all + * + * @return void + */ + public function testExecuteIntoAll() { + $count = count($this->Task->listAll('test')); + if ($count != count($this->fixtures)) { + $this->markTestSkipped('Additional tables detected.'); + } + if (!defined('ARTICLE_MODEL_CREATED')) { + $this->markTestSkipped('Execute into all could not be run as an Article, Tag or Comment model was already loaded.'); + } + $this->Task->connection = 'test'; + $this->Task->path = '/my/path/'; + $this->Task->args = array('all'); + + $this->Task->expects($this->any())->method('_checkUnitTest')->will($this->returnValue(true)); + $this->Task->Test->expects($this->once())->method('bake'); + + $filename = '/my/path/BakeArticlesController.php'; + $this->Task->expects($this->once())->method('createFile')->with( + $filename, + $this->stringContains('class BakeArticlesController') + )->will($this->returnValue(true)); + + $this->Task->execute(); + } + +/** + * test that `cake bake controller foos` works. + * + * @return void + */ + public function testExecuteWithController() { + if (!defined('ARTICLE_MODEL_CREATED')) { + $this->markTestSkipped('Execute with scaffold param requires no Article, Tag or Comment model to be defined'); + } + $this->Task->connection = 'test'; + $this->Task->path = '/my/path/'; + $this->Task->args = array('BakeArticles'); + + $filename = '/my/path/BakeArticlesController.php'; + $this->Task->expects($this->once())->method('createFile')->with( + $filename, + $this->stringContains('$scaffold') + ); + + $this->Task->execute(); + } + +/** + * data provider for testExecuteWithControllerNameVariations + * + * @return void + */ + public static function nameVariations() { + return array( + array('BakeArticles'), array('BakeArticle'), array('bake_article'), array('bake_articles') + ); + } + +/** + * test that both plural and singular forms work for controller baking. + * + * @dataProvider nameVariations + * @return void + */ + public function testExecuteWithControllerNameVariations($name) { + if (!defined('ARTICLE_MODEL_CREATED')) { + $this->markTestSkipped('Execute with scaffold param requires no Article, Tag or Comment model to be defined.'); + } + $this->Task->connection = 'test'; + $this->Task->path = '/my/path/'; + $this->Task->args = array($name); + + $filename = '/my/path/BakeArticlesController.php'; + $this->Task->expects($this->once())->method('createFile')->with( + $filename, $this->stringContains('$scaffold') + ); + $this->Task->execute(); + } + +/** + * test that `cake bake controller foo scaffold` works. + * + * @return void + */ + public function testExecuteWithPublicParam() { + if (!defined('ARTICLE_MODEL_CREATED')) { + $this->markTestSkipped('Execute with public param requires no Article, Tag or Comment model to be defined.'); + } + $this->Task->connection = 'test'; + $this->Task->path = '/my/path/'; + $this->Task->args = array('BakeArticles'); + $this->Task->params = array('public' => true); + + $filename = '/my/path/BakeArticlesController.php'; + $expected = new PHPUnit_Framework_Constraint_Not($this->stringContains('$scaffold')); + $this->Task->expects($this->once())->method('createFile')->with( + $filename, $expected + ); + $this->Task->execute(); + } + +/** + * test that `cake bake controller foos both` works. + * + * @return void + */ + public function testExecuteWithControllerAndBoth() { + if (!defined('ARTICLE_MODEL_CREATED')) { + $this->markTestSkipped('Execute with controller and both requires no Article, Tag or Comment model to be defined.'); + } + $this->Task->Project->expects($this->any())->method('getPrefix')->will($this->returnValue('admin_')); + $this->Task->connection = 'test'; + $this->Task->path = '/my/path/'; + $this->Task->args = array('BakeArticles'); + $this->Task->params = array('public' => true, 'admin' => true); + + $filename = '/my/path/BakeArticlesController.php'; + $this->Task->expects($this->once())->method('createFile')->with( + $filename, $this->stringContains('admin_index') + ); + $this->Task->execute(); + } + +/** + * test that `cake bake controller foos admin` works. + * + * @return void + */ + public function testExecuteWithControllerAndAdmin() { + if (!defined('ARTICLE_MODEL_CREATED')) { + $this->markTestSkipped('Execute with controller and admin requires no Article, Tag or Comment model to be defined.'); + } + $this->Task->Project->expects($this->any())->method('getPrefix')->will($this->returnValue('admin_')); + $this->Task->connection = 'test'; + $this->Task->path = '/my/path/'; + $this->Task->args = array('BakeArticles'); + $this->Task->params = array('admin' => true); + + $filename = '/my/path/BakeArticlesController.php'; + $this->Task->expects($this->once())->method('createFile')->with( + $filename, $this->stringContains('admin_index') + ); + $this->Task->execute(); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/Task/DbConfigTaskTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/Task/DbConfigTaskTest.php new file mode 100644 index 0000000..b831c95 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/Task/DbConfigTaskTest.php @@ -0,0 +1,133 @@ +getMock('ConsoleOutput', array(), array(), '', false); + $in = $this->getMock('ConsoleInput', array(), array(), '', false); + + $this->Task = $this->getMock('DbConfigTask', + array('in', 'out', 'err', 'hr', 'createFile', '_stop', '_checkUnitTest', '_verify'), + array($out, $out, $in) + ); + + $this->Task->path = APP . 'Config' . DS; + } + +/** + * tearDown method + * + * @return void + */ + public function tearDown() { + parent::tearDown(); + unset($this->Task); + } + +/** + * Test the getConfig method. + * + * @return void + */ + public function testGetConfig() { + $this->Task->expects($this->any()) + ->method('in') + ->will($this->returnValue('test')); + + $result = $this->Task->getConfig(); + $this->assertEquals('test', $result); + } + +/** + * test that initialize sets the path up. + * + * @return void + */ + public function testInitialize() { + $this->Task->initialize(); + $this->assertFalse(empty($this->Task->path)); + $this->assertEquals(APP . 'Config' . DS, $this->Task->path); + } + +/** + * test execute and by extension _interactive + * + * @return void + */ + public function testExecuteIntoInteractive() { + $this->Task->initialize(); + + $out = $this->getMock('ConsoleOutput', array(), array(), '', false); + $in = $this->getMock('ConsoleInput', array(), array(), '', false); + $this->Task = $this->getMock( + 'DbConfigTask', + array('in', '_stop', 'createFile', 'bake'), array($out, $out, $in) + ); + + $this->Task->expects($this->once())->method('_stop'); + $this->Task->expects($this->at(0))->method('in')->will($this->returnValue('default')); //name + $this->Task->expects($this->at(1))->method('in')->will($this->returnValue('mysql')); //db type + $this->Task->expects($this->at(2))->method('in')->will($this->returnValue('n')); //persistant + $this->Task->expects($this->at(3))->method('in')->will($this->returnValue('localhost')); //server + $this->Task->expects($this->at(4))->method('in')->will($this->returnValue('n')); //port + $this->Task->expects($this->at(5))->method('in')->will($this->returnValue('root')); //user + $this->Task->expects($this->at(6))->method('in')->will($this->returnValue('password')); //password + $this->Task->expects($this->at(10))->method('in')->will($this->returnValue('cake_test')); //db + $this->Task->expects($this->at(11))->method('in')->will($this->returnValue('n')); //prefix + $this->Task->expects($this->at(12))->method('in')->will($this->returnValue('n')); //encoding + $this->Task->expects($this->at(13))->method('in')->will($this->returnValue('y')); //looks good + $this->Task->expects($this->at(14))->method('in')->will($this->returnValue('n')); //another + $this->Task->expects($this->at(15))->method('bake') + ->with(array( + array( + 'name' => 'default', + 'datasource' => 'mysql', + 'persistent' => 'false', + 'host' => 'localhost', + 'login' => 'root', + 'password' => 'password', + 'database' => 'cake_test', + 'prefix' => null, + 'encoding' => null, + 'port' => '', + 'schema' => null + ) + )); + + $result = $this->Task->execute(); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/Task/ExtractTaskTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/Task/ExtractTaskTest.php new file mode 100644 index 0000000..66bc9c2 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/Task/ExtractTaskTest.php @@ -0,0 +1,462 @@ +getMock('ConsoleOutput', array(), array(), '', false); + $in = $this->getMock('ConsoleInput', array(), array(), '', false); + + $this->Task = $this->getMock( + 'ExtractTask', + array('in', 'out', 'err', '_stop'), + array($out, $out, $in) + ); + $this->path = TMP . 'tests' . DS . 'extract_task_test'; + $Folder = new Folder($this->path . DS . 'locale', true); + } + +/** + * tearDown method + * + * @return void + */ + public function tearDown() { + parent::tearDown(); + unset($this->Task); + + $Folder = new Folder($this->path); + $Folder->delete(); + CakePlugin::unload(); + } + +/** + * testExecute method + * + * @return void + */ + public function testExecute() { + $this->Task->interactive = false; + + $this->Task->params['paths'] = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS . 'Pages'; + $this->Task->params['output'] = $this->path . DS; + $this->Task->params['extract-core'] = 'no'; + $this->Task->expects($this->never())->method('err'); + $this->Task->expects($this->any())->method('in') + ->will($this->returnValue('y')); + $this->Task->expects($this->never())->method('_stop'); + + $this->Task->execute(); + $this->assertTrue(file_exists($this->path . DS . 'default.pot')); + $result = file_get_contents($this->path . DS . 'default.pot'); + + $this->assertFalse(file_exists($this->path . DS . 'cake.pot')); + + $pattern = '/"Content-Type\: text\/plain; charset\=utf-8/'; + $this->assertRegExp($pattern, $result); + $pattern = '/"Content-Transfer-Encoding\: 8bit/'; + $this->assertRegExp($pattern, $result); + $pattern = '/"Plural-Forms\: nplurals\=INTEGER; plural\=EXPRESSION;/'; + $this->assertRegExp($pattern, $result); + + // home.ctp + $pattern = '/msgid "Your tmp directory is writable."\nmsgstr ""\n/'; + $this->assertRegExp($pattern, $result); + + $pattern = '/msgid "Your tmp directory is NOT writable."\nmsgstr ""\n/'; + $this->assertRegExp($pattern, $result); + + $pattern = '/msgid "The %s is being used for caching. To change the config edit '; + $pattern .= 'APP\/config\/core.php "\nmsgstr ""\n/'; + $this->assertRegExp($pattern, $result); + + $pattern = '/msgid "Your cache is NOT working. Please check '; + $pattern .= 'the settings in APP\/config\/core.php"\nmsgstr ""\n/'; + $this->assertRegExp($pattern, $result); + + $pattern = '/msgid "Your database configuration file is present."\nmsgstr ""\n/'; + $this->assertRegExp($pattern, $result); + + $pattern = '/msgid "Your database configuration file is NOT present."\nmsgstr ""\n/'; + $this->assertRegExp($pattern, $result); + + $pattern = '/msgid "Rename config\/database.php.default to '; + $pattern .= 'config\/database.php"\nmsgstr ""\n/'; + $this->assertRegExp($pattern, $result); + + $pattern = '/msgid "Cake is able to connect to the database."\nmsgstr ""\n/'; + $this->assertRegExp($pattern, $result); + + $pattern = '/msgid "Cake is NOT able to connect to the database."\nmsgstr ""\n/'; + $this->assertRegExp($pattern, $result); + + $pattern = '/msgid "Editing this Page"\nmsgstr ""\n/'; + $this->assertRegExp($pattern, $result); + + $pattern = '/msgid "To change the content of this page, create: APP\/views\/pages\/home\.ctp/'; + $this->assertRegExp($pattern, $result); + + $pattern = '/To change its layout, create: APP\/views\/layouts\/default\.ctp\./s'; + $this->assertRegExp($pattern, $result); + + // extract.ctp + $pattern = '/\#: (\\\\|\/)extract\.ctp:15;6\n'; + $pattern .= 'msgid "You have %d new message."\nmsgid_plural "You have %d new messages."/'; + $this->assertRegExp($pattern, $result); + + $pattern = '/msgid "You have %d new message."\nmsgstr ""/'; + $this->assertNotRegExp($pattern, $result, 'No duplicate msgid'); + + $pattern = '/\#: (\\\\|\/)extract\.ctp:7\n'; + $pattern .= 'msgid "You deleted %d message."\nmsgid_plural "You deleted %d messages."/'; + $this->assertRegExp($pattern, $result); + + $pattern = '/\#: (\\\\|\/)extract\.ctp:14\n'; + $pattern .= '\#: (\\\\|\/)home\.ctp:99\n'; + $pattern .= 'msgid "Editing this Page"\nmsgstr ""/'; + $this->assertRegExp($pattern, $result); + + $pattern = '/\#: (\\\\|\/)extract\.ctp:18\nmsgid "'; + $pattern .= 'Hot features!'; + $pattern .= '\\\n - No Configuration: Set-up the database and let the magic begin'; + $pattern .= '\\\n - Extremely Simple: Just look at the name...It\'s Cake'; + $pattern .= '\\\n - Active, Friendly Community: Join us #cakephp on IRC. We\'d love to help you get started'; + $pattern .= '"\nmsgstr ""/'; + $this->assertRegExp($pattern, $result); + + // extract.ctp - reading the domain.pot + $result = file_get_contents($this->path . DS . 'domain.pot'); + + $pattern = '/msgid "You have %d new message."\nmsgid_plural "You have %d new messages."/'; + $this->assertNotRegExp($pattern, $result); + $pattern = '/msgid "You deleted %d message."\nmsgid_plural "You deleted %d messages."/'; + $this->assertNotRegExp($pattern, $result); + + $pattern = '/msgid "You have %d new message \(domain\)."\nmsgid_plural "You have %d new messages \(domain\)."/'; + $this->assertRegExp($pattern, $result); + $pattern = '/msgid "You deleted %d message \(domain\)."\nmsgid_plural "You deleted %d messages \(domain\)."/'; + $this->assertRegExp($pattern, $result); + } + +/** + * test exclusions + * + * @return void + */ + public function testExtractWithExclude() { + $this->Task->interactive = false; + + $this->Task->params['paths'] = CAKE . 'Test' . DS . 'test_app' . DS . 'View'; + $this->Task->params['output'] = $this->path . DS; + $this->Task->params['exclude'] = 'Pages,Layouts'; + $this->Task->params['extract-core'] = 'no'; + + $this->Task->expects($this->any())->method('in') + ->will($this->returnValue('y')); + + $this->Task->execute(); + $this->assertTrue(file_exists($this->path . DS . 'default.pot')); + $result = file_get_contents($this->path . DS . 'default.pot'); + + $pattern = '/\#: .*extract\.ctp:6\n/'; + $this->assertNotRegExp($pattern, $result); + + $pattern = '/\#: .*default\.ctp:26\n/'; + $this->assertNotRegExp($pattern, $result); + } + +/** + * test extract can read more than one path. + * + * @return void + */ + public function testExtractMultiplePaths() { + $this->Task->interactive = false; + + $this->Task->params['paths'] = + CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS . 'Pages,' . + CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS . 'Posts'; + + $this->Task->params['output'] = $this->path . DS; + $this->Task->params['extract-core'] = 'no'; + $this->Task->expects($this->never())->method('err'); + $this->Task->expects($this->never())->method('_stop'); + $this->Task->execute(); + + $result = file_get_contents($this->path . DS . 'default.pot'); + + $pattern = '/msgid "Add User"/'; + $this->assertRegExp($pattern, $result); + } + +/** + * Tests that it is possible to exclude plugin paths by enabling the param option for the ExtractTask + * + * @return void + */ + public function testExtractExcludePlugins() { + App::build(array( + 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS) + )); + $this->out = $this->getMock('ConsoleOutput', array(), array(), '', false); + $this->in = $this->getMock('ConsoleInput', array(), array(), '', false); + $this->Task = $this->getMock('ExtractTask', + array('_isExtractingApp', '_extractValidationMessages', 'in', 'out', 'err', 'clear', '_stop'), + array($this->out, $this->out, $this->in) + ); + $this->Task->expects($this->exactly(2))->method('_isExtractingApp')->will($this->returnValue(true)); + + $this->Task->params['paths'] = CAKE . 'Test' . DS . 'test_app' . DS; + $this->Task->params['output'] = $this->path . DS; + $this->Task->params['exclude-plugins'] = true; + + $this->Task->execute(); + $result = file_get_contents($this->path . DS . 'default.pot'); + $this->assertNotRegExp('#TestPlugin#', $result); + } + +/** + * Test that is possible to extract messages form a single plugin + * + * @return void + */ + public function testExtractPlugin() { + App::build(array( + 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS) + )); + + $this->out = $this->getMock('ConsoleOutput', array(), array(), '', false); + $this->in = $this->getMock('ConsoleInput', array(), array(), '', false); + $this->Task = $this->getMock('ExtractTask', + array('_isExtractingApp', '_extractValidationMessages', 'in', 'out', 'err', 'clear', '_stop'), + array($this->out, $this->out, $this->in) + ); + + $this->Task->params['output'] = $this->path . DS; + $this->Task->params['plugin'] = 'TestPlugin'; + + $this->Task->execute(); + $result = file_get_contents($this->path . DS . 'default.pot'); + $this->assertNotRegExp('#Pages#', $result); + $this->assertContains('translate.ctp:1', $result); + $this->assertContains('This is a translatable string', $result); + } + +/** + * Tests that the task will inspect application models and extract the validation messages from them + * + * @return void + */ + public function testExtractModelValidation() { + App::build(array( + 'Model' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Model' . DS), + 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS) + ), App::RESET); + $this->out = $this->getMock('ConsoleOutput', array(), array(), '', false); + $this->in = $this->getMock('ConsoleInput', array(), array(), '', false); + $this->Task = $this->getMock('ExtractTask', + array('_isExtractingApp', 'in', 'out', 'err', 'clear', '_stop'), + array($this->out, $this->out, $this->in) + ); + $this->Task->expects($this->exactly(2))->method('_isExtractingApp')->will($this->returnValue(true)); + + $this->Task->params['paths'] = CAKE . 'Test' . DS . 'test_app' . DS; + $this->Task->params['output'] = $this->path . DS; + $this->Task->params['extract-core'] = 'no'; + $this->Task->params['exclude-plugins'] = true; + $this->Task->params['ignore-model-validation'] = false; + + $this->Task->execute(); + $result = file_get_contents($this->path . DS . 'default.pot'); + + $pattern = preg_quote('#Model' . DS . 'PersisterOne.php:validation for field title#', '\\'); + $this->assertRegExp($pattern, $result); + + $pattern = preg_quote('#Model' . DS . 'PersisterOne.php:validation for field body#', '\\'); + $this->assertRegExp($pattern, $result); + + $pattern = '#msgid "Post title is required"#'; + $this->assertRegExp($pattern, $result); + + $pattern = '#msgid "You may enter up to %s chars \(minimum is %s chars\)"#'; + $this->assertRegExp($pattern, $result); + + $pattern = '#msgid "Post body is required"#'; + $this->assertRegExp($pattern, $result); + + $pattern = '#msgid "Post body is super required"#'; + $this->assertRegExp($pattern, $result); + } + +/** + * Tests that the task will inspect application models and extract the validation messages from them + * while using a custom validation domain for the messages set on the model itself + * + * @return void + */ + public function testExtractModelValidationWithDomainInModel() { + App::build(array( + 'Model' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS . 'TestPlugin' . DS . 'Model' . DS) + )); + $this->out = $this->getMock('ConsoleOutput', array(), array(), '', false); + $this->in = $this->getMock('ConsoleInput', array(), array(), '', false); + $this->Task = $this->getMock('ExtractTask', + array('_isExtractingApp', 'in', 'out', 'err', 'clear', '_stop'), + array($this->out, $this->out, $this->in) + ); + $this->Task->expects($this->exactly(2))->method('_isExtractingApp')->will($this->returnValue(true)); + + $this->Task->params['paths'] = CAKE . 'Test' . DS . 'test_app' . DS; + $this->Task->params['output'] = $this->path . DS; + $this->Task->params['extract-core'] = 'no'; + $this->Task->params['exclude-plugins'] = true; + $this->Task->params['ignore-model-validation'] = false; + + $this->Task->execute(); + $result = file_get_contents($this->path . DS . 'test_plugin.pot'); + + $pattern = preg_quote('#Plugin' . DS . 'TestPlugin' . DS . 'Model' . DS . 'TestPluginPost.php:validation for field title#', '\\'); + $this->assertRegExp($pattern, $result); + + $pattern = preg_quote('#Plugin' . DS . 'TestPlugin' . DS . 'Model' . DS . 'TestPluginPost.php:validation for field body#', '\\'); + $this->assertRegExp($pattern, $result); + + $pattern = '#msgid "Post title is required"#'; + $this->assertRegExp($pattern, $result); + + $pattern = '#msgid "Post body is required"#'; + $this->assertRegExp($pattern, $result); + + $pattern = '#msgid "Post body is super required"#'; + $this->assertRegExp($pattern, $result); + } + +/** + * Test that the extract shell can obtain validation messages from models inside a specific plugin + * + * @return void + */ + public function testExtractModelValidationInPlugin() { + App::build(array( + 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS) + )); + $this->out = $this->getMock('ConsoleOutput', array(), array(), '', false); + $this->in = $this->getMock('ConsoleInput', array(), array(), '', false); + $this->Task = $this->getMock('ExtractTask', + array('_isExtractingApp', 'in', 'out', 'err', 'clear', '_stop'), + array($this->out, $this->out, $this->in) + ); + + $this->Task->params['output'] = $this->path . DS; + $this->Task->params['ignore-model-validation'] = false; + $this->Task->params['plugin'] = 'TestPlugin'; + + $this->Task->execute(); + $result = file_get_contents($this->path . DS . 'test_plugin.pot'); + + $pattern = preg_quote('#Model' . DS . 'TestPluginPost.php:validation for field title#', '\\'); + $this->assertRegExp($pattern, $result); + + $pattern = preg_quote('#Model' . DS . 'TestPluginPost.php:validation for field body#', '\\'); + $this->assertRegExp($pattern, $result); + + $pattern = '#msgid "Post title is required"#'; + $this->assertRegExp($pattern, $result); + + $pattern = '#msgid "Post body is required"#'; + $this->assertRegExp($pattern, $result); + + $pattern = '#msgid "Post body is super required"#'; + $this->assertRegExp($pattern, $result); + + $pattern = '#Plugin/TestPlugin/Model/TestPluginPost.php:validation for field title#'; + $this->assertNotRegExp($pattern, $result); + } + +/** + * Test that the extract shell overwrites existing files with the overwrite parameter + * + * @return void + */ + public function testExtractOverwrite() { + $this->Task->interactive = false; + + $this->Task->params['paths'] = CAKE . 'Test' . DS . 'test_app' . DS; + $this->Task->params['output'] = $this->path . DS; + $this->Task->params['extract-core'] = 'no'; + $this->Task->params['overwrite'] = true; + + file_put_contents($this->path . DS . 'default.pot', 'will be overwritten'); + $this->assertTrue(file_exists($this->path . DS . 'default.pot')); + $original = file_get_contents($this->path . DS . 'default.pot'); + + $this->Task->execute(); + $result = file_get_contents($this->path . DS . 'default.pot'); + $this->assertNotEquals($original, $result); + } + +/** + * Test that the extract shell scans the core libs + * + * @return void + */ + public function testExtractCore() { + $this->Task->interactive = false; + + $this->Task->params['paths'] = CAKE . 'Test' . DS . 'test_app' . DS; + $this->Task->params['output'] = $this->path . DS; + $this->Task->params['extract-core'] = 'yes'; + + $this->Task->execute(); + $this->assertTrue(file_exists($this->path . DS . 'cake.pot')); + $result = file_get_contents($this->path . DS . 'cake.pot'); + + $pattern = '/msgid "Yesterday, %s"\nmsgstr ""\n/'; + $this->assertRegExp($pattern, $result); + + $this->assertTrue(file_exists($this->path . DS . 'cake_dev.pot')); + $result = file_get_contents($this->path . DS . 'cake_dev.pot'); + + $pattern = '/#: Console\/Templates\//'; + $this->assertNotRegExp($pattern, $result); + + $pattern = '/#: Test\//'; + $this->assertNotRegExp($pattern, $result); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/Task/FixtureTaskTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/Task/FixtureTaskTest.php new file mode 100644 index 0000000..9f2cbd0 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/Task/FixtureTaskTest.php @@ -0,0 +1,388 @@ +getMock('ConsoleOutput', array(), array(), '', false); + $in = $this->getMock('ConsoleInput', array(), array(), '', false); + + $this->Task = $this->getMock('FixtureTask', + array('in', 'err', 'createFile', '_stop', 'clear'), + array($out, $out, $in) + ); + $this->Task->Model = $this->getMock('ModelTask', + array('in', 'out', 'err', 'createFile', 'getName', 'getTable', 'listAll'), + array($out, $out, $in) + ); + $this->Task->Template = new TemplateTask($out, $out, $in); + $this->Task->DbConfig = $this->getMock('DbConfigTask', array(), array($out, $out, $in)); + $this->Task->Template->initialize(); + } + +/** + * tearDown method + * + * @return void + */ + public function tearDown() { + parent::tearDown(); + unset($this->Task); + } + +/** + * test that initialize sets the path + * + * @return void + */ + public function testConstruct() { + $out = $this->getMock('ConsoleOutput', array(), array(), '', false); + $in = $this->getMock('ConsoleInput', array(), array(), '', false); + + $Task = new FixtureTask($out, $out, $in); + $this->assertEquals(APP . 'Test' . DS . 'Fixture' . DS, $Task->path); + } + +/** + * test import option array generation + * + * @return void + */ + public function testImportOptionsSchemaRecords() { + $this->Task->expects($this->at(0))->method('in')->will($this->returnValue('y')); + $this->Task->expects($this->at(1))->method('in')->will($this->returnValue('y')); + + $result = $this->Task->importOptions('Article'); + $expected = array('schema' => 'Article', 'records' => true); + $this->assertEquals($expected, $result); + } + +/** + * test importOptions choosing nothing. + * + * @return void + */ + public function testImportOptionsNothing() { + $this->Task->expects($this->at(0))->method('in')->will($this->returnValue('n')); + $this->Task->expects($this->at(1))->method('in')->will($this->returnValue('n')); + $this->Task->expects($this->at(2))->method('in')->will($this->returnValue('n')); + + $result = $this->Task->importOptions('Article'); + $expected = array(); + $this->assertEquals($expected, $result); + } + +/** + * test importOptions choosing from Table. + * + * @return void + */ + public function testImportOptionsTable() { + $this->Task->expects($this->at(0))->method('in')->will($this->returnValue('n')); + $this->Task->expects($this->at(1))->method('in')->will($this->returnValue('n')); + $this->Task->expects($this->at(2))->method('in')->will($this->returnValue('y')); + $result = $this->Task->importOptions('Article'); + $expected = array('fromTable' => true); + $this->assertEquals($expected, $result); + } + +/** + * test generating a fixture with database conditions. + * + * @return void + */ + public function testImportRecordsFromDatabaseWithConditionsPoo() { + $this->Task->interactive = true; + $this->Task->expects($this->at(0))->method('in') + ->will($this->returnValue('WHERE 1=1')); + + $this->Task->connection = 'test'; + $this->Task->path = '/my/path/'; + + $result = $this->Task->bake('Article', false, array( + 'fromTable' => true, 'schema' => 'Article', 'records' => false + )); + + $this->assertContains('class ArticleFixture extends CakeTestFixture', $result); + $this->assertContains('public $records', $result); + $this->assertContains('public $import', $result); + $this->assertContains("'title' => 'First Article'", $result, 'Missing import data %s'); + $this->assertContains('Second Article', $result, 'Missing import data %s'); + $this->assertContains('Third Article', $result, 'Missing import data %s'); + } + +/** + * test that connection gets set to the import options when a different connection is used. + * + * @return void + */ + public function testImportOptionsAlternateConnection() { + $this->Task->connection = 'test'; + $result = $this->Task->bake('Article', false, array('schema' => 'Article')); + $this->assertContains("'connection' => 'test'", $result); + } + +/** + * Ensure that fixture data doesn't get overly escaped. + * + * @return void + */ + public function testImportRecordsNoEscaping() { + $db = ConnectionManager::getDataSource('test'); + if ($db instanceof Sqlserver) { + $this->markTestSkipped('This test does not run on SQLServer'); + } + + $Article = ClassRegistry::init('Article'); + $Article->updateAll(array('body' => "'Body \"value\"'")); + + $this->Task->interactive = true; + $this->Task->expects($this->at(0)) + ->method('in') + ->will($this->returnValue('WHERE 1=1 LIMIT 10')); + + $this->Task->connection = 'test'; + $this->Task->path = '/my/path/'; + $result = $this->Task->bake('Article', false, array( + 'fromTable' => true, + 'schema' => 'Article', + 'records' => false + )); + $this->assertContains("'body' => 'Body \"value\"'", $result, 'Data has bad escaping'); + } + +/** + * test that execute passes runs bake depending with named model. + * + * + * @return void + */ + public function testExecuteWithNamedModel() { + $this->Task->connection = 'test'; + $this->Task->path = '/my/path/'; + $this->Task->args = array('article'); + $filename = '/my/path/ArticleFixture.php'; + + $this->Task->expects($this->at(0))->method('createFile') + ->with($filename, $this->stringContains('class ArticleFixture')); + + $this->Task->execute(); + } + +/** + * test that execute runs all() when args[0] = all + * + * @return void + */ + public function testExecuteIntoAll() { + $this->Task->connection = 'test'; + $this->Task->path = '/my/path/'; + $this->Task->args = array('all'); + $this->Task->Model->expects($this->any()) + ->method('listAll') + ->will($this->returnValue(array('articles', 'comments'))); + + $filename = '/my/path/ArticleFixture.php'; + $this->Task->expects($this->at(0)) + ->method('createFile') + ->with($filename, $this->stringContains('class ArticleFixture')); + + $filename = '/my/path/CommentFixture.php'; + $this->Task->expects($this->at(1)) + ->method('createFile') + ->with($filename, $this->stringContains('class CommentFixture')); + + $this->Task->execute(); + } + +/** + * test using all() with -count and -records + * + * @return void + */ + public function testAllWithCountAndRecordsFlags() { + $this->Task->connection = 'test'; + $this->Task->path = '/my/path/'; + $this->Task->args = array('all'); + $this->Task->params = array('count' => 10, 'records' => true); + + $this->Task->Model->expects($this->any())->method('listAll') + ->will($this->returnValue(array('Articles', 'comments'))); + + $filename = '/my/path/ArticleFixture.php'; + $this->Task->expects($this->at(0))->method('createFile') + ->with($filename, $this->stringContains("'title' => 'Third Article'")); + + $filename = '/my/path/CommentFixture.php'; + $this->Task->expects($this->at(1))->method('createFile') + ->with($filename, $this->stringContains("'comment' => 'First Comment for First Article'")); + $this->Task->expects($this->exactly(2))->method('createFile'); + + $this->Task->all(); + } + +/** + * test interactive mode of execute + * + * @return void + */ + public function testExecuteInteractive() { + $this->Task->connection = 'test'; + $this->Task->path = '/my/path/'; + + $this->Task->expects($this->any())->method('in')->will($this->returnValue('y')); + $this->Task->Model->expects($this->any())->method('getName')->will($this->returnValue('Article')); + $this->Task->Model->expects($this->any())->method('getTable') + ->with('Article') + ->will($this->returnValue('articles')); + + $filename = '/my/path/ArticleFixture.php'; + $this->Task->expects($this->once())->method('createFile') + ->with($filename, $this->stringContains('class ArticleFixture')); + + $this->Task->execute(); + } + +/** + * Test that bake works + * + * @return void + */ + public function testBake() { + $this->Task->connection = 'test'; + $this->Task->path = '/my/path/'; + + $result = $this->Task->bake('Article'); + $this->assertContains('class ArticleFixture extends CakeTestFixture', $result); + $this->assertContains('public $fields', $result); + $this->assertContains('public $records', $result); + $this->assertNotContains('public $import', $result); + + $result = $this->Task->bake('Article', 'comments'); + $this->assertContains('class ArticleFixture extends CakeTestFixture', $result); + $this->assertContains('public $table = \'comments\';', $result); + $this->assertContains('public $fields = array(', $result); + + $result = $this->Task->bake('Article', 'comments', array('records' => true)); + $this->assertContains("public \$import = array('records' => true, 'connection' => 'test');", $result); + $this->assertNotContains('public $records', $result); + + $result = $this->Task->bake('Article', 'comments', array('schema' => 'Article')); + $this->assertContains("public \$import = array('model' => 'Article', 'connection' => 'test');", $result); + $this->assertNotContains('public $fields', $result); + + $result = $this->Task->bake('Article', 'comments', array('schema' => 'Article', 'records' => true)); + $this->assertContains("public \$import = array('model' => 'Article', 'records' => true, 'connection' => 'test');", $result); + $this->assertNotContains('public $fields', $result); + $this->assertNotContains('public $records', $result); + } + +/** + * test record generation with float and binary types + * + * @return void + */ + public function testRecordGenerationForBinaryAndFloat() { + $this->Task->connection = 'test'; + $this->Task->path = '/my/path/'; + + $result = $this->Task->bake('Article', 'datatypes'); + $this->assertContains("'float_field' => 1", $result); + $this->assertContains("'bool' => 1", $result); + + $result = $this->Task->bake('Article', 'binary_tests'); + $this->assertContains("'data' => 'Lorem ipsum dolor sit amet'", $result); + } + +/** + * Test that file generation includes headers and correct path for plugins. + * + * @return void + */ + public function testGenerateFixtureFile() { + $this->Task->connection = 'test'; + $this->Task->path = '/my/path/'; + $filename = '/my/path/ArticleFixture.php'; + + $this->Task->expects($this->at(0))->method('createFile') + ->with($filename, $this->stringContains('ArticleFixture')); + + $this->Task->expects($this->at(1))->method('createFile') + ->with($filename, $this->stringContains('Task->generateFixtureFile('Article', array()); + + $result = $this->Task->generateFixtureFile('Article', array()); + } + +/** + * test generating files into plugins. + * + * @return void + */ + public function testGeneratePluginFixtureFile() { + $this->Task->connection = 'test'; + $this->Task->path = '/my/path/'; + $this->Task->plugin = 'TestFixture'; + $filename = APP . 'Plugin' . DS . 'TestFixture' . DS . 'Test' . DS . 'Fixture' . DS . 'ArticleFixture.php'; + + //fake plugin path + CakePlugin::load('TestFixture', array('path' => APP . 'Plugin' . DS . 'TestFixture' . DS)); + $this->Task->expects($this->at(0))->method('createFile') + ->with($filename, $this->stringContains('class Article')); + + $result = $this->Task->generateFixtureFile('Article', array()); + CakePlugin::unload(); + } + +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/Task/ModelTaskTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/Task/ModelTaskTest.php new file mode 100644 index 0000000..2e3c5d9 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/Task/ModelTaskTest.php @@ -0,0 +1,1189 @@ +getMock('ConsoleOutput', array(), array(), '', false); + $in = $this->getMock('ConsoleInput', array(), array(), '', false); + + $this->Task = $this->getMock('ModelTask', + array('in', 'err', 'createFile', '_stop', '_checkUnitTest'), + array($out, $out, $in) + ); + $this->_setupOtherMocks(); + } + +/** + * Setup a mock that has out mocked. Normally this is not used as it makes $this->at() really tricky. + * + * @return void + */ + protected function _useMockedOut() { + $out = $this->getMock('ConsoleOutput', array(), array(), '', false); + $in = $this->getMock('ConsoleInput', array(), array(), '', false); + + $this->Task = $this->getMock('ModelTask', + array('in', 'out', 'err', 'hr', 'createFile', '_stop', '_checkUnitTest'), + array($out, $out, $in) + ); + $this->_setupOtherMocks(); + } + +/** + * sets up the rest of the dependencies for Model Task + * + * @return void + */ + protected function _setupOtherMocks() { + $out = $this->getMock('ConsoleOutput', array(), array(), '', false); + $in = $this->getMock('ConsoleInput', array(), array(), '', false); + + $this->Task->Fixture = $this->getMock('FixtureTask', array(), array($out, $out, $in)); + $this->Task->Test = $this->getMock('FixtureTask', array(), array($out, $out, $in)); + $this->Task->Template = new TemplateTask($out, $out, $in); + + $this->Task->name = 'Model'; + $this->Task->interactive = true; + } + +/** + * tearDown method + * + * @return void + */ + public function tearDown() { + parent::tearDown(); + unset($this->Task); + } + +/** + * Test that listAll scans the database connection and lists all the tables in it.s + * + * @return void + */ + public function testListAllArgument() { + $this->_useMockedOut(); + + $result = $this->Task->listAll('test'); + $this->assertContains('bake_articles', $result); + $this->assertContains('bake_articles_bake_tags', $result); + $this->assertContains('bake_tags', $result); + $this->assertContains('bake_comments', $result); + $this->assertContains('category_threads', $result); + } + +/** + * Test that listAll uses the connection property + * + * @return void + */ + public function testListAllConnection() { + $this->_useMockedOut(); + + $this->Task->connection = 'test'; + $result = $this->Task->listAll(); + $this->assertContains('bake_articles', $result); + $this->assertContains('bake_articles_bake_tags', $result); + $this->assertContains('bake_tags', $result); + $this->assertContains('bake_comments', $result); + $this->assertContains('category_threads', $result); + } + +/** + * Test that getName interacts with the user and returns the model name. + * + * @return void + */ + public function testGetNameQuit() { + $this->Task->expects($this->once())->method('in')->will($this->returnValue('q')); + $this->Task->expects($this->once())->method('_stop'); + $this->Task->getName('test'); + } + +/** + * test getName with a valid option. + * + * @return void + */ + public function testGetNameValidOption() { + $listing = $this->Task->listAll('test'); + $this->Task->expects($this->any())->method('in')->will($this->onConsecutiveCalls(1, 4)); + + $result = $this->Task->getName('test'); + $this->assertEquals(Inflector::classify($listing[0]), $result); + + $result = $this->Task->getName('test'); + $this->assertEquals(Inflector::classify($listing[3]), $result); + } + +/** + * test that an out of bounds option causes an error. + * + * @return void + */ + public function testGetNameWithOutOfBoundsOption() { + $this->Task->expects($this->any())->method('in')->will($this->onConsecutiveCalls(99, 1)); + $this->Task->expects($this->once())->method('err'); + + $result = $this->Task->getName('test'); + } + +/** + * Test table name interactions + * + * @return void + */ + public function testGetTableName() { + $this->Task->expects($this->at(0))->method('in')->will($this->returnValue('y')); + $result = $this->Task->getTable('BakeArticle', 'test'); + $expected = 'bake_articles'; + $this->assertEquals($expected, $result); + } + +/** + * test gettting a custom table name. + * + * @return void + */ + public function testGetTableNameCustom() { + $this->Task->expects($this->any())->method('in')->will($this->onConsecutiveCalls('n', 'my_table')); + $result = $this->Task->getTable('BakeArticle', 'test'); + $expected = 'my_table'; + $this->assertEquals($expected, $result); + } + +/** + * test getTable with non-conventional tablenames + * + * @return void + */ + public function testGetTableOddTableInteractive() { + $out = $this->getMock('ConsoleOutput', array(), array(), '', false); + $in = $this->getMock('ConsoleInput', array(), array(), '', false); + $this->Task = $this->getMock('ModelTask', + array('in', 'err', '_stop', '_checkUnitTest', 'getAllTables'), + array($out, $out, $in) + ); + $this->_setupOtherMocks(); + + $this->Task->connection = 'test'; + $this->Task->path = '/my/path/'; + $this->Task->interactive = true; + + $this->Task->expects($this->once())->method('getAllTables')->will($this->returnValue(array('articles', 'bake_odd'))); + $this->Task->expects($this->any())->method('in') + ->will($this->onConsecutiveCalls( + 2 // bake_odd + )); + + $result = $this->Task->getName(); + $expected = 'BakeOdd'; + $this->assertEquals($expected, $result); + + $result = $this->Task->getTable($result); + $expected = 'bake_odd'; + $this->assertEquals($expected, $result); + } + +/** + * test getTable with non-conventional tablenames + * + * @return void + */ + public function testGetTableOddTable() { + $out = $this->getMock('ConsoleOutput', array(), array(), '', false); + $in = $this->getMock('ConsoleInput', array(), array(), '', false); + $this->Task = $this->getMock('ModelTask', + array('in', 'err', '_stop', '_checkUnitTest', 'getAllTables'), + array($out, $out, $in) + ); + $this->_setupOtherMocks(); + + $this->Task->connection = 'test'; + $this->Task->path = '/my/path/'; + $this->Task->interactive = false; + $this->Task->args = array('BakeOdd'); + + $this->Task->expects($this->once())->method('getAllTables')->will($this->returnValue(array('articles', 'bake_odd'))); + + $this->Task->listAll(); + + $result = $this->Task->getTable('BakeOdd'); + $expected = 'bake_odd'; + $this->assertEquals($expected, $result); + } + +/** + * test that initializing the validations works. + * + * @return void + */ + public function testInitValidations() { + $result = $this->Task->initValidations(); + $this->assertTrue(in_array('notempty', $result)); + } + +/** + * test that individual field validation works, with interactive = false + * tests the guessing features of validation + * + * @return void + */ + public function testFieldValidationGuessing() { + $this->Task->interactive = false; + $this->Task->initValidations(); + + $result = $this->Task->fieldValidation('text', array('type' => 'string', 'length' => 10, 'null' => false)); + $expected = array('notempty' => 'notempty'); + $this->assertEquals($expected, $result); + + $result = $this->Task->fieldValidation('text', array('type' => 'date', 'length' => 10, 'null' => false)); + $expected = array('date' => 'date'); + $this->assertEquals($expected, $result); + + $result = $this->Task->fieldValidation('text', array('type' => 'time', 'length' => 10, 'null' => false)); + $expected = array('time' => 'time'); + $this->assertEquals($expected, $result); + + $result = $this->Task->fieldValidation('email', array('type' => 'string', 'length' => 10, 'null' => false)); + $expected = array('email' => 'email'); + $this->assertEquals($expected, $result); + + $result = $this->Task->fieldValidation('test', array('type' => 'integer', 'length' => 10, 'null' => false)); + $expected = array('numeric' => 'numeric'); + $this->assertEquals($expected, $result); + + $result = $this->Task->fieldValidation('test', array('type' => 'boolean', 'length' => 10, 'null' => false)); + $expected = array('boolean' => 'boolean'); + $this->assertEquals($expected, $result); + } + +/** + * test that interactive field validation works and returns multiple validators. + * + * @return void + */ + public function testInteractiveFieldValidation() { + $this->Task->initValidations(); + $this->Task->interactive = true; + $this->Task->expects($this->any())->method('in') + ->will($this->onConsecutiveCalls('23', 'y', '17', 'n')); + + $result = $this->Task->fieldValidation('text', array('type' => 'string', 'length' => 10, 'null' => false)); + $expected = array('notempty' => 'notempty', 'maxlength' => 'maxlength'); + $this->assertEquals($expected, $result); + } + +/** + * test that a bogus response doesn't cause errors to bubble up. + * + * @return void + */ + public function testInteractiveFieldValidationWithBogusResponse() { + $this->_useMockedOut(); + $this->Task->initValidations(); + $this->Task->interactive = true; + + $this->Task->expects($this->any())->method('in') + ->will($this->onConsecutiveCalls('999999', '23', 'n')); + + $this->Task->expects($this->at(10))->method('out') + ->with($this->stringContains('make a valid')); + + $result = $this->Task->fieldValidation('text', array('type' => 'string', 'length' => 10, 'null' => false)); + $expected = array('notempty' => 'notempty'); + $this->assertEquals($expected, $result); + } + +/** + * test that a regular expression can be used for validation. + * + * @return void + */ + public function testInteractiveFieldValidationWithRegexp() { + $this->Task->initValidations(); + $this->Task->interactive = true; + $this->Task->expects($this->any())->method('in') + ->will($this->onConsecutiveCalls('/^[a-z]{0,9}$/', 'n')); + + $result = $this->Task->fieldValidation('text', array('type' => 'string', 'length' => 10, 'null' => false)); + $expected = array('a_z_0_9' => '/^[a-z]{0,9}$/'); + $this->assertEquals($expected, $result); + } + +/** + * test the validation Generation routine + * + * @return void + */ + public function testNonInteractiveDoValidation() { + $Model = $this->getMock('Model'); + $Model->primaryKey = 'id'; + $Model->expects($this->any())->method('schema')->will($this->returnValue(array( + 'id' => array( + 'type' => 'integer', + 'length' => 11, + 'null' => false, + 'key' => 'primary', + ), + 'name' => array( + 'type' => 'string', + 'length' => 20, + 'null' => false, + ), + 'email' => array( + 'type' => 'string', + 'length' => 255, + 'null' => false, + ), + 'some_date' => array( + 'type' => 'date', + 'length' => '', + 'null' => false, + ), + 'some_time' => array( + 'type' => 'time', + 'length' => '', + 'null' => false, + ), + 'created' => array( + 'type' => 'datetime', + 'length' => '', + 'null' => false, + ) + ))); + $this->Task->interactive = false; + + $result = $this->Task->doValidation($Model); + $expected = array( + 'name' => array( + 'notempty' => 'notempty' + ), + 'email' => array( + 'email' => 'email', + ), + 'some_date' => array( + 'date' => 'date' + ), + 'some_time' => array( + 'time' => 'time' + ), + ); + $this->assertEquals($expected, $result); + } + +/** + * test that finding primary key works + * + * @return void + */ + public function testFindPrimaryKey() { + $fields = array( + 'one' => array(), + 'two' => array(), + 'key' => array('key' => 'primary') + ); + $anything = new PHPUnit_Framework_Constraint_IsAnything(); + $this->Task->expects($this->once())->method('in') + ->with($anything, null, 'key') + ->will($this->returnValue('my_field')); + + $result = $this->Task->findPrimaryKey($fields); + $expected = 'my_field'; + $this->assertEquals($expected, $result); + } + +/** + * test finding Display field + * + * @return void + */ + public function testFindDisplayFieldNone() { + $fields = array( + 'id' => array(), 'tagname' => array(), 'body' => array(), + 'created' => array(), 'modified' => array() + ); + $this->Task->expects($this->at(0))->method('in')->will($this->returnValue('n')); + $result = $this->Task->findDisplayField($fields); + $this->assertFalse($result); + } + +/** + * Test finding a displayname from user input + * + * @return void + */ + public function testFindDisplayName() { + $fields = array( + 'id' => array(), 'tagname' => array(), 'body' => array(), + 'created' => array(), 'modified' => array() + ); + $this->Task->expects($this->any())->method('in') + ->will($this->onConsecutiveCalls('y', 2)); + + $result = $this->Task->findDisplayField($fields); + $this->assertEquals('tagname', $result); + } + +/** + * test that belongsTo generation works. + * + * @return void + */ + public function testBelongsToGeneration() { + $model = new Model(array('ds' => 'test', 'name' => 'BakeComment')); + $result = $this->Task->findBelongsTo($model, array()); + $expected = array( + 'belongsTo' => array( + array( + 'alias' => 'BakeArticle', + 'className' => 'BakeArticle', + 'foreignKey' => 'bake_article_id', + ), + array( + 'alias' => 'BakeUser', + 'className' => 'BakeUser', + 'foreignKey' => 'bake_user_id', + ), + ) + ); + $this->assertEquals($expected, $result); + + $model = new Model(array('ds' => 'test', 'name' => 'CategoryThread')); + $result = $this->Task->findBelongsTo($model, array()); + $expected = array( + 'belongsTo' => array( + array( + 'alias' => 'ParentCategoryThread', + 'className' => 'CategoryThread', + 'foreignKey' => 'parent_id', + ), + ) + ); + $this->assertEquals($expected, $result); + } + +/** + * test that hasOne and/or hasMany relations are generated properly. + * + * @return void + */ + public function testHasManyHasOneGeneration() { + $model = new Model(array('ds' => 'test', 'name' => 'BakeArticle')); + $this->Task->connection = 'test'; + $this->Task->listAll(); + $result = $this->Task->findHasOneAndMany($model, array()); + $expected = array( + 'hasMany' => array( + array( + 'alias' => 'BakeComment', + 'className' => 'BakeComment', + 'foreignKey' => 'bake_article_id', + ), + ), + 'hasOne' => array( + array( + 'alias' => 'BakeComment', + 'className' => 'BakeComment', + 'foreignKey' => 'bake_article_id', + ), + ), + ); + $this->assertEquals($expected, $result); + + $model = new Model(array('ds' => 'test', 'name' => 'CategoryThread')); + $result = $this->Task->findHasOneAndMany($model, array()); + $expected = array( + 'hasOne' => array( + array( + 'alias' => 'ChildCategoryThread', + 'className' => 'CategoryThread', + 'foreignKey' => 'parent_id', + ), + ), + 'hasMany' => array( + array( + 'alias' => 'ChildCategoryThread', + 'className' => 'CategoryThread', + 'foreignKey' => 'parent_id', + ), + ) + ); + $this->assertEquals($expected, $result); + } + +/** + * Test that HABTM generation works + * + * @return void + */ + public function testHasAndBelongsToManyGeneration() { + $model = new Model(array('ds' => 'test', 'name' => 'BakeArticle')); + $this->Task->connection = 'test'; + $this->Task->listAll(); + $result = $this->Task->findHasAndBelongsToMany($model, array()); + $expected = array( + 'hasAndBelongsToMany' => array( + array( + 'alias' => 'BakeTag', + 'className' => 'BakeTag', + 'foreignKey' => 'bake_article_id', + 'joinTable' => 'bake_articles_bake_tags', + 'associationForeignKey' => 'bake_tag_id', + ), + ), + ); + $this->assertEquals($expected, $result); + } + +/** + * test non interactive doAssociations + * + * @return void + */ + public function testDoAssociationsNonInteractive() { + $this->Task->connection = 'test'; + $this->Task->interactive = false; + $model = new Model(array('ds' => 'test', 'name' => 'BakeArticle')); + $result = $this->Task->doAssociations($model); + $expected = array( + 'belongsTo' => array( + array( + 'alias' => 'BakeUser', + 'className' => 'BakeUser', + 'foreignKey' => 'bake_user_id', + ), + ), + 'hasMany' => array( + array( + 'alias' => 'BakeComment', + 'className' => 'BakeComment', + 'foreignKey' => 'bake_article_id', + ), + ), + 'hasAndBelongsToMany' => array( + array( + 'alias' => 'BakeTag', + 'className' => 'BakeTag', + 'foreignKey' => 'bake_article_id', + 'joinTable' => 'bake_articles_bake_tags', + 'associationForeignKey' => 'bake_tag_id', + ), + ), + ); + $this->assertEquals($expected, $result); + } + +/** + * Ensure that the fixture object is correctly called. + * + * @return void + */ + public function testBakeFixture() { + $this->Task->plugin = 'TestPlugin'; + $this->Task->interactive = true; + $this->Task->Fixture->expects($this->at(0))->method('bake')->with('BakeArticle', 'bake_articles'); + $this->Task->bakeFixture('BakeArticle', 'bake_articles'); + + $this->assertEquals($this->Task->plugin, $this->Task->Fixture->plugin); + $this->assertEquals($this->Task->connection, $this->Task->Fixture->connection); + $this->assertEquals($this->Task->interactive, $this->Task->Fixture->interactive); + } + +/** + * Ensure that the test object is correctly called. + * + * @return void + */ + public function testBakeTest() { + $this->Task->plugin = 'TestPlugin'; + $this->Task->interactive = true; + $this->Task->Test->expects($this->at(0))->method('bake')->with('Model', 'BakeArticle'); + $this->Task->bakeTest('BakeArticle'); + + $this->assertEquals($this->Task->plugin, $this->Task->Test->plugin); + $this->assertEquals($this->Task->connection, $this->Task->Test->connection); + $this->assertEquals($this->Task->interactive, $this->Task->Test->interactive); + } + +/** + * test confirming of associations, and that when an association is hasMany + * a question for the hasOne is also not asked. + * + * @return void + */ + public function testConfirmAssociations() { + $associations = array( + 'hasOne' => array( + array( + 'alias' => 'ChildCategoryThread', + 'className' => 'CategoryThread', + 'foreignKey' => 'parent_id', + ), + ), + 'hasMany' => array( + array( + 'alias' => 'ChildCategoryThread', + 'className' => 'CategoryThread', + 'foreignKey' => 'parent_id', + ), + ), + 'belongsTo' => array( + array( + 'alias' => 'User', + 'className' => 'User', + 'foreignKey' => 'user_id', + ), + ) + ); + $model = new Model(array('ds' => 'test', 'name' => 'CategoryThread')); + + $this->Task->expects($this->any())->method('in') + ->will($this->onConsecutiveCalls('n', 'y', 'n', 'n', 'n')); + + $result = $this->Task->confirmAssociations($model, $associations); + $this->assertTrue(empty($result['hasOne'])); + + $result = $this->Task->confirmAssociations($model, $associations); + $this->assertTrue(empty($result['hasMany'])); + $this->assertTrue(empty($result['hasOne'])); + } + +/** + * test that inOptions generates questions and only accepts a valid answer + * + * @return void + */ + public function testInOptions() { + $this->_useMockedOut(); + + $options = array('one', 'two', 'three'); + $this->Task->expects($this->at(0))->method('out')->with('1. one'); + $this->Task->expects($this->at(1))->method('out')->with('2. two'); + $this->Task->expects($this->at(2))->method('out')->with('3. three'); + $this->Task->expects($this->at(3))->method('in')->will($this->returnValue(10)); + + $this->Task->expects($this->at(4))->method('out')->with('1. one'); + $this->Task->expects($this->at(5))->method('out')->with('2. two'); + $this->Task->expects($this->at(6))->method('out')->with('3. three'); + $this->Task->expects($this->at(7))->method('in')->will($this->returnValue(2)); + $result = $this->Task->inOptions($options, 'Pick a number'); + $this->assertEquals(1, $result); + } + +/** + * test baking validation + * + * @return void + */ + public function testBakeValidation() { + $validate = array( + 'name' => array( + 'notempty' => 'notempty' + ), + 'email' => array( + 'email' => 'email', + ), + 'some_date' => array( + 'date' => 'date' + ), + 'some_time' => array( + 'time' => 'time' + ) + ); + $result = $this->Task->bake('BakeArticle', compact('validate')); + $this->assertRegExp('/class BakeArticle extends AppModel \{/', $result); + $this->assertRegExp('/\$validate \= array\(/', $result); + $expected = <<< STRINGEND +array( + 'notempty' => array( + 'rule' => array('notempty'), + //'message' => 'Your custom message here', + //'allowEmpty' => false, + //'required' => false, + //'last' => false, // Stop validation after this rule + //'on' => 'create', // Limit validation to 'create' or 'update' operations + ), +STRINGEND; + $this->assertRegExp('/' . preg_quote(str_replace("\r\n", "\n", $expected), '/') . '/', $result); + } + +/** + * test baking relations + * + * @return void + */ + public function testBakeRelations() { + $associations = array( + 'belongsTo' => array( + array( + 'alias' => 'SomethingElse', + 'className' => 'SomethingElse', + 'foreignKey' => 'something_else_id', + ), + array( + 'alias' => 'BakeUser', + 'className' => 'BakeUser', + 'foreignKey' => 'bake_user_id', + ), + ), + 'hasOne' => array( + array( + 'alias' => 'OtherModel', + 'className' => 'OtherModel', + 'foreignKey' => 'other_model_id', + ), + ), + 'hasMany' => array( + array( + 'alias' => 'BakeComment', + 'className' => 'BakeComment', + 'foreignKey' => 'parent_id', + ), + ), + 'hasAndBelongsToMany' => array( + array( + 'alias' => 'BakeTag', + 'className' => 'BakeTag', + 'foreignKey' => 'bake_article_id', + 'joinTable' => 'bake_articles_bake_tags', + 'associationForeignKey' => 'bake_tag_id', + ), + ) + ); + $result = $this->Task->bake('BakeArticle', compact('associations')); + $this->assertContains(' * @property BakeUser $BakeUser', $result); + $this->assertContains(' * @property OtherModel $OtherModel', $result); + $this->assertContains(' * @property BakeComment $BakeComment', $result); + $this->assertContains(' * @property BakeTag $BakeTag', $result); + $this->assertRegExp('/\$hasAndBelongsToMany \= array\(/', $result); + $this->assertRegExp('/\$hasMany \= array\(/', $result); + $this->assertRegExp('/\$belongsTo \= array\(/', $result); + $this->assertRegExp('/\$hasOne \= array\(/', $result); + $this->assertRegExp('/BakeTag/', $result); + $this->assertRegExp('/OtherModel/', $result); + $this->assertRegExp('/SomethingElse/', $result); + $this->assertRegExp('/BakeComment/', $result); + } + +/** + * test bake() with a -plugin param + * + * @return void + */ + public function testBakeWithPlugin() { + $this->Task->plugin = 'ControllerTest'; + + //fake plugin path + CakePlugin::load('ControllerTest', array('path' => APP . 'Plugin' . DS . 'ControllerTest' . DS)); + $path = APP . 'Plugin' . DS . 'ControllerTest' . DS . 'Model' . DS . 'BakeArticle.php'; + $this->Task->expects($this->once())->method('createFile') + ->with($path, $this->stringContains('BakeArticle extends ControllerTestAppModel')); + + $result = $this->Task->bake('BakeArticle', array(), array()); + $this->assertContains("App::uses('ControllerTestAppModel', 'ControllerTest.Model');", $result); + + $this->assertEquals(count(ClassRegistry::keys()), 0); + $this->assertEquals(count(ClassRegistry::mapKeys()), 0); + } + +/** + * test that execute passes runs bake depending with named model. + * + * @return void + */ + public function testExecuteWithNamedModel() { + $this->Task->connection = 'test'; + $this->Task->path = '/my/path/'; + $this->Task->args = array('BakeArticle'); + $filename = '/my/path/BakeArticle.php'; + + $this->Task->expects($this->once())->method('_checkUnitTest')->will($this->returnValue(1)); + $this->Task->expects($this->once())->method('createFile') + ->with($filename, $this->stringContains('class BakeArticle extends AppModel')); + + $this->Task->execute(); + + $this->assertEquals(count(ClassRegistry::keys()), 0); + $this->assertEquals(count(ClassRegistry::mapKeys()), 0); + } + +/** + * data provider for testExecuteWithNamedModelVariations + * + * @return void + */ + public static function nameVariations() { + return array( + array('BakeArticles'), array('BakeArticle'), array('bake_article'), array('bake_articles') + ); + } + +/** + * test that execute passes with different inflections of the same name. + * + * @dataProvider nameVariations + * @return void + */ + public function testExecuteWithNamedModelVariations($name) { + $this->Task->connection = 'test'; + $this->Task->path = '/my/path/'; + $this->Task->expects($this->once())->method('_checkUnitTest')->will($this->returnValue(1)); + + $this->Task->args = array($name); + $filename = '/my/path/BakeArticle.php'; + + $this->Task->expects($this->at(0))->method('createFile') + ->with($filename, $this->stringContains('class BakeArticle extends AppModel')); + $this->Task->execute(); + } + +/** + * test that execute with a model name picks up hasMany associations. + * + * @return void + */ + public function testExecuteWithNamedModelHasManyCreated() { + $this->Task->connection = 'test'; + $this->Task->path = '/my/path/'; + $this->Task->args = array('BakeArticle'); + $filename = '/my/path/BakeArticle.php'; + + $this->Task->expects($this->once())->method('_checkUnitTest')->will($this->returnValue(1)); + $this->Task->expects($this->at(0))->method('createFile') + ->with($filename, $this->stringContains("'BakeComment' => array(")); + + $this->Task->execute(); + } + +/** + * test that execute runs all() when args[0] = all + * + * @return void + */ + public function testExecuteIntoAll() { + $count = count($this->Task->listAll('test')); + if ($count != count($this->fixtures)) { + $this->markTestSkipped('Additional tables detected.'); + } + + $this->Task->connection = 'test'; + $this->Task->path = '/my/path/'; + $this->Task->args = array('all'); + $this->Task->expects($this->once())->method('_checkUnitTest')->will($this->returnValue(true)); + + $this->Task->Fixture->expects($this->exactly(5))->method('bake'); + $this->Task->Test->expects($this->exactly(5))->method('bake'); + + $filename = '/my/path/BakeArticle.php'; + $this->Task->expects($this->at(1))->method('createFile') + ->with($filename, $this->stringContains('class BakeArticle')); + + $filename = '/my/path/BakeArticlesBakeTag.php'; + $this->Task->expects($this->at(2))->method('createFile') + ->with($filename, $this->stringContains('class BakeArticlesBakeTag')); + + $filename = '/my/path/BakeComment.php'; + $this->Task->expects($this->at(3))->method('createFile') + ->with($filename, $this->stringContains('class BakeComment')); + + $filename = '/my/path/BakeComment.php'; + $this->Task->expects($this->at(3))->method('createFile') + ->with($filename, $this->stringContains('public $primaryKey = \'otherid\';')); + + $filename = '/my/path/BakeTag.php'; + $this->Task->expects($this->at(4))->method('createFile') + ->with($filename, $this->stringContains('class BakeTag')); + + $filename = '/my/path/BakeTag.php'; + $this->Task->expects($this->at(4))->method('createFile') + ->with($filename, $this->logicalNot($this->stringContains('public $primaryKey'))); + + $filename = '/my/path/CategoryThread.php'; + $this->Task->expects($this->at(5))->method('createFile') + ->with($filename, $this->stringContains('class CategoryThread')); + + $this->Task->execute(); + + $this->assertEquals(count(ClassRegistry::keys()), 0); + $this->assertEquals(count(ClassRegistry::mapKeys()), 0); + } + +/** + * test that odd tablenames arent inflected back from modelname + * + * @return void + */ + public function testExecuteIntoAllOddTables() { + $out = $this->getMock('ConsoleOutput', array(), array(), '', false); + $in = $this->getMock('ConsoleInput', array(), array(), '', false); + $this->Task = $this->getMock('ModelTask', + array('in', 'err', '_stop', '_checkUnitTest', 'getAllTables', '_getModelObject', 'bake', 'bakeFixture'), + array($out, $out, $in) + ); + $this->_setupOtherMocks(); + + $this->Task->connection = 'test'; + $this->Task->path = '/my/path/'; + $this->Task->args = array('all'); + $this->Task->expects($this->once())->method('_checkUnitTest')->will($this->returnValue(true)); + $this->Task->expects($this->once())->method('getAllTables')->will($this->returnValue(array('bake_odd'))); + $object = new Model(array('name' => 'BakeOdd', 'table' => 'bake_odd', 'ds' => 'test')); + $this->Task->expects($this->once())->method('_getModelObject')->with('BakeOdd', 'bake_odd')->will($this->returnValue($object)); + $this->Task->expects($this->at(3))->method('bake')->with($object, false)->will($this->returnValue(true)); + $this->Task->expects($this->once())->method('bakeFixture')->with('BakeOdd', 'bake_odd'); + + $this->Task->execute(); + + $out = $this->getMock('ConsoleOutput', array(), array(), '', false); + $in = $this->getMock('ConsoleInput', array(), array(), '', false); + $this->Task = $this->getMock('ModelTask', + array('in', 'err', '_stop', '_checkUnitTest', 'getAllTables', '_getModelObject', 'doAssociations', 'doValidation', 'createFile'), + array($out, $out, $in) + ); + $this->_setupOtherMocks(); + + $this->Task->connection = 'test'; + $this->Task->path = '/my/path/'; + $this->Task->args = array('all'); + $this->Task->expects($this->once())->method('_checkUnitTest')->will($this->returnValue(true)); + $this->Task->expects($this->once())->method('getAllTables')->will($this->returnValue(array('bake_odd'))); + $object = new Model(array('name' => 'BakeOdd', 'table' => 'bake_odd', 'ds' => 'test')); + $this->Task->expects($this->once())->method('_getModelObject')->will($this->returnValue($object)); + $this->Task->expects($this->once())->method('doAssociations')->will($this->returnValue(array())); + $this->Task->expects($this->once())->method('doValidation')->will($this->returnValue(array())); + + $filename = '/my/path/BakeOdd.php'; + $this->Task->expects($this->once())->method('createFile') + ->with($filename, $this->stringContains('class BakeOdd')); + + $filename = '/my/path/BakeOdd.php'; + $this->Task->expects($this->once())->method('createFile') + ->with($filename, $this->stringContains('public $useTable = \'bake_odd\'')); + + $this->Task->execute(); + } + +/** + * test that odd tablenames arent inflected back from modelname + * + * @return void + */ + public function testExecuteIntoBakeOddTables() { + $out = $this->getMock('ConsoleOutput', array(), array(), '', false); + $in = $this->getMock('ConsoleInput', array(), array(), '', false); + $this->Task = $this->getMock('ModelTask', + array('in', 'err', '_stop', '_checkUnitTest', 'getAllTables', '_getModelObject', 'bake', 'bakeFixture'), + array($out, $out, $in) + ); + $this->_setupOtherMocks(); + + $this->Task->connection = 'test'; + $this->Task->path = '/my/path/'; + $this->Task->args = array('BakeOdd'); + $this->Task->expects($this->once())->method('_checkUnitTest')->will($this->returnValue(true)); + $this->Task->expects($this->once())->method('getAllTables')->will($this->returnValue(array('articles', 'bake_odd'))); + $object = new Model(array('name' => 'BakeOdd', 'table' => 'bake_odd', 'ds' => 'test')); + $this->Task->expects($this->once())->method('_getModelObject')->with('BakeOdd', 'bake_odd')->will($this->returnValue($object)); + $this->Task->expects($this->once())->method('bake')->with($object, false)->will($this->returnValue(true)); + $this->Task->expects($this->once())->method('bakeFixture')->with('BakeOdd', 'bake_odd'); + + $this->Task->execute(); + + $out = $this->getMock('ConsoleOutput', array(), array(), '', false); + $in = $this->getMock('ConsoleInput', array(), array(), '', false); + $this->Task = $this->getMock('ModelTask', + array('in', 'err', '_stop', '_checkUnitTest', 'getAllTables', '_getModelObject', 'doAssociations', 'doValidation', 'createFile'), + array($out, $out, $in) + ); + $this->_setupOtherMocks(); + + $this->Task->connection = 'test'; + $this->Task->path = '/my/path/'; + $this->Task->args = array('BakeOdd'); + $this->Task->expects($this->once())->method('_checkUnitTest')->will($this->returnValue(true)); + $this->Task->expects($this->once())->method('getAllTables')->will($this->returnValue(array('articles', 'bake_odd'))); + $object = new Model(array('name' => 'BakeOdd', 'table' => 'bake_odd', 'ds' => 'test')); + $this->Task->expects($this->once())->method('_getModelObject')->will($this->returnValue($object)); + $this->Task->expects($this->once())->method('doAssociations')->will($this->returnValue(array())); + $this->Task->expects($this->once())->method('doValidation')->will($this->returnValue(array())); + + $filename = '/my/path/BakeOdd.php'; + $this->Task->expects($this->once())->method('createFile') + ->with($filename, $this->stringContains('class BakeOdd')); + + $filename = '/my/path/BakeOdd.php'; + $this->Task->expects($this->once())->method('createFile') + ->with($filename, $this->stringContains('public $useTable = \'bake_odd\'')); + + $this->Task->execute(); + } + +/** + * test that skipTables changes how all() works. + * + * @return void + */ + public function testSkipTablesAndAll() { + $count = count($this->Task->listAll('test')); + if ($count != count($this->fixtures)) { + $this->markTestSkipped('Additional tables detected.'); + } + + $this->Task->connection = 'test'; + $this->Task->path = '/my/path/'; + $this->Task->args = array('all'); + $this->Task->expects($this->once())->method('_checkUnitTest')->will($this->returnValue(true)); + $this->Task->skipTables = array('bake_tags'); + + $this->Task->Fixture->expects($this->exactly(4))->method('bake'); + $this->Task->Test->expects($this->exactly(4))->method('bake'); + + $filename = '/my/path/BakeArticle.php'; + $this->Task->expects($this->at(1))->method('createFile') + ->with($filename, $this->stringContains('class BakeArticle')); + + $filename = '/my/path/BakeArticlesBakeTag.php'; + $this->Task->expects($this->at(2))->method('createFile') + ->with($filename, $this->stringContains('class BakeArticlesBakeTag')); + + $filename = '/my/path/BakeComment.php'; + $this->Task->expects($this->at(3))->method('createFile') + ->with($filename, $this->stringContains('class BakeComment')); + + $filename = '/my/path/CategoryThread.php'; + $this->Task->expects($this->at(4))->method('createFile') + ->with($filename, $this->stringContains('class CategoryThread')); + + $this->Task->execute(); + } + +/** + * test the interactive side of bake. + * + * @return void + */ + public function testExecuteIntoInteractive() { + $tables = $this->Task->listAll('test'); + $article = array_search('bake_articles', $tables) + 1; + + $this->Task->connection = 'test'; + $this->Task->path = '/my/path/'; + $this->Task->interactive = true; + + $this->Task->expects($this->any())->method('in') + ->will($this->onConsecutiveCalls( + $article, // article + 'n', // no validation + 'y', // associations + 'y', // comment relation + 'y', // user relation + 'y', // tag relation + 'n', // additional assocs + 'y' // looks good? + )); + $this->Task->expects($this->once())->method('_checkUnitTest')->will($this->returnValue(true)); + + $this->Task->Test->expects($this->once())->method('bake'); + $this->Task->Fixture->expects($this->once())->method('bake'); + + $filename = '/my/path/BakeArticle.php'; + + $this->Task->expects($this->once())->method('createFile') + ->with($filename, $this->stringContains('class BakeArticle')); + + $this->Task->execute(); + + $this->assertEquals(count(ClassRegistry::keys()), 0); + $this->assertEquals(count(ClassRegistry::mapKeys()), 0); + } + +/** + * test using bake interactively with a table that does not exist. + * + * @return void + */ + public function testExecuteWithNonExistantTableName() { + $this->Task->connection = 'test'; + $this->Task->path = '/my/path/'; + + $this->Task->expects($this->any())->method('in') + ->will($this->onConsecutiveCalls( + 'Foobar', // Or type in the name of the model + 'y', // Do you want to use this table + 'n' // Doesn't exist, continue anyway? + )); + + $this->Task->execute(); + } + +/** + * test using bake interactively with a table that does not exist. + * + * @return void + */ + public function testForcedExecuteWithNonExistantTableName() { + $this->Task->connection = 'test'; + $this->Task->path = '/my/path/'; + + $this->Task->expects($this->any())->method('in') + ->will($this->onConsecutiveCalls( + 'Foobar', // Or type in the name of the model + 'y', // Do you want to use this table + 'y', // Doesn't exist, continue anyway? + 'id', // Primary key + 'y' // Looks good? + )); + + $this->Task->execute(); + } + +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/Task/PluginTaskTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/Task/PluginTaskTest.php new file mode 100644 index 0000000..28f06cc --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/Task/PluginTaskTest.php @@ -0,0 +1,207 @@ +out = $this->getMock('ConsoleOutput', array(), array(), '', false); + $this->in = $this->getMock('ConsoleInput', array(), array(), '', false); + + $this->Task = $this->getMock('PluginTask', + array('in', 'err', 'createFile', '_stop', 'clear'), + array($this->out, $this->out, $this->in) + ); + $this->Task->path = TMP . 'tests' . DS; + $this->Task->bootstrap = TMP . 'tests' . DS . 'bootstrap.php'; + touch($this->Task->bootstrap); + + $this->_paths = $paths = App::path('plugins'); + foreach ($paths as $i => $p) { + if (!is_dir($p)) { + array_splice($paths, $i, 1); + } + } + $this->_testPath = array_push($paths, TMP . 'tests' . DS); + App::build(array('plugins' => $paths)); + } + +/** + * tearDown() + * + * @return void + */ + public function tearDown() { + if (file_exists($this->Task->bootstrap)) { + unlink($this->Task->bootstrap); + } + parent::tearDown(); + } + +/** + * test bake() + * + * @return void + */ + public function testBakeFoldersAndFiles() { + $this->Task->expects($this->at(0))->method('in')->will($this->returnValue($this->_testPath)); + $this->Task->expects($this->at(1))->method('in')->will($this->returnValue('y')); + + $path = $this->Task->path . 'BakeTestPlugin'; + + $file = $path . DS . 'Controller' . DS . 'BakeTestPluginAppController.php'; + $this->Task->expects($this->at(2))->method('createFile') + ->with($file, new PHPUnit_Framework_Constraint_IsAnything()); + + $file = $path . DS . 'Model' . DS . 'BakeTestPluginAppModel.php'; + $this->Task->expects($this->at(3))->method('createFile') + ->with($file, new PHPUnit_Framework_Constraint_IsAnything()); + + $this->Task->bake('BakeTestPlugin'); + + $path = $this->Task->path . 'BakeTestPlugin'; + $this->assertTrue(is_dir($path), 'No plugin dir %s'); + + $directories = array( + 'Config' . DS . 'Schema', + 'Model' . DS . 'Behavior', + 'Model' . DS . 'Datasource', + 'Console' . DS . 'Command' . DS . 'Task', + 'Controller' . DS . 'Component', + 'Lib', + 'View' . DS . 'Helper', + 'Test' . DS . 'Case' . DS . 'Controller' . DS . 'Component', + 'Test' . DS . 'Case' . DS . 'View' . DS . 'Helper', + 'Test' . DS . 'Case' . DS . 'Model' . DS . 'Behavior', + 'Test' . DS . 'Fixture', + 'Vendor', + 'webroot' + ); + foreach ($directories as $dir) { + $this->assertTrue(is_dir($path . DS . $dir), 'Missing directory for ' . $dir); + } + + $Folder = new Folder($this->Task->path . 'BakeTestPlugin'); + $Folder->delete(); + } + +/** + * test execute with no args, flowing into interactive, + * + * @return void + */ + public function testExecuteWithNoArgs() { + $this->Task->expects($this->at(0))->method('in')->will($this->returnValue('TestPlugin')); + $this->Task->expects($this->at(1))->method('in')->will($this->returnValue($this->_testPath)); + $this->Task->expects($this->at(2))->method('in')->will($this->returnValue('y')); + + $path = $this->Task->path . 'TestPlugin'; + $file = $path . DS . 'Controller' . DS . 'TestPluginAppController.php'; + + $this->Task->expects($this->at(3))->method('createFile') + ->with($file, new PHPUnit_Framework_Constraint_IsAnything()); + + $file = $path . DS . 'Model' . DS . 'TestPluginAppModel.php'; + $this->Task->expects($this->at(4))->method('createFile') + ->with($file, new PHPUnit_Framework_Constraint_IsAnything()); + + $this->Task->args = array(); + $this->Task->execute(); + + $Folder = new Folder($path); + $Folder->delete(); + } + +/** + * Test Execute + * + * @return void + */ + public function testExecuteWithOneArg() { + $this->Task->expects($this->at(0))->method('in') + ->will($this->returnValue($this->_testPath)); + $this->Task->expects($this->at(1))->method('in') + ->will($this->returnValue('y')); + + $path = $this->Task->path . 'BakeTestPlugin'; + $file = $path . DS . 'Controller' . DS . 'BakeTestPluginAppController.php'; + $this->Task->expects($this->at(2))->method('createFile') + ->with($file, new PHPUnit_Framework_Constraint_IsAnything()); + + $path = $this->Task->path . 'BakeTestPlugin'; + $file = $path . DS . 'Model' . DS . 'BakeTestPluginAppModel.php'; + $this->Task->expects($this->at(3))->method('createFile') + ->with($file, new PHPUnit_Framework_Constraint_IsAnything()); + + $this->Task->args = array('BakeTestPlugin'); + + $this->Task->execute(); + + $Folder = new Folder($this->Task->path . 'BakeTestPlugin'); + $Folder->delete(); + } + +/** + * Test that findPath ignores paths that don't exist. + * + * @return void + */ + public function testFindPathNonExistant() { + $paths = App::path('plugins'); + $last = count($paths); + $paths[] = '/fake/path'; + + $this->Task = $this->getMock('PluginTask', + array('in', 'out', 'err', 'createFile', '_stop'), + array($this->out, $this->out, $this->in) + ); + $this->Task->path = TMP . 'tests' . DS; + + // Make sure the added path is filtered out. + $this->Task->expects($this->exactly($last)) + ->method('out'); + + $this->Task->expects($this->once()) + ->method('in') + ->will($this->returnValue($last)); + + $this->Task->findPath($paths); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/Task/ProjectTaskTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/Task/ProjectTaskTest.php new file mode 100644 index 0000000..8fd1b33 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/Task/ProjectTaskTest.php @@ -0,0 +1,369 @@ +getMock('ConsoleOutput', array(), array(), '', false); + $in = $this->getMock('ConsoleInput', array(), array(), '', false); + + $this->Task = $this->getMock('ProjectTask', + array('in', 'err', 'createFile', '_stop'), + array($out, $out, $in) + ); + $this->Task->path = TMP . 'tests' . DS; + } + +/** + * tearDown method + * + * @return void + */ + public function tearDown() { + parent::tearDown(); + + $Folder = new Folder($this->Task->path . 'bake_test_app'); + $Folder->delete(); + unset($this->Task); + } + +/** + * creates a test project that is used for testing project task. + * + * @return void + */ + protected function _setupTestProject() { + $skel = CAKE . 'Console' . DS . 'Templates' . DS . 'skel'; + $this->Task->expects($this->at(0))->method('in')->will($this->returnValue('y')); + $this->Task->bake($this->Task->path . 'bake_test_app', $skel); + } + +/** + * test bake() method and directory creation. + * + * @return void + */ + public function testBake() { + $this->_setupTestProject(); + $path = $this->Task->path . 'bake_test_app'; + + $this->assertTrue(is_dir($path), 'No project dir %s'); + $dirs = array( + 'Config', + 'Config' . DS . 'Schema', + 'Console', + 'Console' . DS . 'Command', + 'Console' . DS . 'Templates', + 'Console' . DS . 'Command' . DS . 'Task', + 'Controller', + 'Controller' . DS . 'Component', + 'Locale', + 'Model', + 'Model' . DS . 'Behavior', + 'Model' . DS . 'Datasource', + 'Plugin', + 'Test', + 'Test' . DS . 'Case', + 'Test' . DS . 'Case' . DS . 'Controller', + 'Test' . DS . 'Case' . DS . 'Controller' . DS . 'Component', + 'Test' . DS . 'Case' . DS . 'Model', + 'Test' . DS . 'Case' . DS . 'Model' . DS . 'Behavior', + 'Test' . DS . 'Fixture', + 'Vendor', + 'View', + 'View' . DS . 'Helper', + 'tmp', + 'tmp' . DS . 'cache', + 'tmp' . DS . 'cache' . DS . 'models', + 'tmp' . DS . 'cache' . DS . 'persistent', + 'tmp' . DS . 'cache' . DS . 'views', + 'tmp' . DS . 'logs', + 'tmp' . DS . 'sessions', + 'tmp' . DS . 'tests', + 'webroot', + 'webroot' . DS . 'css', + 'webroot' . DS . 'files', + 'webroot' . DS . 'img', + 'webroot' . DS . 'js', + + ); + foreach ($dirs as $dir) { + $this->assertTrue(is_dir($path . DS . $dir), 'Missing ' . $dir); + } + } + +/** + * test bake with an absolute path. + * + * @return void + */ + public function testExecuteWithAbsolutePath() { + $path = $this->Task->args[0] = TMP . 'tests' . DS . 'bake_test_app'; + $this->Task->params['skel'] = CAKE . 'Console' . DS . 'Templates' . DS . 'skel'; + $this->Task->expects($this->at(0))->method('in')->will($this->returnValue('y')); + $this->Task->execute(); + + $this->assertTrue(is_dir($this->Task->args[0]), 'No project dir'); + $File = new File($path . DS . 'webroot' . DS . 'index.php'); + $contents = $File->read(); + $this->assertRegExp('/define\(\'CAKE_CORE_INCLUDE_PATH\', .*?DS/', $contents); + $File = new File($path . DS . 'webroot' . DS . 'test.php'); + $contents = $File->read(); + $this->assertRegExp('/define\(\'CAKE_CORE_INCLUDE_PATH\', .*?DS/', $contents); + } + +/** + * test bake with CakePHP on the include path. The constants should remain commented out. + * + * @return void + */ + public function testExecuteWithCakeOnIncludePath() { + if (!function_exists('ini_set')) { + $this->markTestAsSkipped('Not access to ini_set, cannot proceed.'); + } + $restore = ini_get('include_path'); + ini_set('include_path', CAKE_CORE_INCLUDE_PATH . PATH_SEPARATOR . $restore); + + $path = $this->Task->args[0] = TMP . 'tests' . DS . 'bake_test_app'; + $this->Task->params['skel'] = CAKE . 'Console' . DS . 'Templates' . DS . 'skel'; + $this->Task->expects($this->at(0))->method('in')->will($this->returnValue('y')); + $this->Task->execute(); + + $this->assertTrue(is_dir($this->Task->args[0]), 'No project dir'); + $contents = file_get_contents($path . DS . 'webroot' . DS . 'index.php'); + $this->assertRegExp('#//define\(\'CAKE_CORE_INCLUDE_PATH#', $contents); + + $contents = file_get_contents($path . DS . 'webroot' . DS . 'test.php'); + $this->assertRegExp('#//define\(\'CAKE_CORE_INCLUDE_PATH#', $contents); + + ini_set('include_path', $restore); + } + +/** + * test bake() method with -empty flag, directory creation and empty files. + * + * @return void + */ + public function testBakeEmptyFlag() { + $this->Task->params['empty'] = true; + $this->_setupTestProject(); + $path = $this->Task->path . 'bake_test_app'; + + $empty = array( + 'Console' . DS . 'Command' . DS . 'Task' => 'empty', + 'Controller' . DS . 'Component' => 'empty', + 'Lib' => 'empty', + 'Model' . DS . 'Behavior' => 'empty', + 'Model' . DS . 'Datasource' => 'empty', + 'Plugin' => 'empty', + 'Test' . DS . 'Case' . DS . 'Model' . DS . 'Behavior' => 'empty', + 'Test' . DS . 'Case' . DS . 'Controller' . DS . 'Component' => 'empty', + 'Test' . DS . 'Case' . DS . 'View' . DS . 'Helper' => 'empty', + 'Test' . DS . 'Fixture' => 'empty', + 'Vendor' => 'empty', + 'View' . DS . 'Elements' => 'empty', + 'View' . DS . 'Scaffolds' => 'empty', + 'tmp' . DS . 'cache' . DS . 'models' => 'empty', + 'tmp' . DS . 'cache' . DS . 'persistent' => 'empty', + 'tmp' . DS . 'cache' . DS . 'views' => 'empty', + 'tmp' . DS . 'logs' => 'empty', + 'tmp' . DS . 'sessions' => 'empty', + 'tmp' . DS . 'tests' => 'empty', + 'webroot' . DS . 'js' => 'empty', + 'webroot' . DS . 'files' => 'empty' + ); + + foreach ($empty as $dir => $file) { + $this->assertTrue(is_file($path . DS . $dir . DS . $file), sprintf('Missing %s file in %s', $file, $dir)); + } + } + +/** + * test generation of Security.salt + * + * @return void + */ + public function testSecuritySaltGeneration() { + $this->_setupTestProject(); + + $path = $this->Task->path . 'bake_test_app' . DS; + $result = $this->Task->securitySalt($path); + $this->assertTrue($result); + + $File = new File($path . 'Config' . DS . 'core.php'); + $contents = $File->read(); + $this->assertNotRegExp('/DYhG93b0qyJfIxfs2guVoUubWwvniR2G0FgaC9mi/', $contents, 'Default Salt left behind. %s'); + } + +/** + * test generation of Security.cipherSeed + * + * @return void + */ + public function testSecurityCipherSeedGeneration() { + $this->_setupTestProject(); + + $path = $this->Task->path . 'bake_test_app' . DS; + $result = $this->Task->securityCipherSeed($path); + $this->assertTrue($result); + + $File = new File($path . 'Config' . DS . 'core.php'); + $contents = $File->read(); + $this->assertNotRegExp('/76859309657453542496749683645/', $contents, 'Default CipherSeed left behind. %s'); + } + +/** + * Test that index.php is generated correctly. + * + * @return void + */ + public function testIndexPhpGeneration() { + $this->_setupTestProject(); + + $path = $this->Task->path . 'bake_test_app' . DS; + $this->Task->corePath($path); + + $File = new File($path . 'webroot' . DS . 'index.php'); + $contents = $File->read(); + $this->assertNotRegExp('/define\(\'CAKE_CORE_INCLUDE_PATH\', ROOT/', $contents); + $File = new File($path . 'webroot' . DS . 'test.php'); + $contents = $File->read(); + $this->assertNotRegExp('/define\(\'CAKE_CORE_INCLUDE_PATH\', ROOT/', $contents); + } + +/** + * test getPrefix method, and that it returns Routing.prefix or writes to config file. + * + * @return void + */ + public function testGetPrefix() { + Configure::write('Routing.prefixes', array('admin')); + $result = $this->Task->getPrefix(); + $this->assertEquals('admin_', $result); + + Configure::write('Routing.prefixes', null); + $this->_setupTestProject(); + $this->Task->configPath = $this->Task->path . 'bake_test_app' . DS . 'Config' . DS; + $this->Task->expects($this->once())->method('in')->will($this->returnValue('super_duper_admin')); + + $result = $this->Task->getPrefix(); + $this->assertEquals('super_duper_admin_', $result); + + $File = new File($this->Task->configPath . 'core.php'); + $File->delete(); + } + +/** + * test cakeAdmin() writing core.php + * + * @return void + */ + public function testCakeAdmin() { + $File = new File(APP . 'Config' . DS . 'core.php'); + $contents = $File->read(); + $File = new File(TMP . 'tests' . DS . 'core.php'); + $File->write($contents); + + Configure::write('Routing.prefixes', null); + $this->Task->configPath = TMP . 'tests' . DS; + $result = $this->Task->cakeAdmin('my_prefix'); + $this->assertTrue($result); + + $this->assertEquals(Configure::read('Routing.prefixes'), array('my_prefix')); + $File->delete(); + } + +/** + * test getting the prefix with more than one prefix setup + * + * @return void + */ + public function testGetPrefixWithMultiplePrefixes() { + Configure::write('Routing.prefixes', array('admin', 'ninja', 'shinobi')); + $this->_setupTestProject(); + $this->Task->configPath = $this->Task->path . 'bake_test_app' . DS . 'Config' . DS; + $this->Task->expects($this->once())->method('in')->will($this->returnValue(2)); + + $result = $this->Task->getPrefix(); + $this->assertEquals('ninja_', $result); + } + +/** + * Test execute method with one param to destination folder. + * + * @return void + */ + public function testExecute() { + $this->Task->params['skel'] = CAKE . 'Console' . DS . 'Templates' . DS . 'skel'; + $this->Task->params['working'] = TMP . 'tests' . DS; + + $path = $this->Task->path . 'bake_test_app'; + $this->Task->expects($this->at(0))->method('in')->will($this->returnValue($path)); + $this->Task->expects($this->at(1))->method('in')->will($this->returnValue('y')); + + $this->Task->execute(); + $this->assertTrue(is_dir($path), 'No project dir'); + $this->assertTrue(is_dir($path . DS . 'Controller'), 'No controllers dir '); + $this->assertTrue(is_dir($path . DS . 'Controller' . DS . 'Component'), 'No components dir '); + $this->assertTrue(is_dir($path . DS . 'Model'), 'No models dir'); + $this->assertTrue(is_dir($path . DS . 'View'), 'No views dir'); + $this->assertTrue(is_dir($path . DS . 'View' . DS . 'Helper'), 'No helpers dir'); + $this->assertTrue(is_dir($path . DS . 'Test'), 'No tests dir'); + $this->assertTrue(is_dir($path . DS . 'Test' . DS . 'Case'), 'No cases dir'); + $this->assertTrue(is_dir($path . DS . 'Test' . DS . 'Fixture'), 'No fixtures dir'); + } + +/** + * test console path + * + * @return void + */ + public function testConsolePath() { + $this->_setupTestProject(); + + $path = $this->Task->path . 'bake_test_app' . DS; + $result = $this->Task->consolePath($path); + $this->assertTrue($result); + + $File = new File($path . 'Console' . DS . 'cake.php'); + $contents = $File->read(); + $this->assertNotRegExp('/__CAKE_PATH__/', $contents, 'Console path placeholder left behind.'); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/Task/TemplateTaskTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/Task/TemplateTaskTest.php new file mode 100644 index 0000000..d2df394 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/Task/TemplateTaskTest.php @@ -0,0 +1,165 @@ +getMock('ConsoleOutput', array(), array(), '', false); + $in = $this->getMock('ConsoleInput', array(), array(), '', false); + + $this->Task = $this->getMock('TemplateTask', + array('in', 'err', 'createFile', '_stop', 'clear'), + array($out, $out, $in) + ); + } + +/** + * tearDown method + * + * @return void + */ + public function tearDown() { + parent::tearDown(); + unset($this->Task); + } + +/** + * test that set sets variables + * + * @return void + */ + public function testSet() { + $this->Task->set('one', 'two'); + $this->assertTrue(isset($this->Task->templateVars['one'])); + $this->assertEquals('two', $this->Task->templateVars['one']); + + $this->Task->set(array('one' => 'three', 'four' => 'five')); + $this->assertTrue(isset($this->Task->templateVars['one'])); + $this->assertEquals('three', $this->Task->templateVars['one']); + $this->assertTrue(isset($this->Task->templateVars['four'])); + $this->assertEquals('five', $this->Task->templateVars['four']); + + $this->Task->templateVars = array(); + $this->Task->set(array(3 => 'three', 4 => 'four')); + $this->Task->set(array(1 => 'one', 2 => 'two')); + $expected = array(3 => 'three', 4 => 'four', 1 => 'one', 2 => 'two'); + $this->assertEquals($expected, $this->Task->templateVars); + } + +/** + * test finding themes installed in + * + * @return void + */ + public function testFindingInstalledThemesForBake() { + $consoleLibs = CAKE . 'Console' . DS; + $this->Task->initialize(); + $this->assertEquals($this->Task->templatePaths['default'], $consoleLibs . 'Templates' . DS . 'default' . DS); + } + +/** + * test getting the correct theme name. Ensure that with only one theme, or a theme param + * that the user is not bugged. If there are more, find and return the correct theme name + * + * @return void + */ + public function testGetThemePath() { + $defaultTheme = CAKE . 'Console' . DS . 'Templates' . DS . 'default' . DS; + $this->Task->templatePaths = array('default' => $defaultTheme); + + $this->Task->expects($this->exactly(1))->method('in')->will($this->returnValue('1')); + + $result = $this->Task->getThemePath(); + $this->assertEquals($defaultTheme, $result); + + $this->Task->templatePaths = array('other' => '/some/path', 'default' => $defaultTheme); + $this->Task->params['theme'] = 'other'; + $result = $this->Task->getThemePath(); + $this->assertEquals('/some/path', $result); + + $this->Task->params = array(); + $result = $this->Task->getThemePath(); + $this->assertEquals('/some/path', $result); + $this->assertEquals('other', $this->Task->params['theme']); + } + +/** + * test generate + * + * @return void + */ + public function testGenerate() { + App::build(array( + 'Console' => array( + CAKE . 'Test' . DS . 'test_app' . DS . 'Console' . DS + ) + )); + $this->Task->initialize(); + $this->Task->expects($this->any())->method('in')->will($this->returnValue(1)); + + $result = $this->Task->generate('classes', 'test_object', array('test' => 'foo')); + $expected = "I got rendered\nfoo"; + $this->assertTextEquals($expected, $result); + } + +/** + * test generate with a missing template in the chosen theme. + * ensure fallback to default works. + * + * @return void + */ + public function testGenerateWithTemplateFallbacks() { + App::build(array( + 'Console' => array( + CAKE . 'Test' . DS . 'test_app' . DS . 'Console' . DS, + CAKE_CORE_INCLUDE_PATH . DS . 'console' . DS + ) + )); + $this->Task->initialize(); + $this->Task->params['theme'] = 'test'; + $this->Task->set(array( + 'model' => 'Article', + 'table' => 'articles', + 'import' => false, + 'records' => false, + 'schema' => '' + )); + $result = $this->Task->generate('classes', 'fixture'); + $this->assertRegExp('/ArticleFixture extends CakeTestFixture/', $result); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/Task/TestTaskTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/Task/TestTaskTest.php new file mode 100644 index 0000000..6806af8 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/Task/TestTaskTest.php @@ -0,0 +1,783 @@ + array( + 'className' => 'TestTask.TestTaskComment', + 'foreignKey' => 'article_id', + ) + ); + +/** + * Has and Belongs To Many Associations + * + * @var array + */ + public $hasAndBelongsToMany = array( + 'Tag' => array( + 'className' => 'TestTaskTag', + 'joinTable' => 'articles_tags', + 'foreignKey' => 'article_id', + 'associationForeignKey' => 'tag_id' + ) + ); + +/** + * Example public method + * + * @return void + */ + public function doSomething() { + } + +/** + * Example Secondary public method + * + * @return void + */ + public function doSomethingElse() { + } + +/** + * Example protected method + * + * @return void + */ + protected function _innerMethod() { + } + +} + +/** + * Tag Testing Model + * + * @package Cake.Test.Case.Console.Command.Task + * @package Cake.Test.Case.Console.Command.Task + */ +class TestTaskTag extends Model { + +/** + * Model name + * + * @var string + */ + public $name = 'TestTaskTag'; + +/** + * Table name + * + * @var string + */ + public $useTable = 'tags'; + +/** + * Has and Belongs To Many Associations + * + * @var array + */ + public $hasAndBelongsToMany = array( + 'Article' => array( + 'className' => 'TestTaskArticle', + 'joinTable' => 'articles_tags', + 'foreignKey' => 'tag_id', + 'associationForeignKey' => 'article_id' + ) + ); +} + +/** + * Simulated plugin + * + * @package Cake.Test.Case.Console.Command.Task + * @package Cake.Test.Case.Console.Command.Task + */ +class TestTaskAppModel extends Model { +} + +/** + * Testing AppMode (TaskComment) + * + * @package Cake.Test.Case.Console.Command.Task + * @package Cake.Test.Case.Console.Command.Task + */ +class TestTaskComment extends TestTaskAppModel { + +/** + * Model name + * + * @var string + */ + public $name = 'TestTaskComment'; + +/** + * Table name + * + * @var string + */ + public $useTable = 'comments'; + +/** + * Belongs To Associations + * + * @var array + */ + public $belongsTo = array( + 'Article' => array( + 'className' => 'TestTaskArticle', + 'foreignKey' => 'article_id', + ) + ); +} + +/** + * Test Task Comments Controller + * + * @package Cake.Test.Case.Console.Command.Task + * @package Cake.Test.Case.Console.Command.Task + */ +class TestTaskCommentsController extends Controller { + +/** + * Controller Name + * + * @var string + */ + public $name = 'TestTaskComments'; + +/** + * Models to use + * + * @var array + */ + public $uses = array('TestTaskComment', 'TestTaskTag'); +} + +/** + * TestTaskTest class + * + * @package Cake.Test.Case.Console.Command.Task + */ +class TestTaskTest extends CakeTestCase { + +/** + * Fixtures + * + * @var string + */ + public $fixtures = array('core.article', 'core.comment', 'core.articles_tag', 'core.tag'); + +/** + * setUp method + * + * @return void + */ + public function setUp() { + parent::setUp(); + $out = $this->getMock('ConsoleOutput', array(), array(), '', false); + $in = $this->getMock('ConsoleInput', array(), array(), '', false); + + $this->Task = $this->getMock('TestTask', + array('in', 'err', 'createFile', '_stop', 'isLoadableClass'), + array($out, $out, $in) + ); + $this->Task->name = 'Test'; + $this->Task->Template = new TemplateTask($out, $out, $in); + } + +/** + * tearDown method + * + * @return void + */ + public function tearDown() { + parent::tearDown(); + unset($this->Task); + CakePlugin::unload(); + } + +/** + * Test that file path generation doesn't continuously append paths. + * + * @return void + */ + public function testFilePathGenerationModelRepeated() { + $this->Task->expects($this->never())->method('err'); + $this->Task->expects($this->never())->method('_stop'); + + $file = TESTS . 'Case' . DS . 'Model' . DS . 'MyClassTest.php'; + + $this->Task->expects($this->at(1))->method('createFile') + ->with($file, $this->anything()); + + $this->Task->expects($this->at(3))->method('createFile') + ->with($file, $this->anything()); + + $file = TESTS . 'Case' . DS . 'Controller' . DS . 'CommentsControllerTest.php'; + $this->Task->expects($this->at(5))->method('createFile') + ->with($file, $this->anything()); + + $this->Task->bake('Model', 'MyClass'); + $this->Task->bake('Model', 'MyClass'); + $this->Task->bake('Controller', 'Comments'); + } + +/** + * Test that method introspection pulls all relevant non parent class + * methods into the test case. + * + * @return void + */ + public function testMethodIntrospection() { + $result = $this->Task->getTestableMethods('TestTaskArticle'); + $expected = array('dosomething', 'dosomethingelse'); + $this->assertEquals($expected, array_map('strtolower', $result)); + } + +/** + * test that the generation of fixtures works correctly. + * + * @return void + */ + public function testFixtureArrayGenerationFromModel() { + $subject = ClassRegistry::init('TestTaskArticle'); + $result = $this->Task->generateFixtureList($subject); + $expected = array('plugin.test_task.test_task_comment', 'app.articles_tags', + 'app.test_task_article', 'app.test_task_tag'); + + $this->assertEquals(sort($expected), sort($result)); + } + +/** + * test that the generation of fixtures works correctly. + * + * @return void + */ + public function testFixtureArrayGenerationFromController() { + $subject = new TestTaskCommentsController(); + $result = $this->Task->generateFixtureList($subject); + $expected = array('plugin.test_task.test_task_comment', 'app.articles_tags', + 'app.test_task_article', 'app.test_task_tag'); + + $this->assertEquals(sort($expected), sort($result)); + } + +/** + * test user interaction to get object type + * + * @return void + */ + public function testGetObjectType() { + $this->Task->expects($this->once())->method('_stop'); + $this->Task->expects($this->at(0))->method('in')->will($this->returnValue('q')); + $this->Task->expects($this->at(2))->method('in')->will($this->returnValue(2)); + + $this->Task->getObjectType(); + + $result = $this->Task->getObjectType(); + $this->assertEquals($this->Task->classTypes['Controller'], $result); + } + +/** + * creating test subjects should clear the registry so the registry is always fresh + * + * @return void + */ + public function testRegistryClearWhenBuildingTestObjects() { + ClassRegistry::flush(); + $model = ClassRegistry::init('TestTaskComment'); + $model->bindModel(array( + 'belongsTo' => array( + 'Random' => array( + 'className' => 'TestTaskArticle', + 'foreignKey' => 'article_id', + ) + ) + )); + $keys = ClassRegistry::keys(); + $this->assertTrue(in_array('test_task_comment', $keys)); + $object = $this->Task->buildTestSubject('Model', 'TestTaskComment'); + + $keys = ClassRegistry::keys(); + $this->assertFalse(in_array('random', $keys)); + } + +/** + * test that getClassName returns the user choice as a classname. + * + * @return void + */ + public function testGetClassName() { + $objects = App::objects('model'); + $this->skipIf(empty($objects), 'No models in app.'); + + $this->Task->expects($this->at(0))->method('in')->will($this->returnValue('MyCustomClass')); + $this->Task->expects($this->at(1))->method('in')->will($this->returnValue(1)); + + $result = $this->Task->getClassName('Model'); + $this->assertEquals('MyCustomClass', $result); + + $result = $this->Task->getClassName('Model'); + $options = App::objects('model'); + $this->assertEquals($options[0], $result); + } + +/** + * Test the user interaction for defining additional fixtures. + * + * @return void + */ + public function testGetUserFixtures() { + $this->Task->expects($this->at(0))->method('in')->will($this->returnValue('y')); + $this->Task->expects($this->at(1))->method('in') + ->will($this->returnValue('app.pizza, app.topping, app.side_dish')); + + $result = $this->Task->getUserFixtures(); + $expected = array('app.pizza', 'app.topping', 'app.side_dish'); + $this->assertEquals($expected, $result); + } + +/** + * test that resolving classnames works + * + * @return void + */ + public function testGetRealClassname() { + $result = $this->Task->getRealClassname('Model', 'Post'); + $this->assertEquals('Post', $result); + + $result = $this->Task->getRealClassname('Controller', 'Posts'); + $this->assertEquals('PostsController', $result); + + $result = $this->Task->getRealClassname('Controller', 'PostsController'); + $this->assertEquals('PostsController', $result); + + $result = $this->Task->getRealClassname('Controller', 'AlertTypes'); + $this->assertEquals('AlertTypesController', $result); + + $result = $this->Task->getRealClassname('Helper', 'Form'); + $this->assertEquals('FormHelper', $result); + + $result = $this->Task->getRealClassname('Helper', 'FormHelper'); + $this->assertEquals('FormHelper', $result); + + $result = $this->Task->getRealClassname('Behavior', 'Containable'); + $this->assertEquals('ContainableBehavior', $result); + + $result = $this->Task->getRealClassname('Behavior', 'ContainableBehavior'); + $this->assertEquals('ContainableBehavior', $result); + + $result = $this->Task->getRealClassname('Component', 'Auth'); + $this->assertEquals('AuthComponent', $result); + } + +/** + * test baking files. The conditionally run tests are known to fail in PHP4 + * as PHP4 classnames are all lower case, breaking the plugin path inflection. + * + * @return void + */ + public function testBakeModelTest() { + $this->Task->expects($this->once())->method('createFile')->will($this->returnValue(true)); + $this->Task->expects($this->once())->method('isLoadableClass')->will($this->returnValue(true)); + + $result = $this->Task->bake('Model', 'TestTaskArticle'); + + $this->assertContains("App::uses('TestTaskArticle', 'Model')", $result); + $this->assertContains('class TestTaskArticleTest extends CakeTestCase', $result); + + $this->assertContains('function setUp()', $result); + $this->assertContains("\$this->TestTaskArticle = ClassRegistry::init('TestTaskArticle')", $result); + + $this->assertContains('function tearDown()', $result); + $this->assertContains('unset($this->TestTaskArticle)', $result); + + $this->assertContains('function testDoSomething()', $result); + $this->assertContains('function testDoSomethingElse()', $result); + + $this->assertContains("'app.test_task_article'", $result); + $this->assertContains("'app.test_task_comment'", $result); + $this->assertContains("'app.test_task_tag'", $result); + $this->assertContains("'app.articles_tag'", $result); + } + +/** + * test baking controller test files + * + * @return void + */ + public function testBakeControllerTest() { + $this->Task->expects($this->once())->method('createFile')->will($this->returnValue(true)); + $this->Task->expects($this->once())->method('isLoadableClass')->will($this->returnValue(true)); + + $result = $this->Task->bake('Controller', 'TestTaskComments'); + + $this->assertContains("App::uses('TestTaskCommentsController', 'Controller')", $result); + $this->assertContains('class TestTaskCommentsControllerTest extends ControllerTestCase', $result); + + $this->assertNotContains('function setUp()', $result); + $this->assertNotContains("\$this->TestTaskComments = new TestTaskCommentsController()", $result); + $this->assertNotContains("\$this->TestTaskComments->constructClasses()", $result); + + $this->assertNotContains('function tearDown()', $result); + $this->assertNotContains('unset($this->TestTaskComments)', $result); + + $this->assertContains("'app.test_task_article'", $result); + $this->assertContains("'app.test_task_comment'", $result); + $this->assertContains("'app.test_task_tag'", $result); + $this->assertContains("'app.articles_tag'", $result); + } + +/** + * test baking component test files, + * + * @return void + */ + public function testBakeComponentTest() { + $this->Task->expects($this->once())->method('createFile')->will($this->returnValue(true)); + + $result = $this->Task->bake('Component', 'Example'); + + $this->assertContains("App::uses('ExampleComponent', 'Controller/Component')", $result); + $this->assertContains('class ExampleComponentTest extends CakeTestCase', $result); + + $this->assertContains('function setUp()', $result); + $this->assertContains("\$Collection = new ComponentCollection()", $result); + $this->assertContains("\$this->Example = new ExampleComponent(\$Collection)", $result); + + $this->assertContains('function tearDown()', $result); + $this->assertContains('unset($this->Example)', $result); + } + +/** + * test baking behavior test files, + * + * @return void + */ + public function testBakeBehaviorTest() { + $this->Task->expects($this->once())->method('createFile')->will($this->returnValue(true)); + + $result = $this->Task->bake('Behavior', 'Example'); + + $this->assertContains("App::uses('ExampleBehavior', 'Model/Behavior')", $result); + $this->assertContains('class ExampleBehaviorTest extends CakeTestCase', $result); + + $this->assertContains('function setUp()', $result); + $this->assertContains("\$this->Example = new ExampleBehavior()", $result); + + $this->assertContains('function tearDown()', $result); + $this->assertContains('unset($this->Example)', $result); + } + +/** + * test baking helper test files, + * + * @return void + */ + public function testBakeHelperTest() { + $this->Task->expects($this->once())->method('createFile')->will($this->returnValue(true)); + + $result = $this->Task->bake('Helper', 'Example'); + + $this->assertContains("App::uses('ExampleHelper', 'View/Helper')", $result); + $this->assertContains('class ExampleHelperTest extends CakeTestCase', $result); + + $this->assertContains('function setUp()', $result); + $this->assertContains("\$View = new View()", $result); + $this->assertContains("\$this->Example = new ExampleHelper(\$View)", $result); + + $this->assertContains('function tearDown()', $result); + $this->assertContains('unset($this->Example)', $result); + } + +/** + * test Constructor generation ensure that constructClasses is called for controllers + * + * @return void + */ + public function testGenerateConstructor() { + $result = $this->Task->generateConstructor('controller', 'PostsController', null); + $expected = array('', '', ''); + $this->assertEquals($expected, $result); + + $result = $this->Task->generateConstructor('model', 'Post', null); + $expected = array('', "ClassRegistry::init('Post');\n", ''); + $this->assertEquals($expected, $result); + + $result = $this->Task->generateConstructor('helper', 'FormHelper', null); + $expected = array("\$View = new View();\n", "new FormHelper(\$View);\n", ''); + $this->assertEquals($expected, $result); + } + +/** + * Test generateUses() + */ + public function testGenerateUses() { + $result = $this->Task->generateUses('model', 'Model', 'Post'); + $expected = array( + array('Post', 'Model') + ); + $this->assertEquals($expected, $result); + + $result = $this->Task->generateUses('controller', 'Controller', 'PostsController'); + $expected = array( + array('PostsController', 'Controller') + ); + $this->assertEquals($expected, $result); + + $result = $this->Task->generateUses('helper', 'View/Helper', 'FormHelper'); + $expected = array( + array('View', 'View'), + array('Helper', 'View'), + array('FormHelper', 'View/Helper'), + ); + $this->assertEquals($expected, $result); + + $result = $this->Task->generateUses('component', 'Controller/Component', 'AuthComponent'); + $expected = array( + array('ComponentCollection', 'Controller'), + array('Component', 'Controller'), + array('AuthComponent', 'Controller/Component') + ); + $this->assertEquals($expected, $result); + } + +/** + * Test that mock class generation works for the appropriate classes + * + * @return void + */ + public function testMockClassGeneration() { + $result = $this->Task->hasMockClass('controller'); + $this->assertTrue($result); + } + +/** + * test bake() with a -plugin param + * + * @return void + */ + public function testBakeWithPlugin() { + $this->Task->plugin = 'TestTest'; + + //fake plugin path + CakePlugin::load('TestTest', array('path' => APP . 'Plugin' . DS . 'TestTest' . DS)); + $path = APP . 'Plugin' . DS . 'TestTest' . DS . 'Test' . DS . 'Case' . DS . 'View' . DS . 'Helper' . DS . 'FormHelperTest.php'; + $this->Task->expects($this->once())->method('createFile') + ->with($path, $this->anything()); + + $this->Task->bake('Helper', 'Form'); + CakePlugin::unload(); + } + +/** + * test interactive with plugins lists from the plugin + * + * @return void + */ + public function testInteractiveWithPlugin() { + $testApp = CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS; + App::build(array( + 'Plugin' => array($testApp) + ), App::RESET); + CakePlugin::load('TestPlugin'); + + $this->Task->plugin = 'TestPlugin'; + $path = $testApp . 'TestPlugin' . DS . 'Test' . DS . 'Case' . DS . 'View' . DS . 'Helper' . DS . 'OtherHelperTest.php'; + $this->Task->expects($this->any()) + ->method('in') + ->will($this->onConsecutiveCalls( + 5, //helper + 1 //OtherHelper + )); + + $this->Task->expects($this->once()) + ->method('createFile') + ->with($path, $this->anything()); + + $this->Task->stdout->expects($this->at(21)) + ->method('write') + ->with('1. OtherHelperHelper'); + + $this->Task->execute(); + } + + public static function caseFileNameProvider() { + return array( + array('Model', 'Post', 'Case' . DS . 'Model' . DS . 'PostTest.php'), + array('Helper', 'Form', 'Case' . DS . 'View' . DS . 'Helper' . DS . 'FormHelperTest.php'), + array('Controller', 'Posts', 'Case' . DS . 'Controller' . DS . 'PostsControllerTest.php'), + array('Behavior', 'Containable', 'Case' . DS . 'Model' . DS . 'Behavior' . DS . 'ContainableBehaviorTest.php'), + array('Component', 'Auth', 'Case' . DS . 'Controller' . DS . 'Component' . DS . 'AuthComponentTest.php'), + array('model', 'Post', 'Case' . DS . 'Model' . DS . 'PostTest.php'), + array('helper', 'Form', 'Case' . DS . 'View' . DS . 'Helper' . DS . 'FormHelperTest.php'), + array('controller', 'Posts', 'Case' . DS . 'Controller' . DS . 'PostsControllerTest.php'), + array('behavior', 'Containable', 'Case' . DS . 'Model' . DS . 'Behavior' . DS . 'ContainableBehaviorTest.php'), + array('component', 'Auth', 'Case' . DS . 'Controller' . DS . 'Component' . DS . 'AuthComponentTest.php'), + ); + } + +/** + * Test filename generation for each type + plugins + * + * @dataProvider caseFileNameProvider + * @return void + */ + public function testTestCaseFileName($type, $class, $expected) { + $this->Task->path = DS . 'my' . DS . 'path' . DS . 'tests' . DS; + + $result = $this->Task->testCaseFileName($type, $class); + $expected = $this->Task->path . $expected; + $this->assertEquals($expected, $result); + } + +/** + * Test filename generation for plugins. + * + * @return void + */ + public function testTestCaseFileNamePlugin() { + $this->Task->path = DS . 'my' . DS . 'path' . DS . 'tests' . DS; + + CakePlugin::load('TestTest', array('path' => APP . 'Plugin' . DS . 'TestTest' . DS )); + $this->Task->plugin = 'TestTest'; + $result = $this->Task->testCaseFileName('Model', 'Post'); + $expected = APP . 'Plugin' . DS . 'TestTest' . DS . 'Test' . DS . 'Case' . DS . 'Model' . DS . 'PostTest.php'; + $this->assertEquals($expected, $result); + } + +/** + * test execute with a type defined + * + * @return void + */ + public function testExecuteWithOneArg() { + $this->Task->args[0] = 'Model'; + $this->Task->expects($this->at(0))->method('in')->will($this->returnValue('TestTaskTag')); + $this->Task->expects($this->once())->method('isLoadableClass')->will($this->returnValue(true)); + $this->Task->expects($this->once())->method('createFile') + ->with( + $this->anything(), + $this->stringContains('class TestTaskTagTest extends CakeTestCase') + ); + $this->Task->execute(); + } + +/** + * test execute with type and class name defined + * + * @return void + */ + public function testExecuteWithTwoArgs() { + $this->Task->args = array('Model', 'TestTaskTag'); + $this->Task->expects($this->at(0))->method('in')->will($this->returnValue('TestTaskTag')); + $this->Task->expects($this->once())->method('createFile') + ->with( + $this->anything(), + $this->stringContains('class TestTaskTagTest extends CakeTestCase') + ); + $this->Task->expects($this->any())->method('isLoadableClass')->will($this->returnValue(true)); + $this->Task->execute(); + } + +/** + * test execute with type and class name defined and lower case. + * + * @return void + */ + public function testExecuteWithTwoArgsLowerCase() { + $this->Task->args = array('model', 'TestTaskTag'); + $this->Task->expects($this->at(0))->method('in')->will($this->returnValue('TestTaskTag')); + $this->Task->expects($this->once())->method('createFile') + ->with( + $this->anything(), + $this->stringContains('class TestTaskTagTest extends CakeTestCase') + ); + $this->Task->expects($this->any())->method('isLoadableClass')->will($this->returnValue(true)); + $this->Task->execute(); + } + +/** + * Data provider for mapType() tests. + * + * @return array + */ + public static function mapTypeProvider() { + return array( + array('controller', null, 'Controller'), + array('Controller', null, 'Controller'), + array('component', null, 'Controller/Component'), + array('Component', null, 'Controller/Component'), + array('model', null, 'Model'), + array('Model', null, 'Model'), + array('behavior', null, 'Model/Behavior'), + array('Behavior', null, 'Model/Behavior'), + array('helper', null, 'View/Helper'), + array('Helper', null, 'View/Helper'), + array('Helper', 'DebugKit', 'DebugKit.View/Helper'), + ); + } + +/** + * Test that mapType returns the correct package names. + * + * @dataProvider mapTypeProvider + * @return void + */ + public function testMapType($original, $plugin, $expected) { + $this->assertEquals($expected, $this->Task->mapType($original, $plugin)); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/Task/ViewTaskTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/Task/ViewTaskTest.php new file mode 100644 index 0000000..4865443 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/Task/ViewTaskTest.php @@ -0,0 +1,731 @@ + array( + 'className' => 'TestTest.ViewTaskArticle', + 'foreignKey' => 'article_id' + ) + ); +} + +/** + * Test View Task Article Model + * + * @package Cake.Test.Case.Console.Command.Task + * @package Cake.Test.Case.Console.Command.Task + */ +class ViewTaskArticle extends Model { + +/** + * Model name + * + * @var string + */ + public $name = 'ViewTaskArticle'; + +/** + * Table name + * + * @var string + */ + public $useTable = 'articles'; +} + +/** + * Test View Task Comments Controller + * + * @package Cake.Test.Case.Console.Command.Task + * @package Cake.Test.Case.Console.Command.Task + */ +class ViewTaskCommentsController extends Controller { + +/** + * Controller name + * + * @var string + */ + public $name = 'ViewTaskComments'; + +/** + * Testing public controller action + * + * @return void + */ + public function index() { + } + +/** + * Testing public controller action + * + * @return void + */ + public function add() { + } + +} + +/** + * Test View Task Articles Controller + * + * @package Cake.Test.Case.Console.Command.Task + * @package Cake.Test.Case.Console.Command.Task + */ +class ViewTaskArticlesController extends Controller { + +/** + * Controller name + * + * @var string + */ + public $name = 'ViewTaskArticles'; + +/** + * Test public controller action + * + * @return void + */ + public function index() { + } + +/** + * Test public controller action + * + * @return void + */ + public function add() { + } + +/** + * Test admin prefixed controller action + * + * @return void + */ + public function admin_index() { + } + +/** + * Test admin prefixed controller action + * + * @return void + */ + public function admin_add() { + } + +/** + * Test admin prefixed controller action + * + * @return void + */ + public function admin_view() { + } + +/** + * Test admin prefixed controller action + * + * @return void + */ + public function admin_edit() { + } + +/** + * Test admin prefixed controller action + * + * @return void + */ + public function admin_delete() { + } + +} + +/** + * ViewTaskTest class + * + * @package Cake.Test.Case.Console.Command.Task + */ +class ViewTaskTest extends CakeTestCase { + +/** + * Fixtures + * + * @var array + */ + public $fixtures = array('core.article', 'core.comment', 'core.articles_tag', 'core.tag'); + +/** + * setUp method + * + * Ensure that the default theme is used + * + * @return void + */ + public function setUp() { + parent::setUp(); + $out = $this->getMock('ConsoleOutput', array(), array(), '', false); + $in = $this->getMock('ConsoleInput', array(), array(), '', false); + + $this->Task = $this->getMock('ViewTask', + array('in', 'err', 'createFile', '_stop'), + array($out, $out, $in) + ); + $this->Task->Template = new TemplateTask($out, $out, $in); + $this->Task->Controller = $this->getMock('ControllerTask', array(), array($out, $out, $in)); + $this->Task->Project = $this->getMock('ProjectTask', array(), array($out, $out, $in)); + $this->Task->DbConfig = $this->getMock('DbConfigTask', array(), array($out, $out, $in)); + + $this->Task->path = TMP; + $this->Task->Template->params['theme'] = 'default'; + $this->Task->Template->templatePaths = array('default' => CAKE . 'Console' . DS . 'Templates' . DS . 'default' . DS); + } + +/** + * tearDown method + * + * @return void + */ + public function tearDown() { + parent::tearDown(); + unset($this->Task, $this->Dispatch); + } + +/** + * Test getContent and parsing of Templates. + * + * @return void + */ + public function testGetContent() { + $vars = array( + 'modelClass' => 'TestViewModel', + 'schema' => array(), + 'primaryKey' => 'id', + 'displayField' => 'name', + 'singularVar' => 'testViewModel', + 'pluralVar' => 'testViewModels', + 'singularHumanName' => 'Test View Model', + 'pluralHumanName' => 'Test View Models', + 'fields' => array('id', 'name', 'body'), + 'associations' => array() + ); + $result = $this->Task->getContent('view', $vars); + + $this->assertRegExp('/Delete Test View Model/', $result); + $this->assertRegExp('/Edit Test View Model/', $result); + $this->assertRegExp('/List Test View Models/', $result); + $this->assertRegExp('/New Test View Model/', $result); + + $this->assertRegExp('/testViewModel\[\'TestViewModel\'\]\[\'id\'\]/', $result); + $this->assertRegExp('/testViewModel\[\'TestViewModel\'\]\[\'name\'\]/', $result); + $this->assertRegExp('/testViewModel\[\'TestViewModel\'\]\[\'body\'\]/', $result); + } + +/** + * test getContent() using an admin_prefixed action. + * + * @return void + */ + public function testGetContentWithAdminAction() { + $_back = Configure::read('Routing'); + Configure::write('Routing.prefixes', array('admin')); + $vars = array( + 'modelClass' => 'TestViewModel', + 'schema' => array(), + 'primaryKey' => 'id', + 'displayField' => 'name', + 'singularVar' => 'testViewModel', + 'pluralVar' => 'testViewModels', + 'singularHumanName' => 'Test View Model', + 'pluralHumanName' => 'Test View Models', + 'fields' => array('id', 'name', 'body'), + 'associations' => array() + ); + $result = $this->Task->getContent('admin_view', $vars); + + $this->assertRegExp('/Delete Test View Model/', $result); + $this->assertRegExp('/Edit Test View Model/', $result); + $this->assertRegExp('/List Test View Models/', $result); + $this->assertRegExp('/New Test View Model/', $result); + + $this->assertRegExp('/testViewModel\[\'TestViewModel\'\]\[\'id\'\]/', $result); + $this->assertRegExp('/testViewModel\[\'TestViewModel\'\]\[\'name\'\]/', $result); + $this->assertRegExp('/testViewModel\[\'TestViewModel\'\]\[\'body\'\]/', $result); + + $result = $this->Task->getContent('admin_add', $vars); + $this->assertRegExp("/input\('name'\)/", $result); + $this->assertRegExp("/input\('body'\)/", $result); + $this->assertRegExp('/List Test View Models/', $result); + + Configure::write('Routing', $_back); + } + +/** + * test Bake method + * + * @return void + */ + public function testBakeView() { + $this->Task->controllerName = 'ViewTaskComments'; + + $this->Task->expects($this->at(0))->method('createFile') + ->with( + TMP . 'ViewTaskComments' . DS . 'view.ctp', + $this->stringContains('View Task Articles') + ); + + $this->Task->bake('view', true); + } + +/** + * test baking an edit file + * + * @return void + */ + public function testBakeEdit() { + $this->Task->controllerName = 'ViewTaskComments'; + + $this->Task->expects($this->at(0))->method('createFile') + ->with( + TMP . 'ViewTaskComments' . DS . 'edit.ctp', + new PHPUnit_Framework_Constraint_IsAnything() + ); + $this->Task->bake('edit', true); + } + +/** + * test baking an index + * + * @return void + */ + public function testBakeIndex() { + $this->Task->controllerName = 'ViewTaskComments'; + + $this->Task->expects($this->at(0))->method('createFile') + ->with( + TMP . 'ViewTaskComments' . DS . 'index.ctp', + $this->stringContains("\$viewTaskComment['Article']['title']") + ); + $this->Task->bake('index', true); + } + +/** + * test that baking a view with no template doesn't make a file. + * + * @return void + */ + public function testBakeWithNoTemplate() { + $this->Task->controllerName = 'ViewTaskComments'; + + $this->Task->expects($this->never())->method('createFile'); + $this->Task->bake('delete', true); + } + +/** + * test bake() with a -plugin param + * + * @return void + */ + public function testBakeWithPlugin() { + $this->Task->controllerName = 'ViewTaskComments'; + $this->Task->plugin = 'TestTest'; + $this->Task->name = 'View'; + + //fake plugin path + CakePlugin::load('TestTest', array('path' => APP . 'Plugin' . DS . 'TestTest' . DS)); + $path = APP . 'Plugin' . DS . 'TestTest' . DS . 'View' . DS . 'ViewTaskComments' . DS . 'view.ctp'; + + $result = $this->Task->getContent('index'); + $this->assertNotContains('List Test Test.view Task Articles', $result); + + $this->Task->expects($this->once()) + ->method('createFile') + ->with($path, $this->anything()); + + $this->Task->bake('view', true); + CakePlugin::unload(); + } + +/** + * test bake actions baking multiple actions. + * + * @return void + */ + public function testBakeActions() { + $this->Task->controllerName = 'ViewTaskComments'; + + $this->Task->expects($this->at(0))->method('createFile') + ->with( + TMP . 'ViewTaskComments' . DS . 'view.ctp', + $this->stringContains('View Task Comments') + ); + $this->Task->expects($this->at(1))->method('createFile') + ->with( + TMP . 'ViewTaskComments' . DS . 'edit.ctp', + $this->stringContains('Edit View Task Comment') + ); + $this->Task->expects($this->at(2))->method('createFile') + ->with( + TMP . 'ViewTaskComments' . DS . 'index.ctp', + $this->stringContains('ViewTaskComment') + ); + + $this->Task->bakeActions(array('view', 'edit', 'index'), array()); + } + +/** + * test baking a customAction (non crud) + * + * @return void + */ + public function testCustomAction() { + $this->Task->controllerName = 'ViewTaskComments'; + + $this->Task->expects($this->any())->method('in') + ->will($this->onConsecutiveCalls('', 'my_action', 'y')); + + $this->Task->expects($this->once())->method('createFile') + ->with( + TMP . 'ViewTaskComments' . DS . 'my_action.ctp', + $this->anything() + ); + + $this->Task->customAction(); + } + +/** + * Test all() + * + * @return void + */ + public function testExecuteIntoAll() { + $this->Task->args[0] = 'all'; + + $this->Task->Controller->expects($this->once())->method('listAll') + ->will($this->returnValue(array('view_task_comments'))); + + $this->Task->expects($this->at(0))->method('createFile') + ->with( + TMP . 'ViewTaskComments' . DS . 'index.ctp', + $this->anything() + ); + $this->Task->expects($this->at(1))->method('createFile') + ->with( + TMP . 'ViewTaskComments' . DS . 'add.ctp', + $this->anything() + ); + $this->Task->expects($this->exactly(2))->method('createFile'); + + $this->Task->execute(); + } + +/** + * Test all() with action parameter + * + * @return void + */ + public function testExecuteIntoAllWithActionName() { + $this->Task->args = array('all', 'index'); + + $this->Task->Controller->expects($this->once())->method('listAll') + ->will($this->returnValue(array('view_task_comments'))); + + $this->Task->expects($this->once())->method('createFile') + ->with( + TMP . 'ViewTaskComments' . DS . 'index.ctp', + $this->anything() + ); + + $this->Task->execute(); + } + +/** + * test `cake bake view $controller view` + * + * @return void + */ + public function testExecuteWithActionParam() { + $this->Task->args[0] = 'ViewTaskComments'; + $this->Task->args[1] = 'view'; + + $this->Task->expects($this->once())->method('createFile') + ->with( + TMP . 'ViewTaskComments' . DS . 'view.ctp', + $this->anything() + ); + $this->Task->execute(); + } + +/** + * test `cake bake view $controller` + * Ensure that views are only baked for actions that exist in the controller. + * + * @return void + */ + public function testExecuteWithController() { + $this->Task->args[0] = 'ViewTaskComments'; + + $this->Task->expects($this->at(0))->method('createFile') + ->with( + TMP . 'ViewTaskComments' . DS . 'index.ctp', + $this->anything() + ); + $this->Task->expects($this->at(1))->method('createFile') + ->with( + TMP . 'ViewTaskComments' . DS . 'add.ctp', + $this->anything() + ); + $this->Task->expects($this->exactly(2))->method('createFile'); + + $this->Task->execute(); + } + +/** + * static dataprovider for test cases + * + * @return void + */ + public static function nameVariations() { + return array(array('ViewTaskComments'), array('ViewTaskComment'), array('view_task_comment')); + } + +/** + * test that both plural and singular forms can be used for baking views. + * + * @dataProvider nameVariations + * @return void + */ + public function testExecuteWithControllerVariations($name) { + $this->Task->args = array($name); + + $this->Task->expects($this->at(0))->method('createFile') + ->with( + TMP . 'ViewTaskComments' . DS . 'index.ctp', + $this->anything() + ); + $this->Task->expects($this->at(1))->method('createFile') + ->with( + TMP . 'ViewTaskComments' . DS . 'add.ctp', + $this->anything() + ); + $this->Task->execute(); + } + +/** + * test `cake bake view $controller --admin` + * Which only bakes admin methods, not non-admin methods. + * + * @return void + */ + public function testExecuteWithControllerAndAdminFlag() { + $_back = Configure::read('Routing'); + Configure::write('Routing.prefixes', array('admin')); + $this->Task->args[0] = 'ViewTaskArticles'; + $this->Task->params['admin'] = 1; + + $this->Task->Project->expects($this->any())->method('getPrefix')->will($this->returnValue('admin_')); + + $this->Task->expects($this->exactly(4))->method('createFile'); + + $views = array('admin_index.ctp', 'admin_add.ctp', 'admin_view.ctp', 'admin_edit.ctp'); + foreach ($views as $i => $view) { + $this->Task->expects($this->at($i))->method('createFile') + ->with( + TMP . 'ViewTaskArticles' . DS . $view, + $this->anything() + ); + } + $this->Task->execute(); + Configure::write('Routing', $_back); + } + +/** + * test execute into interactive. + * + * @return void + */ + public function testExecuteInteractive() { + $this->Task->connection = 'test'; + $this->Task->args = array(); + $this->Task->params = array(); + + $this->Task->Controller->expects($this->once())->method('getName') + ->will($this->returnValue('ViewTaskComments')); + + $this->Task->expects($this->any())->method('in') + ->will($this->onConsecutiveCalls('y', 'y', 'n')); + + $this->Task->expects($this->at(3))->method('createFile') + ->with( + TMP . 'ViewTaskComments' . DS . 'index.ctp', + $this->stringContains('ViewTaskComment') + ); + + $this->Task->expects($this->at(4))->method('createFile') + ->with( + TMP . 'ViewTaskComments' . DS . 'view.ctp', + $this->stringContains('ViewTaskComment') + ); + + $this->Task->expects($this->at(5))->method('createFile') + ->with( + TMP . 'ViewTaskComments' . DS . 'add.ctp', + $this->stringContains('Add View Task Comment') + ); + + $this->Task->expects($this->at(6))->method('createFile') + ->with( + TMP . 'ViewTaskComments' . DS . 'edit.ctp', + $this->stringContains('Edit View Task Comment') + ); + + $this->Task->expects($this->exactly(4))->method('createFile'); + $this->Task->execute(); + } + +/** + * test `cake bake view posts index list` + * + * @return void + */ + public function testExecuteWithAlternateTemplates() { + $this->Task->connection = 'test'; + $this->Task->args = array('ViewTaskComments', 'index', 'list'); + $this->Task->params = array(); + + $this->Task->expects($this->once())->method('createFile') + ->with( + TMP . 'ViewTaskComments' . DS . 'list.ctp', + $this->stringContains('ViewTaskComment') + ); + $this->Task->execute(); + } + +/** + * test execute into interactive() with admin methods. + * + * @return void + */ + public function testExecuteInteractiveWithAdmin() { + Configure::write('Routing.prefixes', array('admin')); + $this->Task->connection = 'test'; + $this->Task->args = array(); + + $this->Task->Controller->expects($this->once())->method('getName') + ->will($this->returnValue('ViewTaskComments')); + + $this->Task->Project->expects($this->once())->method('getPrefix') + ->will($this->returnValue('admin_')); + + $this->Task->expects($this->any())->method('in') + ->will($this->onConsecutiveCalls('y', 'n', 'y')); + + $this->Task->expects($this->at(3))->method('createFile') + ->with( + TMP . 'ViewTaskComments' . DS . 'admin_index.ctp', + $this->stringContains('ViewTaskComment') + ); + + $this->Task->expects($this->at(4))->method('createFile') + ->with( + TMP . 'ViewTaskComments' . DS . 'admin_view.ctp', + $this->stringContains('ViewTaskComment') + ); + + $this->Task->expects($this->at(5))->method('createFile') + ->with( + TMP . 'ViewTaskComments' . DS . 'admin_add.ctp', + $this->stringContains('Add View Task Comment') + ); + + $this->Task->expects($this->at(6))->method('createFile') + ->with( + TMP . 'ViewTaskComments' . DS . 'admin_edit.ctp', + $this->stringContains('Edit View Task Comment') + ); + + $this->Task->expects($this->exactly(4))->method('createFile'); + $this->Task->execute(); + } + +/** + * test getting templates, make sure noTemplateActions works and prefixed template is used before generic one. + * + * @return void + */ + public function testGetTemplate() { + $result = $this->Task->getTemplate('delete'); + $this->assertFalse($result); + + $result = $this->Task->getTemplate('add'); + $this->assertEquals('form', $result); + + Configure::write('Routing.prefixes', array('admin')); + + $result = $this->Task->getTemplate('admin_add'); + $this->assertEquals('form', $result); + + $this->Task->Template->templatePaths = array( + 'test' => CAKE . 'Test' . DS . 'test_app' . DS . 'Console' . DS . 'Templates' . DS . 'test' . DS + ); + $this->Task->Template->params['theme'] = 'test'; + + $result = $this->Task->getTemplate('admin_edit'); + $this->assertEquals('admin_edit', $result); + } + +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/TestShellTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/TestShellTest.php new file mode 100644 index 0000000..5d08c58 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/Command/TestShellTest.php @@ -0,0 +1,335 @@ +_mapFileToCase($file, $category, $throwOnMissingFile); + } + + public function mapFileToCategory($file) { + return $this->_mapFileToCategory($file); + } + +} + +class TestShellTest extends CakeTestCase { + +/** + * setUp test case + * + * @return void + */ + public function setUp() { + parent::setUp(); + $out = $this->getMock('ConsoleOutput', array(), array(), '', false); + $in = $this->getMock('ConsoleInput', array(), array(), '', false); + + $this->Shell = $this->getMock( + 'TestTestShell', + array('in', 'out', 'hr', 'help', 'error', 'err', '_stop', 'initialize', '_run', 'clear'), + array($out, $out, $in) + ); + $this->Shell->OptionParser = $this->getMock('ConsoleOptionParser', array(), array(null, false)); + } + +/** + * tearDown method + * + * @return void + */ + public function tearDown() { + parent::tearDown(); + unset($this->Dispatch, $this->Shell); + } + +/** + * testMapCoreFileToCategory + * + * @return void + */ + public function testMapCoreFileToCategory() { + $this->Shell->startup(); + + $return = $this->Shell->mapFileToCategory('lib/Cake/basics.php'); + $this->assertSame('core', $return); + + $return = $this->Shell->mapFileToCategory('lib/Cake/Core/App.php'); + $this->assertSame('core', $return); + + $return = $this->Shell->mapFileToCategory('lib/Cake/Some/Deeply/Nested/Structure.php'); + $this->assertSame('core', $return); + } + +/** + * testMapCoreFileToCase + * + * basics.php is a slightly special case - it's the only file in the core with a test that isn't Capitalized + * + * @return void + */ + public function testMapCoreFileToCase() { + $this->Shell->startup(); + + $return = $this->Shell->mapFileToCase('lib/Cake/basics.php', 'core'); + $this->assertSame('Basics', $return); + + $return = $this->Shell->mapFileToCase('lib/Cake/Core/App.php', 'core'); + $this->assertSame('Core/App', $return); + + $return = $this->Shell->mapFileToCase('lib/Cake/Some/Deeply/Nested/Structure.php', 'core', false); + $this->assertSame('Some/Deeply/Nested/Structure', $return); + } + +/** + * testMapAppFileToCategory + * + * @return void + */ + public function testMapAppFileToCategory() { + $this->Shell->startup(); + + $return = $this->Shell->mapFileToCategory(APP . 'Controller/ExampleController.php'); + $this->assertSame('app', $return); + + $return = $this->Shell->mapFileToCategory(APP . 'My/File/Is/Here.php'); + $this->assertSame('app', $return); + } + +/** + * testMapAppFileToCase + * + * @return void + */ + public function testMapAppFileToCase() { + $this->Shell->startup(); + + $return = $this->Shell->mapFileToCase(APP . 'Controller/ExampleController.php', 'app', false); + $this->assertSame('Controller/ExampleController', $return); + + $return = $this->Shell->mapFileToCase(APP . 'My/File/Is/Here.php', 'app', false); + $this->assertSame('My/File/Is/Here', $return); + } + +/** + * testMapPluginFileToCategory + * + * @return void + */ + public function testMapPluginFileToCategory() { + $this->Shell->startup(); + + $return = $this->Shell->mapFileToCategory(APP . 'Plugin/awesome/Controller/ExampleController.php'); + $this->assertSame('awesome', $return); + + $return = $this->Shell->mapFileToCategory(dirname(CAKE) . 'plugins/awesome/Controller/ExampleController.php'); + $this->assertSame('awesome', $return); + } + +/** + * testMapPluginFileToCase + * + * @return void + */ + public function testMapPluginFileToCase() { + $this->Shell->startup(); + + $return = $this->Shell->mapFileToCase(APP . 'Plugin/awesome/Controller/ExampleController.php', 'awesome', false); + $this->assertSame('Controller/ExampleController', $return); + + $return = $this->Shell->mapFileToCase(dirname(CAKE) . 'plugins/awesome/Controller/ExampleController.php', 'awesome', false); + $this->assertSame('Controller/ExampleController', $return); + } + +/** + * testMapCoreTestToCategory + * + * @return void + */ + public function testMapCoreTestToCategory() { + $this->Shell->startup(); + + $return = $this->Shell->mapFileToCategory('lib/Cake/Test/Case/BasicsTest.php'); + $this->assertSame('core', $return); + + $return = $this->Shell->mapFileToCategory('lib/Cake/Test/Case/BasicsTest.php'); + $this->assertSame('core', $return); + + $return = $this->Shell->mapFileToCategory('lib/Cake/Test/Case/Some/Deeply/Nested/StructureTest.php'); + $this->assertSame('core', $return); + } + +/** + * testMapCoreTestToCase + * + * basics.php is a slightly special case - it's the only file in the core with a test that isn't Capitalized + * + * @return void + */ + public function testMapCoreTestToCase() { + $this->Shell->startup(); + + $return = $this->Shell->mapFileToCase('lib/Cake/Test/Case/BasicsTest.php', 'core'); + $this->assertSame('Basics', $return); + + $return = $this->Shell->mapFileToCase('lib/Cake/Test/Case/Core/AppTest.php', 'core'); + $this->assertSame('Core/App', $return); + + $return = $this->Shell->mapFileToCase('lib/Cake/Test/Case/Some/Deeply/Nested/StructureTest.php', 'core', false); + $this->assertSame('Some/Deeply/Nested/Structure', $return); + } + +/** + * testMapAppTestToCategory + * + * @return void + */ + public function testMapAppTestToCategory() { + $this->Shell->startup(); + + $return = $this->Shell->mapFileToCategory(APP . 'Test/Case/Controller/ExampleControllerTest.php'); + $this->assertSame('app', $return); + + $return = $this->Shell->mapFileToCategory(APP . 'Test/Case/My/File/Is/HereTest.php'); + $this->assertSame('app', $return); + } + +/** + * testMapAppTestToCase + * + * @return void + */ + public function testMapAppTestToCase() { + $this->Shell->startup(); + + $return = $this->Shell->mapFileToCase(APP . 'Test/Case/Controller/ExampleControllerTest.php', 'app', false); + $this->assertSame('Controller/ExampleController', $return); + + $return = $this->Shell->mapFileToCase(APP . 'Test/Case/My/File/Is/HereTest.php', 'app', false); + $this->assertSame('My/File/Is/Here', $return); + } + +/** + * testMapPluginTestToCategory + * + * @return void + */ + public function testMapPluginTestToCategory() { + $this->Shell->startup(); + + $return = $this->Shell->mapFileToCategory(APP . 'Plugin/awesome/Test/Case/Controller/ExampleControllerTest.php'); + $this->assertSame('awesome', $return); + + $return = $this->Shell->mapFileToCategory(dirname(CAKE) . 'plugins/awesome/Test/Case/Controller/ExampleControllerTest.php'); + $this->assertSame('awesome', $return); + } + +/** + * testMapPluginTestToCase + * + * @return void + */ + public function testMapPluginTestToCase() { + $this->Shell->startup(); + + $return = $this->Shell->mapFileToCase(APP . 'Plugin/awesome/Test/Case/Controller/ExampleControllerTest.php', 'awesome', false); + $this->assertSame('Controller/ExampleController', $return); + + $return = $this->Shell->mapFileToCase(dirname(CAKE) . 'plugins/awesome/Test/Case/Controller/ExampleControllerTest.php', 'awesome', false); + $this->assertSame('Controller/ExampleController', $return); + } + +/** + * testMapNotTestToNothing + * + * @return void + */ + public function testMapNotTestToNothing() { + $this->Shell->startup(); + + $return = $this->Shell->mapFileToCategory(APP . 'Test/Case/NotATestFile.php'); + $this->assertSame('app', $return); + + $return = $this->Shell->mapFileToCase(APP . 'Test/Case/NotATestFile.php', false, false); + $this->assertFalse($return); + + $return = $this->Shell->mapFileToCategory(APP . 'Test/Fixture/SomeTest.php'); + $this->assertSame('app', $return); + + $return = $this->Shell->mapFileToCase(APP . 'Test/Fixture/SomeTest.php', false, false); + $this->assertFalse($return); + } + +/** + * test available list of test cases for an empty category + * + * @return void + */ + public function testAvailableWithEmptyList() { + $this->Shell->startup(); + $this->Shell->args = array('unexistant-category'); + $this->Shell->expects($this->at(0))->method('out')->with(__d('cake_console', "No test cases available \n\n")); + $this->Shell->OptionParser->expects($this->once())->method('help'); + $this->Shell->available(); + } + +/** + * test available list of test cases for core category + * + * @return void + */ + public function testAvailableCoreCategory() { + $this->Shell->startup(); + $this->Shell->args = array('core'); + $this->Shell->expects($this->at(0))->method('out')->with('Core Test Cases:'); + $this->Shell->expects($this->at(1))->method('out') + ->with($this->stringContains('[1]')); + $this->Shell->expects($this->at(2))->method('out') + ->with($this->stringContains('[2]')); + + $this->Shell->expects($this->once())->method('in') + ->with(__d('cake_console', 'What test case would you like to run?'), null, 'q') + ->will($this->returnValue('1')); + + $this->Shell->expects($this->once())->method('_run'); + $this->Shell->available(); + $this->assertEquals(array('core', 'AllBehaviors'), $this->Shell->args); + } + +/** + * Tests that correct option for test runner are passed + * + * @return void + */ + public function testRunnerOptions() { + $this->Shell->startup(); + $this->Shell->args = array('core', 'Basics'); + $this->Shell->params = array('filter' => 'myFilter', 'colors' => true, 'verbose' => true); + + $this->Shell->expects($this->once())->method('_run') + ->with( + array('app' => false, 'plugin' => null, 'core' => true, 'output' => 'text', 'case' => 'Basics'), + array('--filter', 'myFilter', '--colors', '--verbose') + ); + $this->Shell->main(); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/ConsoleErrorHandlerTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/ConsoleErrorHandlerTest.php new file mode 100644 index 0000000..ef24dcb --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/ConsoleErrorHandlerTest.php @@ -0,0 +1,134 @@ +Error = $this->getMock('ConsoleErrorHandler', array('_stop')); + ConsoleErrorHandler::$stderr = $this->getMock('ConsoleOutput', array(), array(), '', false); + } + +/** + * tearDown + * + * @return void + */ + public function tearDown() { + unset($this->Error); + parent::tearDown(); + } + +/** + * test that the console error handler can deal with CakeExceptions. + * + * @return void + */ + public function testHandleError() { + $content = "Notice Error: This is a notice error in [/some/file, line 275]\n"; + ConsoleErrorHandler::$stderr->expects($this->once())->method('write') + ->with($content); + + $this->Error->handleError(E_NOTICE, 'This is a notice error', '/some/file', 275); + } + +/** + * test that the console error handler can deal with CakeExceptions. + * + * @return void + */ + public function testCakeErrors() { + $exception = new MissingActionException('Missing action'); + ConsoleErrorHandler::$stderr->expects($this->once())->method('write') + ->with($this->stringContains('Missing action')); + + $this->Error->expects($this->once()) + ->method('_stop') + ->with(404); + + $this->Error->handleException($exception); + } + +/** + * test a non CakeException exception. + * + * @return void + */ + public function testNonCakeExceptions() { + $exception = new InvalidArgumentException('Too many parameters.'); + + ConsoleErrorHandler::$stderr->expects($this->once())->method('write') + ->with($this->stringContains('Too many parameters.')); + + $this->Error->expects($this->once()) + ->method('_stop') + ->with(1); + + $this->Error->handleException($exception); + } + +/** + * test a Error404 exception. + * + * @return void + */ + public function testError404Exception() { + $exception = new NotFoundException('dont use me in cli.'); + + ConsoleErrorHandler::$stderr->expects($this->once())->method('write') + ->with($this->stringContains('dont use me in cli.')); + + $this->Error->expects($this->once()) + ->method('_stop') + ->with(404); + + $this->Error->handleException($exception); + } + +/** + * test a Error500 exception. + * + * @return void + */ + public function testError500Exception() { + $exception = new InternalErrorException('dont use me in cli.'); + + ConsoleErrorHandler::$stderr->expects($this->once())->method('write') + ->with($this->stringContains('dont use me in cli.')); + + $this->Error->expects($this->once()) + ->method('_stop') + ->with(500); + + $this->Error->handleException($exception); + } + +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/ConsoleOptionParserTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/ConsoleOptionParserTest.php new file mode 100644 index 0000000..0677b09 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/ConsoleOptionParserTest.php @@ -0,0 +1,594 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Console + * @since CakePHP(tm) v 2.0 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ + +App::uses('ConsoleOptionParser', 'Console'); + +class ConsoleOptionParserTest extends CakeTestCase { + +/** + * test setting the console description + * + * @return void + */ + public function testDescription() { + $parser = new ConsoleOptionParser('test', false); + $result = $parser->description('A test'); + + $this->assertEquals($parser, $result, 'Setting description is not chainable'); + $this->assertEquals('A test', $parser->description(), 'getting value is wrong.'); + + $result = $parser->description(array('A test', 'something')); + $this->assertEquals("A test\nsomething", $parser->description(), 'getting value is wrong.'); + } + +/** + * test setting the console epilog + * + * @return void + */ + public function testEpilog() { + $parser = new ConsoleOptionParser('test', false); + $result = $parser->epilog('A test'); + + $this->assertEquals($parser, $result, 'Setting epilog is not chainable'); + $this->assertEquals('A test', $parser->epilog(), 'getting value is wrong.'); + + $result = $parser->epilog(array('A test', 'something')); + $this->assertEquals("A test\nsomething", $parser->epilog(), 'getting value is wrong.'); + } + +/** + * test adding an option returns self. + * + * @return void + */ + public function testAddOptionReturnSelf() { + $parser = new ConsoleOptionParser('test', false); + $result = $parser->addOption('test'); + $this->assertEquals($parser, $result, 'Did not return $this from addOption'); + } + +/** + * test adding an option and using the long value for parsing. + * + * @return void + */ + public function testAddOptionLong() { + $parser = new ConsoleOptionParser('test', false); + $parser->addOption('test', array( + 'short' => 't' + )); + $result = $parser->parse(array('--test', 'value')); + $this->assertEquals(array('test' => 'value', 'help' => false), $result[0], 'Long parameter did not parse out'); + } + +/** + * test addOption with an object. + * + * @return void + */ + public function testAddOptionObject() { + $parser = new ConsoleOptionParser('test', false); + $parser->addOption(new ConsoleInputOption('test', 't')); + $result = $parser->parse(array('--test=value')); + $this->assertEquals(array('test' => 'value', 'help' => false), $result[0], 'Long parameter did not parse out'); + } + +/** + * test adding an option and using the long value for parsing. + * + * @return void + */ + public function testAddOptionLongEquals() { + $parser = new ConsoleOptionParser('test', false); + $parser->addOption('test', array( + 'short' => 't' + )); + $result = $parser->parse(array('--test=value')); + $this->assertEquals(array('test' => 'value', 'help' => false), $result[0], 'Long parameter did not parse out'); + } + +/** + * test adding an option and using the default. + * + * @return void + */ + public function testAddOptionDefault() { + $parser = new ConsoleOptionParser('test', false); + $parser->addOption('test', array( + 'default' => 'default value', + )); + $result = $parser->parse(array('--test')); + $this->assertEquals(array('test' => 'default value', 'help' => false), $result[0], 'Default value did not parse out'); + + $parser = new ConsoleOptionParser('test', false); + $parser->addOption('test', array( + 'default' => 'default value', + )); + $result = $parser->parse(array()); + $this->assertEquals(array('test' => 'default value', 'help' => false), $result[0], 'Default value did not parse out'); + } + +/** + * test adding an option and using the short value for parsing. + * + * @return void + */ + public function testAddOptionShort() { + $parser = new ConsoleOptionParser('test', false); + $parser->addOption('test', array( + 'short' => 't' + )); + $result = $parser->parse(array('-t', 'value')); + $this->assertEquals(array('test' => 'value', 'help' => false), $result[0], 'Short parameter did not parse out'); + } + +/** + * Test that adding an option using a two letter short value causes an exception. + * As they will not parse correctly. + * + * @expectedException ConsoleException + * @return void + */ + public function testAddOptionShortOneLetter() { + $parser = new ConsoleOptionParser('test', false); + $parser->addOption('test', array('short' => 'te')); + } + +/** + * test adding and using boolean options. + * + * @return void + */ + public function testAddOptionBoolean() { + $parser = new ConsoleOptionParser('test', false); + $parser->addOption('test', array( + 'boolean' => true, + )); + + $result = $parser->parse(array('--test', 'value')); + $expected = array(array('test' => true, 'help' => false), array('value')); + $this->assertEquals($expected, $result); + + $result = $parser->parse(array('value')); + $expected = array(array('test' => false, 'help' => false), array('value')); + $this->assertEquals($expected, $result); + } + +/** + * test adding an multiple shorts. + * + * @return void + */ + public function testAddOptionMultipleShort() { + $parser = new ConsoleOptionParser('test', false); + $parser->addOption('test', array('short' => 't', 'boolean' => true)) + ->addOption('file', array('short' => 'f', 'boolean' => true)) + ->addOption('output', array('short' => 'o', 'boolean' => true)); + + $result = $parser->parse(array('-o', '-t', '-f')); + $expected = array('file' => true, 'test' => true, 'output' => true, 'help' => false); + $this->assertEquals($expected, $result[0], 'Short parameter did not parse out'); + + $result = $parser->parse(array('-otf')); + $this->assertEquals($expected, $result[0], 'Short parameter did not parse out'); + } + +/** + * test multiple options at once. + * + * @return void + */ + public function testMultipleOptions() { + $parser = new ConsoleOptionParser('test', false); + $parser->addOption('test') + ->addOption('connection') + ->addOption('table', array('short' => 't', 'default' => true)); + + $result = $parser->parse(array('--test', 'value', '-t', '--connection', 'postgres')); + $expected = array('test' => 'value', 'table' => true, 'connection' => 'postgres', 'help' => false); + $this->assertEquals($expected, $result[0], 'multiple options did not parse'); + } + +/** + * Test adding multiple options. + * + * @return void + */ + public function testAddOptions() { + $parser = new ConsoleOptionParser('something', false); + $result = $parser->addOptions(array( + 'name' => array('help' => 'The name'), + 'other' => array('help' => 'The other arg') + )); + $this->assertEquals($parser, $result, 'addOptions is not chainable.'); + + $result = $parser->options(); + $this->assertEquals(3, count($result), 'Not enough options'); + } + +/** + * test that boolean options work + * + * @return void + */ + public function testOptionWithBooleanParam() { + $parser = new ConsoleOptionParser('test', false); + $parser->addOption('no-commit', array('boolean' => true)) + ->addOption('table', array('short' => 't')); + + $result = $parser->parse(array('--table', 'posts', '--no-commit', 'arg1', 'arg2')); + $expected = array(array('table' => 'posts', 'no-commit' => true, 'help' => false), array('arg1', 'arg2')); + $this->assertEquals($expected, $result, 'Boolean option did not parse correctly.'); + } + +/** + * test parsing options that do not exist. + * + * @expectedException ConsoleException + */ + public function testOptionThatDoesNotExist() { + $parser = new ConsoleOptionParser('test', false); + $parser->addOption('no-commit', array('boolean' => true)); + + $result = $parser->parse(array('--fail', 'other')); + } + +/** + * test parsing short options that do not exist. + * + * @expectedException ConsoleException + */ + public function testShortOptionThatDoesNotExist() { + $parser = new ConsoleOptionParser('test', false); + $parser->addOption('no-commit', array('boolean' => true)); + + $result = $parser->parse(array('-f')); + } + +/** + * test that options with choices enforce them. + * + * @expectedException ConsoleException + * @return void + */ + public function testOptionWithChoices() { + $parser = new ConsoleOptionParser('test', false); + $parser->addOption('name', array('choices' => array('mark', 'jose'))); + + $result = $parser->parse(array('--name', 'mark')); + $expected = array('name' => 'mark', 'help' => false); + $this->assertEquals($expected, $result[0], 'Got the correct value.'); + + $result = $parser->parse(array('--name', 'jimmy')); + } + +/** + * Ensure that option values can start with - + * + * @return void + */ + public function testOptionWithValueStartingWithMinus() { + $parser = new ConsoleOptionParser('test', false); + $parser->addOption('name') + ->addOption('age'); + + $result = $parser->parse(array('--name', '-foo', '--age', 'old')); + $expected = array('name' => '-foo', 'age' => 'old', 'help' => false); + $this->assertEquals($expected, $result[0], 'Option values starting with "-" are broken.'); + } + +/** + * test positional argument parsing. + * + * @return void + */ + public function testPositionalArgument() { + $parser = new ConsoleOptionParser('test', false); + $result = $parser->addArgument('name', array('help' => 'An argument')); + $this->assertEquals($parser, $result, 'Should return this'); + } + +/** + * test addOption with an object. + * + * @return void + */ + public function testAddArgumentObject() { + $parser = new ConsoleOptionParser('test', false); + $parser->addArgument(new ConsoleInputArgument('test')); + $result = $parser->arguments(); + $this->assertEquals(1, count($result)); + $this->assertEquals('test', $result[0]->name()); + } + +/** + * test overwriting positional arguments. + * + * @return void + */ + public function testPositionalArgOverwrite() { + $parser = new ConsoleOptionParser('test', false); + $parser->addArgument('name', array('help' => 'An argument')) + ->addArgument('other', array('index' => 0)); + + $result = $parser->arguments(); + $this->assertEquals(1, count($result), 'Overwrite did not occur'); + } + +/** + * test parsing arguments. + * + * @expectedException ConsoleException + * @return void + */ + public function testParseArgumentTooMany() { + $parser = new ConsoleOptionParser('test', false); + $parser->addArgument('name', array('help' => 'An argument')) + ->addArgument('other'); + + $expected = array('one', 'two'); + $result = $parser->parse($expected); + $this->assertEquals($expected, $result[1], 'Arguments are not as expected'); + + $result = $parser->parse(array('one', 'two', 'three')); + } + +/** + * test parsing arguments with 0 value. + * + * @return void + */ + public function testParseArgumentZero() { + $parser = new ConsoleOptionParser('test', false); + + $expected = array('one', 'two', 0, 'after', 'zero'); + $result = $parser->parse($expected); + $this->assertEquals($expected, $result[1], 'Arguments are not as expected'); + } + +/** + * test that when there are not enough arguments an exception is raised + * + * @expectedException ConsoleException + * @return void + */ + public function testPositionalArgNotEnough() { + $parser = new ConsoleOptionParser('test', false); + $parser->addArgument('name', array('required' => true)) + ->addArgument('other', array('required' => true)); + + $parser->parse(array('one')); + } + +/** + * test that arguments with choices enforce them. + * + * @expectedException ConsoleException + * @return void + */ + public function testPositionalArgWithChoices() { + $parser = new ConsoleOptionParser('test', false); + $parser->addArgument('name', array('choices' => array('mark', 'jose'))) + ->addArgument('alias', array('choices' => array('cowboy', 'samurai'))) + ->addArgument('weapon', array('choices' => array('gun', 'sword'))); + + $result = $parser->parse(array('mark', 'samurai', 'sword')); + $expected = array('mark', 'samurai', 'sword'); + $this->assertEquals($expected, $result[1], 'Got the correct value.'); + + $result = $parser->parse(array('jose', 'coder')); + } + +/** + * Test adding multiple arguments. + * + * @return void + */ + public function testAddArguments() { + $parser = new ConsoleOptionParser('test', false); + $result = $parser->addArguments(array( + 'name' => array('help' => 'The name'), + 'other' => array('help' => 'The other arg') + )); + $this->assertEquals($parser, $result, 'addArguments is not chainable.'); + + $result = $parser->arguments(); + $this->assertEquals(2, count($result), 'Not enough arguments'); + } + +/** + * test setting a subcommand up. + * + * @return void + */ + public function testSubcommand() { + $parser = new ConsoleOptionParser('test', false); + $result = $parser->addSubcommand('initdb', array( + 'help' => 'Initialize the database' + )); + $this->assertEquals($parser, $result, 'Adding a subcommand is not chainable'); + } + +/** + * test addSubcommand with an object. + * + * @return void + */ + public function testAddSubcommandObject() { + $parser = new ConsoleOptionParser('test', false); + $parser->addSubcommand(new ConsoleInputSubcommand('test')); + $result = $parser->subcommands(); + $this->assertEquals(1, count($result)); + $this->assertEquals('test', $result['test']->name()); + } + +/** + * test adding multiple subcommands + * + * @return void + */ + public function testAddSubcommands() { + $parser = new ConsoleOptionParser('test', false); + $result = $parser->addSubcommands(array( + 'initdb' => array('help' => 'Initialize the database'), + 'create' => array('help' => 'Create something') + )); + $this->assertEquals($parser, $result, 'Adding a subcommands is not chainable'); + $result = $parser->subcommands(); + $this->assertEquals(2, count($result), 'Not enough subcommands'); + } + +/** + * test that no exception is triggered when help is being generated + * + * @return void + */ + public function testHelpNoExceptionWhenGettingHelp() { + $parser = new ConsoleOptionParser('mycommand', false); + $parser->addOption('test', array('help' => 'A test option.')) + ->addArgument('model', array('help' => 'The model to make.', 'required' => true)); + + $result = $parser->parse(array('--help')); + $this->assertTrue($result[0]['help']); + } + +/** + * test that help() with a command param shows the help for a subcommand + * + * @return void + */ + public function testHelpSubcommandHelp() { + $subParser = new ConsoleOptionParser('method', false); + $subParser->addOption('connection', array('help' => 'Db connection.')); + + $parser = new ConsoleOptionParser('mycommand', false); + $parser->addSubcommand('method', array( + 'help' => 'This is another command', + 'parser' => $subParser + )) + ->addOption('test', array('help' => 'A test option.')); + + $result = $parser->help('method'); + $expected = <<Usage: +cake mycommand method [-h] [--connection] + +Options: + +--help, -h Display this help. +--connection Db connection. + +TEXT; + $this->assertTextEquals($expected, $result, 'Help is not correct.'); + } + +/** + * test building a parser from an array. + * + * @return void + */ + public function testBuildFromArray() { + $spec = array( + 'command' => 'test', + 'arguments' => array( + 'name' => array('help' => 'The name'), + 'other' => array('help' => 'The other arg') + ), + 'options' => array( + 'name' => array('help' => 'The name'), + 'other' => array('help' => 'The other arg') + ), + 'subcommands' => array( + 'initdb' => array('help' => 'make database') + ), + 'description' => 'description text', + 'epilog' => 'epilog text' + ); + $parser = ConsoleOptionParser::buildFromArray($spec); + + $this->assertEquals($spec['description'], $parser->description()); + $this->assertEquals($spec['epilog'], $parser->epilog()); + + $options = $parser->options(); + $this->assertTrue(isset($options['name'])); + $this->assertTrue(isset($options['other'])); + + $args = $parser->arguments(); + $this->assertEquals(2, count($args)); + + $commands = $parser->subcommands(); + $this->assertEquals(1, count($commands)); + } + +/** + * test that create() returns instances + * + * @return void + */ + public function testCreateFactory() { + $parser = ConsoleOptionParser::create('factory', false); + $this->assertInstanceOf('ConsoleOptionParser', $parser); + $this->assertEquals('factory', $parser->command()); + } + +/** + * test that command() inflects the command name. + * + * @return void + */ + public function testCommandInflection() { + $parser = new ConsoleOptionParser('CommandLine'); + $this->assertEquals('command_line', $parser->command()); + } + +/** + * test that parse() takes a subcommand argument, and that the subcommand parser + * is used. + * + * @return void + */ + public function testParsingWithSubParser() { + $parser = new ConsoleOptionParser('test', false); + $parser->addOption('primary') + ->addArgument('one', array('required' => true, 'choices' => array('a', 'b'))) + ->addArgument('two', array('required' => true)) + ->addSubcommand('sub', array( + 'parser' => array( + 'options' => array( + 'secondary' => array('boolean' => true), + 'fourth' => array('help' => 'fourth option') + ), + 'arguments' => array( + 'sub_arg' => array('choices' => array('c', 'd')) + ) + ) + )); + + $result = $parser->parse(array('--secondary', '--fourth', '4', 'c'), 'sub'); + $expected = array(array( + 'secondary' => true, + 'fourth' => '4', + 'help' => false, + 'verbose' => false, + 'quiet' => false), array('c')); + $this->assertEquals($expected, $result, 'Sub parser did not parse request.'); + } + +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/ConsoleOutputTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/ConsoleOutputTest.php new file mode 100644 index 0000000..a9cd056 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/ConsoleOutputTest.php @@ -0,0 +1,242 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Console + * @since CakePHP(tm) v 1.2.0.5432 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ + +App::uses('ConsoleOutput', 'Console'); + +class ConsoleOutputTest extends CakeTestCase { + +/** + * setup + * + * @return void + */ + public function setUp() { + parent::setUp(); + $this->output = $this->getMock('ConsoleOutput', array('_write')); + $this->output->outputAs(ConsoleOutput::COLOR); + } + +/** + * tearDown + * + * @return void + */ + public function tearDown() { + parent::tearDown(); + unset($this->output); + } + +/** + * test writing with no new line + * + * @return void + */ + public function testWriteNoNewLine() { + $this->output->expects($this->once())->method('_write') + ->with('Some output'); + + $this->output->write('Some output', false); + } + +/** + * test writing with no new line + * + * @return void + */ + public function testWriteNewLine() { + $this->output->expects($this->once())->method('_write') + ->with('Some output' . PHP_EOL); + + $this->output->write('Some output'); + } + +/** + * test write() with multiple new lines + * + * @return void + */ + public function testWriteMultipleNewLines() { + $this->output->expects($this->once())->method('_write') + ->with('Some output' . PHP_EOL . PHP_EOL . PHP_EOL . PHP_EOL); + + $this->output->write('Some output', 4); + } + +/** + * test writing an array of messages. + * + * @return void + */ + public function testWriteArray() { + $this->output->expects($this->once())->method('_write') + ->with('Line' . PHP_EOL . 'Line' . PHP_EOL . 'Line' . PHP_EOL); + + $this->output->write(array('Line', 'Line', 'Line')); + } + +/** + * test getting a style. + * + * @return void + */ + public function testStylesGet() { + $result = $this->output->styles('error'); + $expected = array('text' => 'red', 'underline' => true); + $this->assertEquals($expected, $result); + + $this->assertNull($this->output->styles('made_up_goop')); + + $result = $this->output->styles(); + $this->assertNotEmpty($result, 'error', 'Error is missing'); + $this->assertNotEmpty($result, 'warning', 'Warning is missing'); + } + +/** + * test adding a style. + * + * @return void + */ + public function testStylesAdding() { + $this->output->styles('test', array('text' => 'red', 'background' => 'black')); + $result = $this->output->styles('test'); + $expected = array('text' => 'red', 'background' => 'black'); + $this->assertEquals($expected, $result); + + $this->assertTrue($this->output->styles('test', false), 'Removing a style should return true.'); + $this->assertNull($this->output->styles('test'), 'Removed styles should be null.'); + } + +/** + * test formatting text with styles. + * + * @return void + */ + public function testFormattingSimple() { + $this->output->expects($this->once())->method('_write') + ->with("\033[31;4mError:\033[0m Something bad"); + + $this->output->write('Error: Something bad', false); + } + +/** + * test that formatting doesn't eat tags it doesn't know about. + * + * @return void + */ + public function testFormattingNotEatingTags() { + $this->output->expects($this->once())->method('_write') + ->with(" Something bad"); + + $this->output->write(' Something bad', false); + } + +/** + * test formatting with custom styles. + * + * @return void + */ + public function testFormattingCustom() { + $this->output->styles('annoying', array( + 'text' => 'magenta', + 'background' => 'cyan', + 'blink' => true, + 'underline' => true + )); + + $this->output->expects($this->once())->method('_write') + ->with("\033[35;46;5;4mAnnoy:\033[0m Something bad"); + + $this->output->write('Annoy: Something bad', false); + } + +/** + * test formatting text with missing styles. + * + * @return void + */ + public function testFormattingMissingStyleName() { + $this->output->expects($this->once())->method('_write') + ->with("Error: Something bad"); + + $this->output->write('Error: Something bad', false); + } + +/** + * test formatting text with multiple styles. + * + * @return void + */ + public function testFormattingMultipleStylesName() { + $this->output->expects($this->once())->method('_write') + ->with("\033[31;4mBad\033[0m \033[33mWarning\033[0m Regular"); + + $this->output->write('Bad Warning Regular', false); + } + +/** + * test that multiple tags of the same name work in one string. + * + * @return void + */ + public function testFormattingMultipleSameTags() { + $this->output->expects($this->once())->method('_write') + ->with("\033[31;4mBad\033[0m \033[31;4mWarning\033[0m Regular"); + + $this->output->write('Bad Warning Regular', false); + } + +/** + * test raw output not getting tags replaced. + * + * @return void + */ + public function testOutputAsRaw() { + $this->output->outputAs(ConsoleOutput::RAW); + $this->output->expects($this->once())->method('_write') + ->with('Bad Regular'); + + $this->output->write('Bad Regular', false); + } + +/** + * test plain output. + * + * @return void + */ + public function testOutputAsPlain() { + $this->output->outputAs(ConsoleOutput::PLAIN); + $this->output->expects($this->once())->method('_write') + ->with('Bad Regular'); + + $this->output->write('Bad Regular', false); + } + +/** + * test plain output only strips tags used for formatting. + * + * @return void + */ + public function testOutputAsPlainSelectiveTagRemoval() { + $this->output->outputAs(ConsoleOutput::PLAIN); + $this->output->expects($this->once())->method('_write') + ->with('Bad Regular Left behind '); + + $this->output->write('Bad Regular Left behind ', false); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/HelpFormatterTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/HelpFormatterTest.php new file mode 100644 index 0000000..7af5c1e --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/HelpFormatterTest.php @@ -0,0 +1,505 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Console + * @since CakePHP(tm) v 2.0 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ + +App::uses('ConsoleOptionParser', 'Console'); +App::uses('HelpFormatter', 'Console'); + +class HelpFormatterTest extends CakeTestCase { + +/** + * test that the console max width is respected when generating help. + * + * @return void + */ + public function testWidthFormatting() { + $parser = new ConsoleOptionParser('test', false); + $parser->description('This is fifteen This is fifteen This is fifteen') + ->addOption('four', array('help' => 'this is help text this is help text')) + ->addArgument('four', array('help' => 'this is help text this is help text')) + ->addSubcommand('four', array('help' => 'this is help text this is help text')); + + $formatter = new HelpFormatter($parser); + $result = $formatter->text(30); + $expected = <<Usage: +cake test [subcommand] [-h] [--four] [] + +Subcommands: + +four this is help text this + is help text + +To see help on a subcommand use `cake test [subcommand] --help` + +Options: + +--help, -h Display this help. +--four this is help text + this is help text + +Arguments: + +four this is help text this + is help text + (optional) + +TEXT; + $this->assertTextEquals($expected, $result, 'Generated help is too wide'); + } + +/** + * test help() with options and arguments that have choices. + * + * @return void + */ + public function testHelpWithChoices() { + $parser = new ConsoleOptionParser('mycommand', false); + $parser->addOption('test', array('help' => 'A test option.', 'choices' => array('one', 'two'))) + ->addArgument('type', array( + 'help' => 'Resource type.', + 'choices' => array('aco', 'aro'), + 'required' => true + )) + ->addArgument('other_longer', array('help' => 'Another argument.')); + + $formatter = new HelpFormatter($parser); + $result = $formatter->text(); + $expected = <<Usage: +cake mycommand [-h] [--test one|two] [] + +Options: + +--help, -h Display this help. +--test A test option. (choices: one|two) + +Arguments: + +type Resource type. (choices: aco|aro) +other_longer Another argument. (optional) + +TEXT; + $this->assertTextEquals($expected, $result, 'Help does not match'); + } + +/** + * test description and epilog in the help + * + * @return void + */ + public function testHelpDescriptionAndEpilog() { + $parser = new ConsoleOptionParser('mycommand', false); + $parser->description('Description text') + ->epilog('epilog text') + ->addOption('test', array('help' => 'A test option.')) + ->addArgument('model', array('help' => 'The model to make.', 'required' => true)); + + $formatter = new HelpFormatter($parser); + $result = $formatter->text(); + $expected = <<Usage: +cake mycommand [-h] [--test] + +Options: + +--help, -h Display this help. +--test A test option. + +Arguments: + +model The model to make. + +epilog text + +TEXT; + $this->assertTextEquals($expected, $result, 'Help is wrong.'); + } + +/** + * test that help() outputs subcommands. + * + * @return void + */ + public function testHelpSubcommand() { + $parser = new ConsoleOptionParser('mycommand', false); + $parser->addSubcommand('method', array('help' => 'This is another command')) + ->addOption('test', array('help' => 'A test option.')); + + $formatter = new HelpFormatter($parser); + $result = $formatter->text(); + $expected = <<Usage: +cake mycommand [subcommand] [-h] [--test] + +Subcommands: + +method This is another command + +To see help on a subcommand use `cake mycommand [subcommand] --help` + +Options: + +--help, -h Display this help. +--test A test option. + +TEXT; + $this->assertTextEquals($expected, $result, 'Help is not correct.'); + } + +/** + * test getting help with defined options. + * + * @return void + */ + public function testHelpWithOptions() { + $parser = new ConsoleOptionParser('mycommand', false); + $parser->addOption('test', array('help' => 'A test option.')) + ->addOption('connection', array( + 'short' => 'c', 'help' => 'The connection to use.', 'default' => 'default' + )); + + $formatter = new HelpFormatter($parser); + $result = $formatter->text(); + $expected = <<Usage: +cake mycommand [-h] [--test] [-c default] + +Options: + +--help, -h Display this help. +--test A test option. +--connection, -c The connection to use. (default: + default) + +TEXT; + $this->assertTextEquals($expected, $result, 'Help does not match'); + } + +/** + * test getting help with defined options. + * + * @return void + */ + public function testHelpWithOptionsAndArguments() { + $parser = new ConsoleOptionParser('mycommand', false); + $parser->addOption('test', array('help' => 'A test option.')) + ->addArgument('model', array('help' => 'The model to make.', 'required' => true)) + ->addArgument('other_longer', array('help' => 'Another argument.')); + + $formatter = new HelpFormatter($parser); + $result = $formatter->text(); + $expected = <<Usage: +cake mycommand [-h] [--test] [] + +Options: + +--help, -h Display this help. +--test A test option. + +Arguments: + +model The model to make. +other_longer Another argument. (optional) + +TEXT; + $this->assertTextEquals($expected, $result, 'Help does not match'); + } + +/** + * Test that a long set of options doesn't make useless output. + * + * @return void + */ + public function testHelpWithLotsOfOptions() { + $parser = new ConsoleOptionParser('mycommand', false); + $parser + ->addOption('test', array('help' => 'A test option.')) + ->addOption('test2', array('help' => 'A test option.')) + ->addOption('test3', array('help' => 'A test option.')) + ->addOption('test4', array('help' => 'A test option.')) + ->addOption('test5', array('help' => 'A test option.')) + ->addOption('test6', array('help' => 'A test option.')) + ->addOption('test7', array('help' => 'A test option.')) + ->addArgument('model', array('help' => 'The model to make.', 'required' => true)) + ->addArgument('other_longer', array('help' => 'Another argument.')); + + $formatter = new HelpFormatter($parser); + $result = $formatter->text(); + $expected = 'cake mycommand [options] []'; + $this->assertContains($expected, $result); + } + +/** + * Test that a long set of arguments doesn't make useless output. + * + * @return void + */ + public function testHelpWithLotsOfArguments() { + $parser = new ConsoleOptionParser('mycommand', false); + $parser + ->addArgument('test', array('help' => 'A test option.')) + ->addArgument('test2', array('help' => 'A test option.')) + ->addArgument('test3', array('help' => 'A test option.')) + ->addArgument('test4', array('help' => 'A test option.')) + ->addArgument('test5', array('help' => 'A test option.')) + ->addArgument('test6', array('help' => 'A test option.')) + ->addArgument('test7', array('help' => 'A test option.')) + ->addArgument('model', array('help' => 'The model to make.', 'required' => true)) + ->addArgument('other_longer', array('help' => 'Another argument.')); + + $formatter = new HelpFormatter($parser); + $result = $formatter->text(); + $expected = 'cake mycommand [-h] [arguments]'; + $this->assertContains($expected, $result); + } + +/** + * test help() with options and arguments that have choices. + * + * @return void + */ + public function testXmlHelpWithChoices() { + $parser = new ConsoleOptionParser('mycommand', false); + $parser->addOption('test', array('help' => 'A test option.', 'choices' => array('one', 'two'))) + ->addArgument('type', array( + 'help' => 'Resource type.', + 'choices' => array('aco', 'aro'), + 'required' => true + )) + ->addArgument('other_longer', array('help' => 'Another argument.')); + + $formatter = new HelpFormatter($parser); + $result = $formatter->xml(); + $expected = << + +mycommand +Description text + + + + + + + + + aco + aro + + + +epilog text + +TEXT; + $this->assertEquals(new DomDocument($expected), new DomDocument($result), 'Help does not match'); + } + +/** + * test description and epilog in the help + * + * @return void + */ + public function testXmlHelpDescriptionAndEpilog() { + $parser = new ConsoleOptionParser('mycommand', false); + $parser->description('Description text') + ->epilog('epilog text') + ->addOption('test', array('help' => 'A test option.')) + ->addArgument('model', array('help' => 'The model to make.', 'required' => true)); + + $formatter = new HelpFormatter($parser); + $result = $formatter->xml(); + $expected = << + +mycommand +Description text + + + + + + + + + + +epilog text + +TEXT; + $this->assertEquals(new DomDocument($expected), new DomDocument($result), 'Help does not match'); + } + +/** + * test that help() outputs subcommands. + * + * @return void + */ + public function testXmlHelpSubcommand() { + $parser = new ConsoleOptionParser('mycommand', false); + $parser->addSubcommand('method', array('help' => 'This is another command')) + ->addOption('test', array('help' => 'A test option.')); + + $formatter = new HelpFormatter($parser); + $result = $formatter->xml(); + $expected = << + +mycommand + + + + + + + + + + + +TEXT; + $this->assertEquals(new DomDocument($expected), new DomDocument($result), 'Help does not match'); + } + +/** + * test getting help with defined options. + * + * @return void + */ + public function testXmlHelpWithOptions() { + $parser = new ConsoleOptionParser('mycommand', false); + $parser->addOption('test', array('help' => 'A test option.')) + ->addOption('connection', array( + 'short' => 'c', 'help' => 'The connection to use.', 'default' => 'default' + )); + + $formatter = new HelpFormatter($parser); + $result = $formatter->xml(); + $expected = << + +mycommand + + + + + + + + + + +TEXT; + $this->assertEquals(new DomDocument($expected), new DomDocument($result), 'Help does not match'); + } + +/** + * test getting help with defined options. + * + * @return void + */ + public function testXmlHelpWithOptionsAndArguments() { + $parser = new ConsoleOptionParser('mycommand', false); + $parser->addOption('test', array('help' => 'A test option.')) + ->addArgument('model', array('help' => 'The model to make.', 'required' => true)) + ->addArgument('other_longer', array('help' => 'Another argument.')); + + $formatter = new HelpFormatter($parser); + $result = $formatter->xml(); + $expected = << + + mycommand + + + + + + + + + + + + + + + + +TEXT; + $this->assertEquals(new DomDocument($expected), new DomDocument($result), 'Help does not match'); + } + +/** + * Test xml help as object + * + * @return void + */ + public function testXmlHelpAsObject() { + $parser = new ConsoleOptionParser('mycommand', false); + $parser->addOption('test', array('help' => 'A test option.')) + ->addArgument('model', array('help' => 'The model to make.', 'required' => true)) + ->addArgument('other_longer', array('help' => 'Another argument.')); + + $formatter = new HelpFormatter($parser); + $result = $formatter->xml(false); + $this->assertInstanceOf('SimpleXmlElement', $result); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/ShellDispatcherTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/ShellDispatcherTest.php new file mode 100644 index 0000000..c115b9d --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/ShellDispatcherTest.php @@ -0,0 +1,576 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Console + * @since CakePHP(tm) v 1.2.0.5432 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ + +App::uses('ShellDispatcher', 'Console'); + +/** + * TestShellDispatcher class + * + * @package Cake.Test.Case.Console + */ +class TestShellDispatcher extends ShellDispatcher { + +/** + * params property + * + * @var array + */ + public $params = array(); + +/** + * stopped property + * + * @var string + */ + public $stopped = null; + +/** + * TestShell + * + * @var mixed + */ + public $TestShell; + +/** + * _initEnvironment method + * + * @return void + */ + protected function _initEnvironment() { + } + +/** + * clear method + * + * @return void + */ + public function clear() { + } + +/** + * _stop method + * + * @return void + */ + protected function _stop($status = 0) { + $this->stopped = 'Stopped with status: ' . $status; + return $status; + } + +/** + * getShell + * + * @param string $shell + * @return mixed + */ + public function getShell($shell) { + return $this->_getShell($shell); + } + +/** + * _getShell + * + * @param string $plugin + * @return mixed + */ + protected function _getShell($shell) { + if (isset($this->TestShell)) { + return $this->TestShell; + } + return parent::_getShell($shell); + } + +} + +/** + * ShellDispatcherTest + * + * @package Cake.Test.Case.Console + */ +class ShellDispatcherTest extends CakeTestCase { + +/** + * setUp method + * + * @return void + */ + public function setUp() { + parent::setUp(); + App::build(array( + 'Plugin' => array( + CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS + ), + 'Console/Command' => array( + CAKE . 'Test' . DS . 'test_app' . DS . 'Console' . DS . 'Command' . DS + ) + ), App::RESET); + CakePlugin::load('TestPlugin'); + } + +/** + * tearDown method + * + * @return void + */ + public function tearDown() { + parent::tearDown(); + CakePlugin::unload(); + } + +/** + * testParseParams method + * + * @return void + */ + public function testParseParams() { + $Dispatcher = new TestShellDispatcher(); + + $params = array( + '/cake/1.2.x.x/cake/console/cake.php', + 'bake', + '-app', + 'new', + '-working', + '/var/www/htdocs' + ); + $expected = array( + 'app' => 'new', + 'webroot' => 'webroot', + 'working' => str_replace('/', DS, '/var/www/htdocs/new'), + 'root' => str_replace('/', DS,'/var/www/htdocs') + ); + $Dispatcher->parseParams($params); + $this->assertEquals($expected, $Dispatcher->params); + + $params = array('cake.php'); + $expected = array( + 'app' => 'app', + 'webroot' => 'webroot', + 'working' => str_replace('\\', DS, dirname(CAKE_CORE_INCLUDE_PATH) . DS . 'app'), + 'root' => str_replace('\\', DS, dirname(CAKE_CORE_INCLUDE_PATH)), + ); + $Dispatcher->params = $Dispatcher->args = array(); + $Dispatcher->parseParams($params); + $this->assertEquals($expected, $Dispatcher->params); + + $params = array( + 'cake.php', + '-app', + 'new', + ); + $expected = array( + 'app' => 'new', + 'webroot' => 'webroot', + 'working' => str_replace('\\', DS, dirname(CAKE_CORE_INCLUDE_PATH) . DS . 'new'), + 'root' => str_replace('\\', DS, dirname(CAKE_CORE_INCLUDE_PATH)) + ); + $Dispatcher->params = $Dispatcher->args = array(); + $Dispatcher->parseParams($params); + $this->assertEquals($expected, $Dispatcher->params); + + $params = array( + './cake.php', + 'bake', + '-app', + 'new', + '-working', + '/cake/1.2.x.x/cake/console' + ); + + $expected = array( + 'app' => 'new', + 'webroot' => 'webroot', + 'working' => str_replace('\\', DS, dirname(CAKE_CORE_INCLUDE_PATH) . DS . 'new'), + 'root' => str_replace('\\', DS, dirname(CAKE_CORE_INCLUDE_PATH)) + ); + + $Dispatcher->params = $Dispatcher->args = array(); + $Dispatcher->parseParams($params); + $this->assertEquals($expected, $Dispatcher->params); + + $params = array( + './console/cake.php', + 'bake', + '-app', + 'new', + '-working', + '/cake/1.2.x.x/cake' + ); + $expected = array( + 'app' => 'new', + 'webroot' => 'webroot', + 'working' => str_replace('\\', DS, dirname(CAKE_CORE_INCLUDE_PATH) . DS . 'new'), + 'root' => str_replace('\\', DS, dirname(CAKE_CORE_INCLUDE_PATH)) + ); + $Dispatcher->params = $Dispatcher->args = array(); + $Dispatcher->parseParams($params); + $this->assertEquals($expected, $Dispatcher->params); + + $params = array( + './console/cake.php', + 'bake', + '-app', + 'new', + '-dry', + '-working', + '/cake/1.2.x.x/cake' + ); + $expected = array( + 'app' => 'new', + 'working' => str_replace('\\', DS, dirname(CAKE_CORE_INCLUDE_PATH) . DS . 'new'), + 'root' => str_replace('\\', DS, dirname(CAKE_CORE_INCLUDE_PATH)), + 'webroot' => 'webroot' + ); + $Dispatcher->params = $Dispatcher->args = array(); + $Dispatcher->parseParams($params); + $this->assertEquals($expected, $Dispatcher->params); + + $params = array( + './console/cake.php', + '-working', + '/cake/1.2.x.x/cake', + 'schema', + 'run', + 'create', + '-dry', + '-f', + '-name', + 'DbAcl' + ); + $expected = array( + 'app' => 'app', + 'webroot' => 'webroot', + 'working' => str_replace('\\', DS, dirname(CAKE_CORE_INCLUDE_PATH) . DS . 'app'), + 'root' => str_replace('\\', DS, dirname(CAKE_CORE_INCLUDE_PATH)), + ); + $Dispatcher->params = $Dispatcher->args = array(); + $Dispatcher->parseParams($params); + $this->assertEquals($expected, $Dispatcher->params); + + $expected = array( + './console/cake.php', 'schema', 'run', 'create', '-dry', '-f', '-name', 'DbAcl' + ); + $this->assertEquals($expected, $Dispatcher->args); + + $params = array( + '/cake/1.2.x.x/cake/console/cake.php', + '-working', + '/cake/1.2.x.x/app', + 'schema', + 'run', + 'create', + '-dry', + '-name', + 'DbAcl' + ); + $expected = array( + 'app' => 'app', + 'webroot' => 'webroot', + 'working' => str_replace('/', DS, '/cake/1.2.x.x/app'), + 'root' => str_replace('/', DS, '/cake/1.2.x.x'), + ); + $Dispatcher->params = $Dispatcher->args = array(); + $Dispatcher->parseParams($params); + $this->assertEquals($expected, $Dispatcher->params); + + $params = array( + 'cake.php', + '-working', + 'C:/wamp/www/cake/app', + 'bake', + '-app', + 'C:/wamp/www/apps/cake/app', + ); + $expected = array( + 'app' => 'app', + 'webroot' => 'webroot', + 'working' => 'C:\wamp\www\apps\cake\app', + 'root' => 'C:\wamp\www\apps\cake' + ); + + $Dispatcher->params = $Dispatcher->args = array(); + $Dispatcher->parseParams($params); + $this->assertEquals($expected, $Dispatcher->params); + + $params = array( + 'cake.php', + '-working', + 'C:\wamp\www\cake\app', + 'bake', + '-app', + 'C:\wamp\www\apps\cake\app', + ); + $expected = array( + 'app' => 'app', + 'webroot' => 'webroot', + 'working' => 'C:\wamp\www\apps\cake\app', + 'root' => 'C:\wamp\www\apps\cake' + ); + $Dispatcher->params = $Dispatcher->args = array(); + $Dispatcher->parseParams($params); + $this->assertEquals($expected, $Dispatcher->params); + + $params = array( + 'cake.php', + '-working', + 'C:\wamp\www\apps', + 'bake', + '-app', + 'cake\app', + '-url', + 'http://example.com/some/url/with/a/path' + ); + $expected = array( + 'app' => 'app', + 'webroot' => 'webroot', + 'working' => 'C:\wamp\www\apps\cake\app', + 'root' => 'C:\wamp\www\apps\cake', + ); + $Dispatcher->params = $Dispatcher->args = array(); + $Dispatcher->parseParams($params); + $this->assertEquals($expected, $Dispatcher->params); + + $params = array( + '/home/amelo/dev/cake-common/cake/console/cake.php', + '-root', + '/home/amelo/dev/lsbu-vacancy', + '-working', + '/home/amelo/dev/lsbu-vacancy', + '-app', + 'app', + ); + $expected = array( + 'app' => 'app', + 'webroot' => 'webroot', + 'working' => '/home/amelo/dev/lsbu-vacancy/app', + 'root' => '/home/amelo/dev/lsbu-vacancy', + ); + $Dispatcher->params = $Dispatcher->args = array(); + $Dispatcher->parseParams($params); + $this->assertEquals($expected, $Dispatcher->params); + + $params = array( + '/cake/1.2.x.x/cake/console/cake.php', + 'bake', + '-app', + 'new', + '-app', + 'old', + '-working', + '/var/www/htdocs' + ); + $expected = array( + 'app' => 'old', + 'webroot' => 'webroot', + 'working' => str_replace('/', DS, '/var/www/htdocs/old'), + 'root' => str_replace('/', DS,'/var/www/htdocs') + ); + $Dispatcher->parseParams($params); + $this->assertEquals($expected, $Dispatcher->params); + + if (DS === '\\') { + $params = array( + 'cake.php', + '-working', + 'D:\www', + 'bake', + 'my_app', + ); + $expected = array( + 'working' => 'D:\\\\www', + 'app' => 'www', + 'root' => 'D:\\', + 'webroot' => 'webroot' + ); + + $Dispatcher->params = $Dispatcher->args = array(); + $Dispatcher->parseParams($params); + $this->assertEquals($expected, $Dispatcher->params); + } + } + +/** + * Verify loading of (plugin-) shells + * + * @return void + */ + public function testGetShell() { + $this->skipIf(class_exists('SampleShell'), 'SampleShell Class already loaded.'); + $this->skipIf(class_exists('ExampleShell'), 'ExampleShell Class already loaded.'); + + $Dispatcher = new TestShellDispatcher(); + + $result = $Dispatcher->getShell('sample'); + $this->assertInstanceOf('SampleShell', $result); + + $Dispatcher = new TestShellDispatcher(); + $result = $Dispatcher->getShell('test_plugin.example'); + $this->assertInstanceOf('ExampleShell', $result); + $this->assertEquals('TestPlugin', $result->plugin); + $this->assertEquals('Example', $result->name); + + $Dispatcher = new TestShellDispatcher(); + $result = $Dispatcher->getShell('TestPlugin.example'); + $this->assertInstanceOf('ExampleShell', $result); + } + +/** + * Verify correct dispatch of Shell subclasses with a main method + * + * @return void + */ + public function testDispatchShellWithMain() { + $Dispatcher = new TestShellDispatcher(); + $Mock = $this->getMock('Shell', array(), array(), 'MockWithMainShell'); + + $Mock->expects($this->once())->method('initialize'); + $Mock->expects($this->once())->method('loadTasks'); + $Mock->expects($this->once())->method('runCommand') + ->with(null, array()) + ->will($this->returnValue(true)); + + $Dispatcher->TestShell = $Mock; + + $Dispatcher->args = array('mock_with_main'); + $result = $Dispatcher->dispatch(); + $this->assertTrue($result); + $this->assertEquals(array(), $Dispatcher->args); + } + +/** + * Verify correct dispatch of Shell subclasses without a main method + * + * @return void + */ + public function testDispatchShellWithoutMain() { + $Dispatcher = new TestShellDispatcher(); + $Shell = $this->getMock('Shell', array(), array(), 'MockWithoutMainShell'); + + $Shell = new MockWithoutMainShell(); + $this->mockObjects[] = $Shell; + + $Shell->expects($this->once())->method('initialize'); + $Shell->expects($this->once())->method('loadTasks'); + $Shell->expects($this->once())->method('runCommand') + ->with('initdb', array('initdb')) + ->will($this->returnValue(true)); + + $Dispatcher->TestShell = $Shell; + + $Dispatcher->args = array('mock_without_main', 'initdb'); + $result = $Dispatcher->dispatch(); + $this->assertTrue($result); + } + +/** + * Verify correct dispatch of custom classes with a main method + * + * @return void + */ + public function testDispatchNotAShellWithMain() { + $Dispatcher = new TestShellDispatcher(); + $methods = get_class_methods('Object'); + array_push($methods, 'main', 'initdb', 'initialize', 'loadTasks', 'startup', '_secret'); + $Shell = $this->getMock('Object', $methods, array(), 'MockWithMainNotAShell'); + + $Shell->expects($this->never())->method('initialize'); + $Shell->expects($this->never())->method('loadTasks'); + $Shell->expects($this->once())->method('startup'); + $Shell->expects($this->once())->method('main')->will($this->returnValue(true)); + $Dispatcher->TestShell = $Shell; + + $Dispatcher->args = array('mock_with_main_not_a'); + $result = $Dispatcher->dispatch(); + $this->assertTrue($result); + $this->assertEquals(array(), $Dispatcher->args); + + $Shell = new MockWithMainNotAShell($Dispatcher); + $this->mockObjects[] = $Shell; + $Shell->expects($this->once())->method('initdb')->will($this->returnValue(true)); + $Shell->expects($this->once())->method('startup'); + $Dispatcher->TestShell = $Shell; + + $Dispatcher->args = array('mock_with_main_not_a', 'initdb'); + $result = $Dispatcher->dispatch(); + $this->assertTrue($result); + } + +/** + * Verify correct dispatch of custom classes without a main method + * + * @return void + */ + public function testDispatchNotAShellWithoutMain() { + $Dispatcher = new TestShellDispatcher(); + $methods = get_class_methods('Object'); + array_push($methods, 'main', 'initdb', 'initialize', 'loadTasks', 'startup', '_secret'); + $Shell = $this->getMock('Object', $methods, array(&$Dispatcher), 'MockWithoutMainNotAShell'); + + $Shell->expects($this->never())->method('initialize'); + $Shell->expects($this->never())->method('loadTasks'); + $Shell->expects($this->once())->method('startup'); + $Shell->expects($this->once())->method('main')->will($this->returnValue(true)); + $Dispatcher->TestShell = $Shell; + + $Dispatcher->args = array('mock_without_main_not_a'); + $result = $Dispatcher->dispatch(); + $this->assertTrue($result); + $this->assertEquals(array(), $Dispatcher->args); + + $Shell = new MockWithoutMainNotAShell($Dispatcher); + $this->mockObjects[] = $Shell; + $Shell->expects($this->once())->method('initdb')->will($this->returnValue(true)); + $Shell->expects($this->once())->method('startup'); + $Dispatcher->TestShell = $Shell; + + $Dispatcher->args = array('mock_without_main_not_a', 'initdb'); + $result = $Dispatcher->dispatch(); + $this->assertTrue($result); + } + +/** + * Verify shifting of arguments + * + * @return void + */ + public function testShiftArgs() { + $Dispatcher = new TestShellDispatcher(); + + $Dispatcher->args = array('a', 'b', 'c'); + $this->assertEquals('a', $Dispatcher->shiftArgs()); + $this->assertSame($Dispatcher->args, array('b', 'c')); + + $Dispatcher->args = array('a' => 'b', 'c', 'd'); + $this->assertEquals('b', $Dispatcher->shiftArgs()); + $this->assertSame($Dispatcher->args, array('c', 'd')); + + $Dispatcher->args = array('a', 'b' => 'c', 'd'); + $this->assertEquals('a', $Dispatcher->shiftArgs()); + $this->assertSame($Dispatcher->args, array('b' => 'c', 'd')); + + $Dispatcher->args = array(0 => 'a', 2 => 'b', 30 => 'c'); + $this->assertEquals('a', $Dispatcher->shiftArgs()); + $this->assertSame($Dispatcher->args, array(0 => 'b', 1 => 'c')); + + $Dispatcher->args = array(); + $this->assertNull($Dispatcher->shiftArgs()); + $this->assertSame(array(), $Dispatcher->args); + } + +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/ShellTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/ShellTest.php new file mode 100644 index 0000000..875b23d --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/ShellTest.php @@ -0,0 +1,875 @@ +stopped = $status; + } + + protected function _secret() { + } + + //@codingStandardsIgnoreStart + public function do_something() { + } + + protected function no_access() { + } + + public function log_something() { + $this->log($this->testMessage); + } + //@codingStandardsIgnoreEnd + + public function mergeVars($properties, $class, $normalize = true) { + return $this->_mergeVars($properties, $class, $normalize); + } + + public function useLogger($enable = true) { + $this->_useLogger($enable); + } + +} + +/** + * Class for testing merging vars + * + * @package Cake.Test.Case.Console.Command + */ +class TestMergeShell extends Shell { + + public $tasks = array('DbConfig', 'Fixture'); + + public $uses = array('Comment'); + +} + +/** + * TestAppleTask class + * + * @package Cake.Test.Case.Console.Command + */ +class TestAppleTask extends Shell { +} + +/** + * TestBananaTask class + * + * @package Cake.Test.Case.Console.Command + */ +class TestBananaTask extends Shell { +} + +/** + * ShellTest class + * + * @package Cake.Test.Case.Console.Command + */ +class ShellTest extends CakeTestCase { + +/** + * Fixtures used in this test case + * + * @var array + */ + public $fixtures = array( + 'core.post', 'core.comment', 'core.article', 'core.user', + 'core.tag', 'core.articles_tag', 'core.attachment' + ); + +/** + * setUp method + * + * @return void + */ + public function setUp() { + parent::setUp(); + + $output = $this->getMock('ConsoleOutput', array(), array(), '', false); + $error = $this->getMock('ConsoleOutput', array(), array(), '', false); + $in = $this->getMock('ConsoleInput', array(), array(), '', false); + $this->Shell = new ShellTestShell($output, $error, $in); + + if (is_dir(TMP . 'shell_test')) { + $Folder = new Folder(TMP . 'shell_test'); + $Folder->delete(); + } + } + +/** + * testConstruct method + * + * @return void + */ + public function testConstruct() { + $this->assertEquals('ShellTestShell', $this->Shell->name); + $this->assertInstanceOf('ConsoleInput', $this->Shell->stdin); + $this->assertInstanceOf('ConsoleOutput', $this->Shell->stdout); + $this->assertInstanceOf('ConsoleOutput', $this->Shell->stderr); + } + +/** + * test merging vars + * + * @return void + */ + public function testMergeVars() { + $this->Shell->tasks = array('DbConfig' => array('one', 'two')); + $this->Shell->uses = array('Posts'); + $this->Shell->mergeVars(array('tasks'), 'TestMergeShell'); + $this->Shell->mergeVars(array('uses'), 'TestMergeShell', false); + + $expected = array('DbConfig' => null, 'Fixture' => null, 'DbConfig' => array('one', 'two')); + $this->assertEquals($expected, $this->Shell->tasks); + + $expected = array('Fixture' => null, 'DbConfig' => array('one', 'two')); + $this->assertEquals($expected, Hash::normalize($this->Shell->tasks), 'Normalized results are wrong.'); + $this->assertEquals(array('Comment', 'Posts'), $this->Shell->uses, 'Merged models are wrong.'); + } + +/** + * testInitialize method + * + * @return void + */ + public function testInitialize() { + App::build(array( + 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS), + 'Model' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Model' . DS) + ), App::RESET); + + CakePlugin::load('TestPlugin'); + $this->Shell->uses = array('TestPlugin.TestPluginPost'); + $this->Shell->initialize(); + + $this->assertTrue(isset($this->Shell->TestPluginPost)); + $this->assertInstanceOf('TestPluginPost', $this->Shell->TestPluginPost); + $this->assertEquals('TestPluginPost', $this->Shell->modelClass); + CakePlugin::unload('TestPlugin'); + + $this->Shell->uses = array('Comment'); + $this->Shell->initialize(); + $this->assertTrue(isset($this->Shell->Comment)); + $this->assertInstanceOf('Comment', $this->Shell->Comment); + $this->assertEquals('Comment', $this->Shell->modelClass); + + App::build(); + } + +/** + * testIn method + * + * @return void + */ + public function testIn() { + $this->Shell->stdin->expects($this->at(0)) + ->method('read') + ->will($this->returnValue('n')); + + $this->Shell->stdin->expects($this->at(1)) + ->method('read') + ->will($this->returnValue('Y')); + + $this->Shell->stdin->expects($this->at(2)) + ->method('read') + ->will($this->returnValue('y')); + + $this->Shell->stdin->expects($this->at(3)) + ->method('read') + ->will($this->returnValue('y')); + + $this->Shell->stdin->expects($this->at(4)) + ->method('read') + ->will($this->returnValue('y')); + + $this->Shell->stdin->expects($this->at(5)) + ->method('read') + ->will($this->returnValue('0')); + + $result = $this->Shell->in('Just a test?', array('y', 'n'), 'n'); + $this->assertEquals('n', $result); + + $result = $this->Shell->in('Just a test?', array('y', 'n'), 'n'); + $this->assertEquals('Y', $result); + + $result = $this->Shell->in('Just a test?', 'y,n', 'n'); + $this->assertEquals('y', $result); + + $result = $this->Shell->in('Just a test?', 'y/n', 'n'); + $this->assertEquals('y', $result); + + $result = $this->Shell->in('Just a test?', 'y', 'y'); + $this->assertEquals('y', $result); + + $result = $this->Shell->in('Just a test?', array(0, 1, 2), '0'); + $this->assertEquals('0', $result); + } + +/** + * Test in() when not interactive. + * + * @return void + */ + public function testInNonInteractive() { + $this->Shell->interactive = false; + + $result = $this->Shell->in('Just a test?', 'y/n', 'n'); + $this->assertEquals('n', $result); + } + +/** + * testOut method + * + * @return void + */ + public function testOut() { + $this->Shell->stdout->expects($this->at(0)) + ->method('write') + ->with("Just a test", 1); + + $this->Shell->stdout->expects($this->at(1)) + ->method('write') + ->with(array('Just', 'a', 'test'), 1); + + $this->Shell->stdout->expects($this->at(2)) + ->method('write') + ->with(array('Just', 'a', 'test'), 2); + + $this->Shell->stdout->expects($this->at(3)) + ->method('write') + ->with('', 1); + + $this->Shell->out('Just a test'); + + $this->Shell->out(array('Just', 'a', 'test')); + + $this->Shell->out(array('Just', 'a', 'test'), 2); + + $this->Shell->out(); + } + +/** + * test that verbose and quiet output levels work + * + * @return void + */ + public function testVerboseOutput() { + $this->Shell->stdout->expects($this->at(0))->method('write') + ->with('Verbose', 1); + $this->Shell->stdout->expects($this->at(1))->method('write') + ->with('Normal', 1); + $this->Shell->stdout->expects($this->at(2))->method('write') + ->with('Quiet', 1); + + $this->Shell->params['verbose'] = true; + $this->Shell->params['quiet'] = false; + + $this->Shell->out('Verbose', 1, Shell::VERBOSE); + $this->Shell->out('Normal', 1, Shell::NORMAL); + $this->Shell->out('Quiet', 1, Shell::QUIET); + } + +/** + * test that verbose and quiet output levels work + * + * @return void + */ + public function testQuietOutput() { + $this->Shell->stdout->expects($this->once())->method('write') + ->with('Quiet', 1); + + $this->Shell->params['verbose'] = false; + $this->Shell->params['quiet'] = true; + + $this->Shell->out('Verbose', 1, Shell::VERBOSE); + $this->Shell->out('Normal', 1, Shell::NORMAL); + $this->Shell->out('Quiet', 1, Shell::QUIET); + } + +/** + * testErr method + * + * @return void + */ + public function testErr() { + $this->Shell->stderr->expects($this->at(0)) + ->method('write') + ->with("Just a test", 1); + + $this->Shell->stderr->expects($this->at(1)) + ->method('write') + ->with(array('Just', 'a', 'test'), 1); + + $this->Shell->stderr->expects($this->at(2)) + ->method('write') + ->with(array('Just', 'a', 'test'), 2); + + $this->Shell->stderr->expects($this->at(3)) + ->method('write') + ->with('', 1); + + $this->Shell->err('Just a test'); + + $this->Shell->err(array('Just', 'a', 'test')); + + $this->Shell->err(array('Just', 'a', 'test'), 2); + + $this->Shell->err(); + } + +/** + * testNl + * + * @return void + */ + public function testNl() { + $newLine = "\n"; + if (DS === '\\') { + $newLine = "\r\n"; + } + $this->assertEquals($this->Shell->nl(), $newLine); + $this->assertEquals($this->Shell->nl(true), $newLine); + $this->assertEquals("", $this->Shell->nl(false)); + $this->assertEquals($this->Shell->nl(2), $newLine . $newLine); + $this->assertEquals($this->Shell->nl(1), $newLine); + } + +/** + * testHr + * + * @return void + */ + public function testHr() { + $bar = '---------------------------------------------------------------'; + + $this->Shell->stdout->expects($this->at(0))->method('write')->with('', 0); + $this->Shell->stdout->expects($this->at(1))->method('write')->with($bar, 1); + $this->Shell->stdout->expects($this->at(2))->method('write')->with('', 0); + + $this->Shell->stdout->expects($this->at(3))->method('write')->with("", true); + $this->Shell->stdout->expects($this->at(4))->method('write')->with($bar, 1); + $this->Shell->stdout->expects($this->at(5))->method('write')->with("", true); + + $this->Shell->stdout->expects($this->at(6))->method('write')->with("", 2); + $this->Shell->stdout->expects($this->at(7))->method('write')->with($bar, 1); + $this->Shell->stdout->expects($this->at(8))->method('write')->with("", 2); + + $this->Shell->hr(); + + $this->Shell->hr(true); + + $this->Shell->hr(2); + } + +/** + * testError + * + * @return void + */ + public function testError() { + $this->Shell->stderr->expects($this->at(0)) + ->method('write') + ->with("Error: Foo Not Found", 1); + + $this->Shell->stderr->expects($this->at(1)) + ->method('write') + ->with("Error: Foo Not Found", 1); + + $this->Shell->stderr->expects($this->at(2)) + ->method('write') + ->with("Searched all...", 1); + + $this->Shell->error('Foo Not Found'); + $this->assertSame($this->Shell->stopped, 1); + + $this->Shell->stopped = null; + + $this->Shell->error('Foo Not Found', 'Searched all...'); + $this->assertSame($this->Shell->stopped, 1); + } + +/** + * testLoadTasks method + * + * @return void + */ + public function testLoadTasks() { + $this->assertTrue($this->Shell->loadTasks()); + + $this->Shell->tasks = null; + $this->assertTrue($this->Shell->loadTasks()); + + $this->Shell->tasks = false; + $this->assertTrue($this->Shell->loadTasks()); + + $this->Shell->tasks = true; + $this->assertTrue($this->Shell->loadTasks()); + + $this->Shell->tasks = array(); + $this->assertTrue($this->Shell->loadTasks()); + + $this->Shell->tasks = array('TestApple'); + $this->assertTrue($this->Shell->loadTasks()); + $this->assertInstanceOf('TestAppleTask', $this->Shell->TestApple); + + $this->Shell->tasks = 'TestBanana'; + $this->assertTrue($this->Shell->loadTasks()); + $this->assertInstanceOf('TestAppleTask', $this->Shell->TestApple); + $this->assertInstanceOf('TestBananaTask', $this->Shell->TestBanana); + + unset($this->Shell->ShellTestApple, $this->Shell->TestBanana); + + $this->Shell->tasks = array('TestApple', 'TestBanana'); + $this->assertTrue($this->Shell->loadTasks()); + $this->assertInstanceOf('TestAppleTask', $this->Shell->TestApple); + $this->assertInstanceOf('TestBananaTask', $this->Shell->TestBanana); + } + +/** + * test that __get() makes args and params references + * + * @return void + */ + public function testMagicGetArgAndParamReferences() { + $this->Shell->tasks = array('TestApple'); + $this->Shell->args = array('one'); + $this->Shell->params = array('help' => false); + $this->Shell->loadTasks(); + $result = $this->Shell->TestApple; + + $this->Shell->args = array('one', 'two'); + + $this->assertSame($this->Shell->args, $result->args); + $this->assertSame($this->Shell->params, $result->params); + } + +/** + * testShortPath method + * + * @return void + */ + public function testShortPath() { + $path = $expected = DS . 'tmp' . DS . 'ab' . DS . 'cd'; + $this->assertEquals($expected, $this->Shell->shortPath($path)); + + $path = $expected = DS . 'tmp' . DS . 'ab' . DS . 'cd' . DS; + $this->assertEquals($expected, $this->Shell->shortPath($path)); + + $path = $expected = DS . 'tmp' . DS . 'ab' . DS . 'index.php'; + $this->assertEquals($expected, $this->Shell->shortPath($path)); + + $path = DS . 'tmp' . DS . 'ab' . DS . DS . 'cd'; + $expected = DS . 'tmp' . DS . 'ab' . DS . 'cd'; + $this->assertEquals($expected, $this->Shell->shortPath($path)); + + $path = 'tmp' . DS . 'ab'; + $expected = 'tmp' . DS . 'ab'; + $this->assertEquals($expected, $this->Shell->shortPath($path)); + + $path = 'tmp' . DS . 'ab'; + $expected = 'tmp' . DS . 'ab'; + $this->assertEquals($expected, $this->Shell->shortPath($path)); + + $path = APP; + $expected = DS . basename(APP) . DS; + $this->assertEquals($expected, $this->Shell->shortPath($path)); + + $path = APP . 'index.php'; + $expected = DS . basename(APP) . DS . 'index.php'; + $this->assertEquals($expected, $this->Shell->shortPath($path)); + } + +/** + * testCreateFile method + * + * @return void + */ + public function testCreateFileNonInteractive() { + $eol = PHP_EOL; + + $path = TMP . 'shell_test'; + $file = $path . DS . 'file1.php'; + + $Folder = new Folder($path, true); + + $this->Shell->interactive = false; + + $contents = "Shell->createFile($file, $contents); + $this->assertTrue($result); + $this->assertTrue(file_exists($file)); + $this->assertEquals(file_get_contents($file), $contents); + + $contents = "Shell->createFile($file, $contents); + $this->assertTrue($result); + $this->assertTrue(file_exists($file)); + $this->assertTextEquals(file_get_contents($file), $contents); + } + +/** + * test createFile when the shell is interactive. + * + * @return void + */ + public function testCreateFileInteractive() { + $eol = PHP_EOL; + + $path = TMP . 'shell_test'; + $file = $path . DS . 'file1.php'; + $Folder = new Folder($path, true); + + $this->Shell->interactive = true; + + $this->Shell->stdin->expects($this->at(0)) + ->method('read') + ->will($this->returnValue('n')); + + $this->Shell->stdin->expects($this->at(1)) + ->method('read') + ->will($this->returnValue('y')); + + $contents = "Shell->createFile($file, $contents); + $this->assertTrue($result); + $this->assertTrue(file_exists($file)); + $this->assertEquals(file_get_contents($file), $contents); + + // no overwrite + $contents = 'new contents'; + $result = $this->Shell->createFile($file, $contents); + $this->assertFalse($result); + $this->assertTrue(file_exists($file)); + $this->assertNotEquals($contents, file_get_contents($file)); + + // overwrite + $contents = 'more new contents'; + $result = $this->Shell->createFile($file, $contents); + $this->assertTrue($result); + $this->assertTrue(file_exists($file)); + $this->assertEquals($contents, file_get_contents($file)); + } + +/** + * Test that you can't create files that aren't writable. + * + * @return void + */ + public function testCreateFileNoPermissions() { + $this->skipIf(DIRECTORY_SEPARATOR === '\\', 'Cant perform operations using permissions on windows.'); + + $path = TMP . 'shell_test'; + $file = $path . DS . 'no_perms'; + + if (!is_dir($path)) { + mkdir($path); + } + chmod($path, 0444); + + $this->Shell->createFile($file, 'testing'); + $this->assertFalse(file_exists($file)); + + chmod($path, 0744); + rmdir($path); + } + +/** + * test hasTask method + * + * @return void + */ + public function testHasTask() { + $this->Shell->tasks = array('Extract', 'DbConfig'); + $this->Shell->loadTasks(); + + $this->assertTrue($this->Shell->hasTask('extract')); + $this->assertTrue($this->Shell->hasTask('Extract')); + $this->assertFalse($this->Shell->hasTask('random')); + + $this->assertTrue($this->Shell->hasTask('db_config')); + $this->assertTrue($this->Shell->hasTask('DbConfig')); + } + +/** + * test the hasMethod + * + * @return void + */ + public function testHasMethod() { + $this->assertTrue($this->Shell->hasMethod('do_something')); + $this->assertFalse($this->Shell->hasMethod('hr'), 'hr is callable'); + $this->assertFalse($this->Shell->hasMethod('_secret'), '_secret is callable'); + $this->assertFalse($this->Shell->hasMethod('no_access'), 'no_access is callable'); + } + +/** + * test run command calling main. + * + * @return void + */ + public function testRunCommandMain() { + $methods = get_class_methods('Shell'); + $Mock = $this->getMock('Shell', array('main', 'startup'), array(), '', false); + + $Mock->expects($this->once())->method('main')->will($this->returnValue(true)); + $result = $Mock->runCommand(null, array()); + $this->assertTrue($result); + } + +/** + * test run command calling a legit method. + * + * @return void + */ + public function testRunCommandWithMethod() { + $methods = get_class_methods('Shell'); + $Mock = $this->getMock('Shell', array('hit_me', 'startup'), array(), '', false); + + $Mock->expects($this->once())->method('hit_me')->will($this->returnValue(true)); + $result = $Mock->runCommand('hit_me', array()); + $this->assertTrue($result); + } + +/** + * test run command causing exception on Shell method. + * + * @return void + */ + public function testRunCommandBaseclassMethod() { + $Mock = $this->getMock('Shell', array('startup', 'getOptionParser', 'out'), array(), '', false); + $Parser = $this->getMock('ConsoleOptionParser', array(), array(), '', false); + + $Parser->expects($this->once())->method('help'); + $Mock->expects($this->once())->method('getOptionParser') + ->will($this->returnValue($Parser)); + $Mock->expects($this->never())->method('hr'); + $Mock->expects($this->once())->method('out'); + + $result = $Mock->runCommand('hr', array()); + } + +/** + * test run command causing exception on Shell method. + * + * @return void + */ + public function testRunCommandMissingMethod() { + $methods = get_class_methods('Shell'); + $Mock = $this->getMock('Shell', array('startup', 'getOptionParser', 'out'), array(), '', false); + $Parser = $this->getMock('ConsoleOptionParser', array(), array(), '', false); + + $Parser->expects($this->once())->method('help'); + $Mock->expects($this->never())->method('idontexist'); + $Mock->expects($this->once())->method('getOptionParser') + ->will($this->returnValue($Parser)); + $Mock->expects($this->once())->method('out'); + + $result = $Mock->runCommand('idontexist', array()); + $this->assertFalse($result); + } + +/** + * test that a --help causes help to show. + * + * @return void + */ + public function testRunCommandTriggeringHelp() { + $Parser = $this->getMock('ConsoleOptionParser', array(), array(), '', false); + $Parser->expects($this->once())->method('parse') + ->with(array('--help')) + ->will($this->returnValue(array(array('help' => true), array()))); + $Parser->expects($this->once())->method('help'); + + $Shell = $this->getMock('Shell', array('getOptionParser', 'out', 'startup', '_welcome'), array(), '', false); + $Shell->expects($this->once())->method('getOptionParser') + ->will($this->returnValue($Parser)); + $Shell->expects($this->once())->method('out'); + + $Shell->runCommand(null, array('--help')); + } + +/** + * test that runCommand will call runCommand on the task. + * + * @return void + */ + public function testRunCommandHittingTask() { + $Shell = $this->getMock('Shell', array('hasTask', 'startup'), array(), '', false); + $task = $this->getMock('Shell', array('execute', 'runCommand'), array(), '', false); + $task->expects($this->any()) + ->method('runCommand') + ->with('execute', array('one', 'value')); + + $Shell->expects($this->once())->method('startup'); + $Shell->expects($this->any()) + ->method('hasTask') + ->will($this->returnValue(true)); + + $Shell->RunCommand = $task; + + $result = $Shell->runCommand('run_command', array('run_command', 'one', 'value')); + } + +/** + * test wrapBlock wrapping text. + * + * @return void + */ + public function testWrapText() { + $text = 'This is the song that never ends. This is the song that never ends. This is the song that never ends.'; + $result = $this->Shell->wrapText($text, 33); + $expected = <<assertTextEquals($expected, $result, 'Text not wrapped.'); + + $result = $this->Shell->wrapText($text, array('indent' => ' ', 'width' => 33)); + $expected = <<assertTextEquals($expected, $result, 'Text not wrapped.'); + } + +/** + * Testing camel cased naming of tasks + * + * @return void + */ + public function testShellNaming() { + $this->Shell->tasks = array('TestApple'); + $this->Shell->loadTasks(); + $expected = 'TestApple'; + $this->assertEquals($expected, $this->Shell->TestApple->name); + } + +/** + * Test that option parsers are created with the correct name/command. + * + * @return void + */ + public function testGetOptionParser() { + $this->Shell->name = 'test'; + $this->Shell->plugin = 'plugin'; + $parser = $this->Shell->getOptionParser(); + + $this->assertEquals('plugin.test', $parser->command()); + } + +/** + * Test file and console and logging + */ + public function testFileAndConsoleLogging() { + // file logging + $this->Shell->log_something(); + $this->assertTrue(file_exists(LOGS . 'error.log')); + + unlink(LOGS . 'error.log'); + $this->assertFalse(file_exists(LOGS . 'error.log')); + + // both file and console logging + require_once CORE_TEST_CASES . DS . 'Log' . DS . 'Engine' . DS . 'ConsoleLogTest.php'; + $mock = $this->getMock('ConsoleLog', array('write'), array( + array('types' => 'error'), + )); + TestCakeLog::config('console', array( + 'engine' => 'ConsoleLog', + 'stream' => 'php://stderr', + )); + TestCakeLog::replace('console', $mock); + $mock->expects($this->once()) + ->method('write') + ->with('error', $this->Shell->testMessage); + $this->Shell->log_something(); + $this->assertTrue(file_exists(LOGS . 'error.log')); + $contents = file_get_contents(LOGS . 'error.log'); + $this->assertContains($this->Shell->testMessage, $contents); + } + +/** + * Tests that _useLogger works properly + * + * @return void + **/ + public function testProtectedUseLogger() { + CakeLog::drop('stdout'); + CakeLog::drop('stderr'); + $this->Shell->useLogger(true); + $this->assertNotEmpty(CakeLog::stream('stdout')); + $this->assertNotEmpty(CakeLog::stream('stderr')); + $this->Shell->useLogger(false); + $this->assertFalse(CakeLog::stream('stdout')); + $this->assertFalse(CakeLog::stream('stderr')); + } + +/** + * Test file and console and logging quiet output + */ + public function testQuietLog() { + $output = $this->getMock('ConsoleOutput', array(), array(), '', false); + $error = $this->getMock('ConsoleOutput', array(), array(), '', false); + $in = $this->getMock('ConsoleInput', array(), array(), '', false); + $this->Shell = $this->getMock('ShellTestShell', array('_useLogger'), array($output, $error, $in)); + $this->Shell->expects($this->once())->method('_useLogger')->with(false); + $this->Shell->runCommand('foo', array('--quiet')); + } + +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/TaskCollectionTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/TaskCollectionTest.php new file mode 100644 index 0000000..9317e77 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Console/TaskCollectionTest.php @@ -0,0 +1,124 @@ +getMock('Shell', array(), array(), '', false); + $dispatcher = $this->getMock('ShellDispatcher', array(), array(), '', false); + $this->Tasks = new TaskCollection($shell, $dispatcher); + } + +/** + * tearDown + * + * @return void + */ + public function tearDown() { + unset($this->Tasks); + parent::tearDown(); + } + +/** + * test triggering callbacks on loaded tasks + * + * @return void + */ + public function testLoad() { + $result = $this->Tasks->load('DbConfig'); + $this->assertInstanceOf('DbConfigTask', $result); + $this->assertInstanceOf('DbConfigTask', $this->Tasks->DbConfig); + + $result = $this->Tasks->attached(); + $this->assertEquals(array('DbConfig'), $result, 'attached() results are wrong.'); + } + +/** + * test load and enable = false + * + * @return void + */ + public function testLoadWithEnableFalse() { + $result = $this->Tasks->load('DbConfig', array('enabled' => false)); + $this->assertInstanceOf('DbConfigTask', $result); + $this->assertInstanceOf('DbConfigTask', $this->Tasks->DbConfig); + + $this->assertFalse($this->Tasks->enabled('DbConfig'), 'DbConfigTask should be disabled'); + } + +/** + * test missingtask exception + * + * @expectedException MissingTaskException + * @return void + */ + public function testLoadMissingTask() { + $result = $this->Tasks->load('ThisTaskShouldAlwaysBeMissing'); + } + +/** + * test loading a plugin helper. + * + * @return void + */ + public function testLoadPluginTask() { + $dispatcher = $this->getMock('ShellDispatcher', array(), array(), '', false); + $shell = $this->getMock('Shell', array(), array(), '', false); + App::build(array( + 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS) + )); + CakePlugin::load('TestPlugin'); + $this->Tasks = new TaskCollection($shell, $dispatcher); + + $result = $this->Tasks->load('TestPlugin.OtherTask'); + $this->assertInstanceOf('OtherTaskTask', $result, 'Task class is wrong.'); + $this->assertInstanceOf('OtherTaskTask', $this->Tasks->OtherTask, 'Class is wrong'); + CakePlugin::unload(); + } + +/** + * test unload() + * + * @return void + */ + public function testUnload() { + $this->Tasks->load('Extract'); + $this->Tasks->load('DbConfig'); + + $result = $this->Tasks->attached(); + $this->assertEquals(array('Extract', 'DbConfig'), $result, 'loaded tasks is wrong'); + + $this->Tasks->unload('DbConfig'); + $this->assertFalse(isset($this->Tasks->DbConfig)); + $this->assertTrue(isset($this->Tasks->Extract)); + + $result = $this->Tasks->attached(); + $this->assertEquals(array('Extract'), $result, 'loaded tasks is wrong'); + } + +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/Acl/DbAclTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/Acl/DbAclTest.php new file mode 100644 index 0000000..bfc33f6 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/Acl/DbAclTest.php @@ -0,0 +1,543 @@ + array('with' => 'PermissionTwoTest')); +} + +/** + * AcoTwoTest class + * + * @package Cake.Test.Case.Controller.Component.Acl + */ +class AcoTwoTest extends AclNodeTwoTestBase { + +/** + * name property + * + * @var string 'AcoTwoTest' + */ + public $name = 'AcoTwoTest'; + +/** + * useTable property + * + * @var string 'aco_twos' + */ + public $useTable = 'aco_twos'; + +/** + * hasAndBelongsToMany property + * + * @var array + */ + public $hasAndBelongsToMany = array('AroTwoTest' => array('with' => 'PermissionTwoTest')); +} + +/** + * PermissionTwoTest class + * + * @package Cake.Test.Case.Controller.Component.Acl + */ +class PermissionTwoTest extends Permission { + +/** + * name property + * + * @var string 'PermissionTwoTest' + */ + public $name = 'PermissionTwoTest'; + +/** + * useTable property + * + * @var string 'aros_aco_twos' + */ + public $useTable = 'aros_aco_twos'; + +/** + * cacheQueries property + * + * @var bool false + */ + public $cacheQueries = false; + +/** + * belongsTo property + * + * @var array + */ + public $belongsTo = array('AroTwoTest' => array('foreignKey' => 'aro_id'), 'AcoTwoTest' => array('foreignKey' => 'aco_id')); + +/** + * actsAs property + * + * @var mixed null + */ + public $actsAs = null; +} + +/** + * DbAclTwoTest class + * + * @package Cake.Test.Case.Controller.Component.Acl + */ +class DbAclTwoTest extends DbAcl { + +/** + * construct method + * + * @return void + */ + public function __construct() { + $this->Aro = new AroTwoTest(); + $this->Aro->Permission = new PermissionTwoTest(); + $this->Aco = new AcoTwoTest(); + $this->Aro->Permission = new PermissionTwoTest(); + + $this->Permission = $this->Aro->Permission; + $this->Permission->Aro = $this->Aro; + $this->Permission->Aco = $this->Aco; + } + +} + +/** + * Test case for AclComponent using the DbAcl implementation. + * + * @package Cake.Test.Case.Controller.Component.Acl + */ +class DbAclTest extends CakeTestCase { + +/** + * fixtures property + * + * @var array + */ + public $fixtures = array('core.aro_two', 'core.aco_two', 'core.aros_aco_two'); + +/** + * setUp method + * + * @return void + */ + public function setUp() { + parent::setUp(); + Configure::write('Acl.classname', 'DbAclTwoTest'); + Configure::write('Acl.database', 'test'); + $Collection = new ComponentCollection(); + $this->Acl = new AclComponent($Collection); + } + +/** + * tearDown method + * + * @return void + */ + public function tearDown() { + parent::tearDown(); + unset($this->Acl); + } + +/** + * testAclCreate method + * + * @return void + */ + public function testCreate() { + $this->Acl->Aro->create(array('alias' => 'Chotchkey')); + $this->assertTrue((bool)$this->Acl->Aro->save()); + + $parent = $this->Acl->Aro->id; + + $this->Acl->Aro->create(array('parent_id' => $parent, 'alias' => 'Joanna')); + $this->assertTrue((bool)$this->Acl->Aro->save()); + + $this->Acl->Aro->create(array('parent_id' => $parent, 'alias' => 'Stapler')); + $this->assertTrue((bool)$this->Acl->Aro->save()); + + $root = $this->Acl->Aco->node('ROOT'); + $parent = $root[0]['AcoTwoTest']['id']; + + $this->Acl->Aco->create(array('parent_id' => $parent, 'alias' => 'Drinks')); + $this->assertTrue((bool)$this->Acl->Aco->save()); + + $this->Acl->Aco->create(array('parent_id' => $parent, 'alias' => 'PiecesOfFlair')); + $this->assertTrue((bool)$this->Acl->Aco->save()); + } + +/** + * testAclCreateWithParent method + * + * @return void + */ + public function testCreateWithParent() { + $parent = $this->Acl->Aro->findByAlias('Peter', null, null, -1); + $this->Acl->Aro->create(); + $this->Acl->Aro->save(array( + 'alias' => 'Subordinate', + 'model' => 'User', + 'foreign_key' => 7, + 'parent_id' => $parent['AroTwoTest']['id'] + )); + $result = $this->Acl->Aro->findByAlias('Subordinate', null, null, -1); + $this->assertEquals(16, $result['AroTwoTest']['lft']); + $this->assertEquals(17, $result['AroTwoTest']['rght']); + } + +/** + * testDbAclAllow method + * + * @expectedException PHPUnit_Framework_Error_Warning + * @return void + */ + public function testAllow() { + $this->assertFalse($this->Acl->check('Micheal', 'tpsReports', 'read')); + $this->assertTrue($this->Acl->allow('Micheal', 'tpsReports', array('read', 'delete', 'update'))); + $this->assertTrue($this->Acl->check('Micheal', 'tpsReports', 'update')); + $this->assertTrue($this->Acl->check('Micheal', 'tpsReports', 'read')); + $this->assertTrue($this->Acl->check('Micheal', 'tpsReports', 'delete')); + + $this->assertFalse($this->Acl->check('Micheal', 'tpsReports', 'create')); + $this->assertTrue($this->Acl->allow('Micheal', 'ROOT/tpsReports', 'create')); + $this->assertTrue($this->Acl->check('Micheal', 'tpsReports', 'create')); + $this->assertTrue($this->Acl->check('Micheal', 'tpsReports', 'delete')); + $this->assertTrue($this->Acl->allow('Micheal', 'printers', 'create')); + // Michael no longer has his delete permission for tpsReports! + $this->assertTrue($this->Acl->check('Micheal', 'tpsReports', 'delete')); + $this->assertTrue($this->Acl->check('Micheal', 'printers', 'create')); + + $this->assertFalse($this->Acl->check('root/users/Samir', 'ROOT/tpsReports/view')); + $this->assertTrue($this->Acl->allow('root/users/Samir', 'ROOT/tpsReports/view', '*')); + $this->assertTrue($this->Acl->check('Samir', 'view', 'read')); + $this->assertTrue($this->Acl->check('root/users/Samir', 'ROOT/tpsReports/view', 'update')); + + $this->assertFalse($this->Acl->check('root/users/Samir', 'ROOT/tpsReports/update','*')); + $this->assertTrue($this->Acl->allow('root/users/Samir', 'ROOT/tpsReports/update', '*')); + $this->assertTrue($this->Acl->check('Samir', 'update', 'read')); + $this->assertTrue($this->Acl->check('root/users/Samir', 'ROOT/tpsReports/update', 'update')); + // Samir should still have his tpsReports/view permissions, but does not + $this->assertTrue($this->Acl->check('root/users/Samir', 'ROOT/tpsReports/view', 'update')); + + $this->assertFalse($this->Acl->allow('Lumbergh', 'ROOT/tpsReports/DoesNotExist', 'create')); + } + +/** + * testAllowInvalidNode method + * + * @expectedException PHPUnit_Framework_Error_Warning + * @return void + */ + public function testAllowInvalidNode() { + $this->Acl->allow('Homer', 'tpsReports', 'create'); + } + +/** + * testDbAclCheck method + * + * @return void + */ + public function testCheck() { + $this->assertTrue($this->Acl->check('Samir', 'print', 'read')); + $this->assertTrue($this->Acl->check('Lumbergh', 'current', 'read')); + $this->assertFalse($this->Acl->check('Milton', 'smash', 'read')); + $this->assertFalse($this->Acl->check('Milton', 'current', 'update')); + + $this->assertFalse($this->Acl->check(null, 'printers', 'create')); + $this->assertFalse($this->Acl->check('managers', null, 'read')); + + $this->assertTrue($this->Acl->check('Bobs', 'ROOT/tpsReports/view/current', 'read')); + $this->assertFalse($this->Acl->check('Samir', 'ROOT/tpsReports/update', 'read')); + + $this->assertFalse($this->Acl->check('root/users/Milton', 'smash', 'delete')); + } + +/** + * testCheckInvalidNode method + * + * @expectedException PHPUnit_Framework_Error_Warning + * @return void + */ + public function testCheckInvalidNode() { + $this->assertFalse($this->Acl->check('WRONG', 'tpsReports', 'read')); + } + +/** + * testCheckInvalidPermission method + * + * @expectedException PHPUnit_Framework_Error_Notice + * @return void + */ + public function testCheckInvalidPermission() { + $this->Acl->check('Lumbergh', 'smash', 'foobar'); + } + +/** + * testCheckMissingPermission method + * + * @expectedException PHPUnit_Framework_Error_Warning + * @return void + */ + public function testCheckMissingPermission() { + $this->Acl->check('users', 'NonExistent', 'read'); + } + +/** + * testDbAclCascadingDeny function + * + * Setup the acl permissions such that Bobs inherits from admin. + * deny Admin delete access to a specific resource, check the permissions are inherited. + * + * @return void + */ + public function testAclCascadingDeny() { + $this->Acl->inherit('Bobs', 'ROOT', '*'); + $this->assertTrue($this->Acl->check('admin', 'tpsReports', 'delete')); + $this->assertTrue($this->Acl->check('Bobs', 'tpsReports', 'delete')); + $this->Acl->deny('admin', 'tpsReports', 'delete'); + $this->assertFalse($this->Acl->check('admin', 'tpsReports', 'delete')); + $this->assertFalse($this->Acl->check('Bobs', 'tpsReports', 'delete')); + } + +/** + * testDbAclDeny method + * + * @expectedException PHPUnit_Framework_Error_Warning + * @return void + */ + public function testDeny() { + $this->assertTrue($this->Acl->check('Micheal', 'smash', 'delete')); + $this->Acl->deny('Micheal', 'smash', 'delete'); + $this->assertFalse($this->Acl->check('Micheal', 'smash', 'delete')); + $this->assertTrue($this->Acl->check('Micheal', 'smash', 'read')); + $this->assertTrue($this->Acl->check('Micheal', 'smash', 'create')); + $this->assertTrue($this->Acl->check('Micheal', 'smash', 'update')); + $this->assertFalse($this->Acl->check('Micheal', 'smash', '*')); + + $this->assertTrue($this->Acl->check('Samir', 'refill', '*')); + $this->Acl->deny('Samir', 'refill', '*'); + $this->assertFalse($this->Acl->check('Samir', 'refill', 'create')); + $this->assertFalse($this->Acl->check('Samir', 'refill', 'update')); + $this->assertFalse($this->Acl->check('Samir', 'refill', 'read')); + $this->assertFalse($this->Acl->check('Samir', 'refill', 'delete')); + + $result = $this->Acl->Aro->Permission->find('all', array('conditions' => array('AroTwoTest.alias' => 'Samir'))); + $expected = '-1'; + $this->assertEquals($expected, $result[0]['PermissionTwoTest']['_delete']); + + $this->assertFalse($this->Acl->deny('Lumbergh', 'ROOT/tpsReports/DoesNotExist', 'create')); + } + +/** + * testAclNodeLookup method + * + * @return void + */ + public function testAclNodeLookup() { + $result = $this->Acl->Aro->node('root/users/Samir'); + $expected = array( + array('AroTwoTest' => array('id' => '7', 'parent_id' => '4', 'model' => 'User', 'foreign_key' => 3, 'alias' => 'Samir')), + array('AroTwoTest' => array('id' => '4', 'parent_id' => '1', 'model' => 'Group', 'foreign_key' => 3, 'alias' => 'users')), + array('AroTwoTest' => array('id' => '1', 'parent_id' => null, 'model' => null, 'foreign_key' => null, 'alias' => 'root')) + ); + $this->assertEquals($expected, $result); + + $result = $this->Acl->Aco->node('ROOT/tpsReports/view/current'); + $expected = array( + array('AcoTwoTest' => array('id' => '4', 'parent_id' => '3', 'model' => null, 'foreign_key' => null, 'alias' => 'current')), + array('AcoTwoTest' => array('id' => '3', 'parent_id' => '2', 'model' => null, 'foreign_key' => null, 'alias' => 'view')), + array('AcoTwoTest' => array('id' => '2', 'parent_id' => '1', 'model' => null, 'foreign_key' => null, 'alias' => 'tpsReports')), + array('AcoTwoTest' => array('id' => '1', 'parent_id' => null, 'model' => null, 'foreign_key' => null, 'alias' => 'ROOT')), + ); + $this->assertEquals($expected, $result); + } + +/** + * testDbInherit method + * + * @return void + */ + public function testInherit() { + //parent doesn't have access inherit should still deny + $this->assertFalse($this->Acl->check('Milton', 'smash', 'delete')); + $this->Acl->inherit('Milton', 'smash', 'delete'); + $this->assertFalse($this->Acl->check('Milton', 'smash', 'delete')); + + //inherit parent + $this->assertFalse($this->Acl->check('Milton', 'smash', 'read')); + $this->Acl->inherit('Milton', 'smash', 'read'); + $this->assertTrue($this->Acl->check('Milton', 'smash', 'read')); + } + +/** + * testDbGrant method + * + * @expectedException PHPUnit_Framework_Error_Warning + * @return void + */ + public function testGrant() { + $this->assertFalse($this->Acl->check('Samir', 'tpsReports', 'create')); + $this->Acl->allow('Samir', 'tpsReports', 'create'); + $this->assertTrue($this->Acl->check('Samir', 'tpsReports', 'create')); + + $this->assertFalse($this->Acl->check('Micheal', 'view', 'read')); + $this->Acl->allow('Micheal', 'view', array('read', 'create', 'update')); + $this->assertTrue($this->Acl->check('Micheal', 'view', 'read')); + $this->assertTrue($this->Acl->check('Micheal', 'view', 'create')); + $this->assertTrue($this->Acl->check('Micheal', 'view', 'update')); + $this->assertFalse($this->Acl->check('Micheal', 'view', 'delete')); + + $this->assertFalse($this->Acl->allow('Peter', 'ROOT/tpsReports/DoesNotExist', 'create')); + } + +/** + * testDbRevoke method + * + * @expectedException PHPUnit_Framework_Error_Warning + * @return void + */ + public function testRevoke() { + $this->assertTrue($this->Acl->check('Bobs', 'tpsReports', 'read')); + $this->Acl->deny('Bobs', 'tpsReports', 'read'); + $this->assertFalse($this->Acl->check('Bobs', 'tpsReports', 'read')); + + $this->assertTrue($this->Acl->check('users', 'printers', 'read')); + $this->Acl->deny('users', 'printers', 'read'); + $this->assertFalse($this->Acl->check('users', 'printers', 'read')); + $this->assertFalse($this->Acl->check('Samir', 'printers', 'read')); + $this->assertFalse($this->Acl->check('Peter', 'printers', 'read')); + + $this->Acl->deny('Bobs', 'ROOT/printers/DoesNotExist', 'create'); + } + +/** + * debug function - to help editing/creating test cases for the ACL component + * + * To check the overall ACL status at any time call $this->__debug(); + * Generates a list of the current aro and aco structures and a grid dump of the permissions that are defined + * Only designed to work with the db based ACL + * + * @param bool $treesToo + * @return void + */ + protected function __debug($printTreesToo = false) { + $this->Acl->Aro->displayField = 'alias'; + $this->Acl->Aco->displayField = 'alias'; + $aros = $this->Acl->Aro->find('list', array('order' => 'lft')); + $acos = $this->Acl->Aco->find('list', array('order' => 'lft')); + $rights = array('*', 'create', 'read', 'update', 'delete'); + $permissions['Aros v Acos >'] = $acos; + foreach ($aros as $aro) { + $row = array(); + foreach ($acos as $aco) { + $perms = ''; + foreach ($rights as $right) { + if ($this->Acl->check($aro, $aco, $right)) { + if ($right == '*') { + $perms .= '****'; + break; + } + $perms .= $right[0]; + } elseif ($right != '*') { + $perms .= ' '; + } + } + $row[] = $perms; + } + $permissions[$aro] = $row; + } + foreach ($permissions as $key => $values) { + array_unshift($values, $key); + $values = array_map(array(&$this, '__pad'), $values); + $permissions[$key] = implode (' ', $values); + } + $permisssions = array_map(array(&$this, '__pad'), $permissions); + array_unshift($permissions, 'Current Permissions :'); + if ($printTreesToo) { + debug(array('aros' => $this->Acl->Aro->generateTreeList(), 'acos' => $this->Acl->Aco->generateTreeList())); + } + debug(implode("\r\n", $permissions)); + } + +/** + * pad function + * Used by debug to format strings used in the data dump + * + * @param string $string + * @param integer $len + * @return void + */ + protected function __pad($string = '', $len = 14) { + return str_pad($string, $len); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/Acl/IniAclTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/Acl/IniAclTest.php new file mode 100644 index 0000000..de552b1 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/Acl/IniAclTest.php @@ -0,0 +1,69 @@ +config = $Ini->readConfigFile($iniFile); + + $this->assertFalse($Ini->check('admin', 'ads')); + $this->assertTrue($Ini->check('admin', 'posts')); + + $this->assertTrue($Ini->check('jenny', 'posts')); + $this->assertTrue($Ini->check('jenny', 'ads')); + + $this->assertTrue($Ini->check('paul', 'posts')); + $this->assertFalse($Ini->check('paul', 'ads')); + + $this->assertFalse($Ini->check('nobody', 'comments')); + } + +/** + * check should accept a user array. + * + * @return void + */ + public function testCheckArray() { + $iniFile = CAKE . 'Test' . DS . 'test_app' . DS . 'Config' . DS . 'acl.ini.php'; + + $Ini = new IniAcl(); + $Ini->config = $Ini->readConfigFile($iniFile); + $Ini->userPath = 'User.username'; + + $user = array( + 'User' => array('username' => 'admin') + ); + $this->assertTrue($Ini->check($user, 'posts')); + } +} + diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/Acl/PhpAclTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/Acl/PhpAclTest.php new file mode 100644 index 0000000..92543b3 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/Acl/PhpAclTest.php @@ -0,0 +1,337 @@ +PhpAcl = new PhpAcl(); + $this->Acl = new AclComponent($Collection, array( + 'adapter' => array( + 'config' => CAKE . 'Test' . DS . 'test_app' . DS . 'Config' . DS . 'acl.php', + ), + )); + } + + public function testRoleInheritance() { + $roles = $this->Acl->Aro->roles('User/peter'); + $this->assertEquals(array('Role/accounting'), $roles[0]); + $this->assertEquals(array('User/peter'), $roles[1]); + + $roles = $this->Acl->Aro->roles('hardy'); + $this->assertEquals(array('Role/database_manager', 'Role/data_acquirer'), $roles[0]); + $this->assertEquals(array('Role/accounting', 'Role/data_analyst'), $roles[1]); + $this->assertEquals(array('Role/accounting_manager', 'Role/reports'), $roles[2]); + $this->assertEquals(array('User/hardy'), $roles[3]); + } + + public function testAddRole() { + $this->assertEquals(array(array(PhpAro::DEFAULT_ROLE)), $this->Acl->Aro->roles('foobar')); + $this->Acl->Aro->addRole(array('User/foobar' => 'Role/accounting')); + $this->assertEquals(array(array('Role/accounting'), array('User/foobar')), $this->Acl->Aro->roles('foobar')); + } + + public function testAroResolve() { + $map = $this->Acl->Aro->map; + $this->Acl->Aro->map = array( + 'User' => 'FooModel/nickname', + 'Role' => 'FooModel/role', + ); + + $this->assertEquals('Role/default', $this->Acl->Aro->resolve('Foo.bar')); + $this->assertEquals('User/hardy', $this->Acl->Aro->resolve('FooModel/hardy')); + $this->assertEquals('User/hardy', $this->Acl->Aro->resolve('hardy')); + $this->assertEquals('User/hardy', $this->Acl->Aro->resolve(array('FooModel' => array('nickname' => 'hardy')))); + $this->assertEquals('Role/admin', $this->Acl->Aro->resolve(array('FooModel' => array('role' => 'admin')))); + $this->assertEquals('Role/admin', $this->Acl->Aro->resolve('Role/admin')); + + $this->assertEquals('Role/admin', $this->Acl->Aro->resolve('admin')); + $this->assertEquals('Role/admin', $this->Acl->Aro->resolve('FooModel/admin')); + $this->assertEquals('Role/accounting', $this->Acl->Aro->resolve('accounting')); + + $this->assertEquals(PhpAro::DEFAULT_ROLE, $this->Acl->Aro->resolve('bla')); + $this->assertEquals(PhpAro::DEFAULT_ROLE, $this->Acl->Aro->resolve(array('FooModel' => array('role' => 'hardy')))); + } + +/** + * test correct resolution of defined aliases + */ + public function testAroAliases() { + $this->Acl->Aro->map = array( + 'User' => 'User/username', + 'Role' => 'User/group_id', + ); + + $this->Acl->Aro->aliases = array( + 'Role/1' => 'Role/admin', + 'Role/24' => 'Role/accounting', + ); + + $user = array( + 'User' => array( + 'username' => 'unknown_user', + 'group_id' => '1', + ), + ); + // group/1 + $this->assertEquals('Role/admin', $this->Acl->Aro->resolve($user)); + // group/24 + $this->assertEquals('Role/accounting', $this->Acl->Aro->resolve('Role/24')); + $this->assertEquals('Role/accounting', $this->Acl->Aro->resolve('24')); + + // check department + $user = array( + 'User' => array( + 'username' => 'foo', + 'group_id' => '25', + ), + ); + + $this->Acl->Aro->addRole(array('Role/IT' => null)); + $this->Acl->Aro->addAlias(array('Role/25' => 'Role/IT')); + $this->Acl->allow('Role/IT', '/rules/debugging/*'); + + $this->assertEquals(array(array('Role/IT', )), $this->Acl->Aro->roles($user)); + $this->assertTrue($this->Acl->check($user, '/rules/debugging/stats/pageload')); + $this->assertTrue($this->Acl->check($user, '/rules/debugging/sql/queries')); + // Role/default is allowed users dashboard, but not Role/IT + $this->assertFalse($this->Acl->check($user, '/controllers/users/dashboard')); + + $this->assertFalse($this->Acl->check($user, '/controllers/invoices/send')); + // wee add an more specific entry for user foo to also inherit from Role/accounting + $this->Acl->Aro->addRole(array('User/foo' => 'Role/IT, Role/accounting')); + $this->assertTrue($this->Acl->check($user, '/controllers/invoices/send')); + } + +/** + * test check method + * + * @return void + */ + public function testCheck() { + $this->assertTrue($this->Acl->check('jan', '/controllers/users/Dashboard')); + $this->assertTrue($this->Acl->check('some_unknown_role', '/controllers/users/Dashboard')); + $this->assertTrue($this->Acl->check('Role/admin', 'foo/bar')); + $this->assertTrue($this->Acl->check('role/admin', '/foo/bar')); + $this->assertTrue($this->Acl->check('jan', 'foo/bar')); + $this->assertTrue($this->Acl->check('user/jan', 'foo/bar')); + $this->assertTrue($this->Acl->check('Role/admin', 'controllers/bar')); + $this->assertTrue($this->Acl->check(array('User' => array('username' => 'jan')), '/controllers/bar/bll')); + $this->assertTrue($this->Acl->check('Role/database_manager', 'controllers/db/create')); + $this->assertTrue($this->Acl->check('User/db_manager_2', 'controllers/db/create')); + $this->assertFalse($this->Acl->check('db_manager_2', '/controllers/users/Dashboard')); + + // inheritance: hardy -> reports -> data_analyst -> database_manager + $this->assertTrue($this->Acl->check('User/hardy', 'controllers/db/create')); + $this->assertFalse($this->Acl->check('User/jeff', 'controllers/db/create')); + + $this->assertTrue($this->Acl->check('Role/database_manager', 'controllers/db/select')); + $this->assertTrue($this->Acl->check('User/db_manager_2', 'controllers/db/select')); + $this->assertFalse($this->Acl->check('User/jeff', 'controllers/db/select')); + + $this->assertTrue($this->Acl->check('Role/database_manager', 'controllers/db/drop')); + $this->assertTrue($this->Acl->check('User/db_manager_1', 'controllers/db/drop')); + $this->assertFalse($this->Acl->check('db_manager_2', 'controllers/db/drop')); + + $this->assertTrue($this->Acl->check('db_manager_2', 'controllers/invoices/edit')); + $this->assertFalse($this->Acl->check('database_manager', 'controllers/invoices/edit')); + $this->assertFalse($this->Acl->check('db_manager_1', 'controllers/invoices/edit')); + + // Role/manager is allowed /controllers/*/*_manager + $this->assertTrue($this->Acl->check('stan', 'controllers/invoices/manager_edit')); + $this->assertTrue($this->Acl->check('Role/manager', 'controllers/baz/manager_foo')); + $this->assertFalse($this->Acl->check('User/stan', 'custom/foo/manager_edit')); + $this->assertFalse($this->Acl->check('stan', 'bar/baz/manager_foo')); + $this->assertFalse($this->Acl->check('Role/accounting', 'bar/baz/manager_foo')); + $this->assertFalse($this->Acl->check('accounting', 'controllers/baz/manager_foo')); + + $this->assertTrue($this->Acl->check('User/stan', 'controllers/articles/edit')); + $this->assertTrue($this->Acl->check('stan', 'controllers/articles/add')); + $this->assertTrue($this->Acl->check('stan', 'controllers/articles/publish')); + $this->assertFalse($this->Acl->check('User/stan', 'controllers/articles/delete')); + $this->assertFalse($this->Acl->check('accounting', 'controllers/articles/edit')); + $this->assertFalse($this->Acl->check('accounting', 'controllers/articles/add')); + $this->assertFalse($this->Acl->check('role/accounting', 'controllers/articles/publish')); + } + +/** + * lhs of defined rules are case insensitive + */ + public function testCheckIsCaseInsensitive() { + $this->assertTrue($this->Acl->check('hardy', 'controllers/forms/new')); + $this->assertTrue($this->Acl->check('Role/data_acquirer', 'controllers/forms/new')); + $this->assertTrue($this->Acl->check('hardy', 'controllers/FORMS/NEW')); + $this->assertTrue($this->Acl->check('Role/data_acquirer', 'controllers/FORMS/NEW')); + } + +/** + * allow should work in-memory + */ + public function testAllow() { + $this->assertFalse($this->Acl->check('jeff', 'foo/bar')); + + $this->Acl->allow('jeff', 'foo/bar'); + + $this->assertTrue($this->Acl->check('jeff', 'foo/bar')); + $this->assertFalse($this->Acl->check('peter', 'foo/bar')); + $this->assertFalse($this->Acl->check('hardy', 'foo/bar')); + + $this->Acl->allow('Role/accounting', 'foo/bar'); + + $this->assertTrue($this->Acl->check('peter', 'foo/bar')); + $this->assertTrue($this->Acl->check('hardy', 'foo/bar')); + + $this->assertFalse($this->Acl->check('Role/reports', 'foo/bar')); + } + +/** + * deny should work in-memory + */ + public function testDeny() { + $this->assertTrue($this->Acl->check('stan', 'controllers/baz/manager_foo')); + + $this->Acl->deny('stan', 'controllers/baz/manager_foo'); + + $this->assertFalse($this->Acl->check('stan', 'controllers/baz/manager_foo')); + $this->assertTrue($this->Acl->check('Role/manager', 'controllers/baz/manager_foo')); + $this->assertTrue($this->Acl->check('stan', 'controllers/baz/manager_bar')); + $this->assertTrue($this->Acl->check('stan', 'controllers/baz/manager_foooooo')); + } + +/** + * test that a deny rule wins over an equally specific allow rule + */ + public function testDenyRuleIsStrongerThanAllowRule() { + $this->assertFalse($this->Acl->check('peter', 'baz/bam')); + $this->Acl->allow('peter', 'baz/bam'); + $this->assertTrue($this->Acl->check('peter', 'baz/bam')); + $this->Acl->deny('peter', 'baz/bam'); + $this->assertFalse($this->Acl->check('peter', 'baz/bam')); + + $this->assertTrue($this->Acl->check('stan', 'controllers/reports/foo')); + // stan is denied as he's sales and sales is denied /controllers/*/delete + $this->assertFalse($this->Acl->check('stan', 'controllers/reports/delete')); + $this->Acl->allow('stan', 'controllers/reports/delete'); + $this->assertFalse($this->Acl->check('Role/sales', 'controllers/reports/delete')); + $this->assertTrue($this->Acl->check('stan', 'controllers/reports/delete')); + $this->Acl->deny('stan', 'controllers/reports/delete'); + $this->assertFalse($this->Acl->check('stan', 'controllers/reports/delete')); + + // there is already an equally specific deny rule that will win + $this->Acl->allow('stan', 'controllers/reports/delete'); + $this->assertFalse($this->Acl->check('stan', 'controllers/reports/delete')); + } + +/** + * test that an invalid configuration throws exception + */ + public function testInvalidConfigWithAroMissing() { + $this->setExpectedException( + 'AclException', + '"roles" section not found in configuration' + ); + $config = array('aco' => array('allow' => array('foo' => ''))); + $this->PhpAcl->build($config); + } + + public function testInvalidConfigWithAcosMissing() { + $this->setExpectedException( + 'AclException', + 'Neither "allow" nor "deny" rules were provided in configuration.' + ); + + $config = array( + 'roles' => array('Role/foo' => null), + ); + + $this->PhpAcl->build($config); + } + +/** + * test resolving of ACOs + */ + public function testAcoResolve() { + $this->assertEquals(array('foo', 'bar'), $this->Acl->Aco->resolve('foo/bar')); + $this->assertEquals(array('foo', 'bar'), $this->Acl->Aco->resolve('foo/bar')); + $this->assertEquals(array('foo', 'bar', 'baz'), $this->Acl->Aco->resolve('foo/bar/baz')); + $this->assertEquals(array('foo', '*-bar', '?-baz'), $this->Acl->Aco->resolve('foo/*-bar/?-baz')); + + $this->assertEquals(array('foo', 'bar', '[a-f0-9]{24}', '*_bla', 'bla'), $this->Acl->Aco->resolve('foo/bar/[a-f0-9]{24}/*_bla/bla')); + + // multiple slashes will be squashed to a single, trimmed and then exploded + $this->assertEquals(array('foo', 'bar'), $this->Acl->Aco->resolve('foo//bar')); + $this->assertEquals(array('foo', 'bar'), $this->Acl->Aco->resolve('//foo///bar/')); + $this->assertEquals(array('foo', 'bar'), $this->Acl->Aco->resolve('/foo//bar//')); + $this->assertEquals(array('foo', 'bar'), $this->Acl->Aco->resolve('/foo // bar')); + $this->assertEquals(array(), $this->Acl->Aco->resolve('/////')); + } + +/** + * test that declaring cyclic dependencies should give an error when building the tree + */ + public function testAroDeclarationContainsCycles() { + $config = array( + 'roles' => array( + 'Role/a' => null, + 'Role/b' => 'User/b', + 'User/a' => 'Role/a, Role/b', + 'User/b' => 'User/a', + + ), + 'rules' => array( + 'allow' => array( + '*' => 'Role/a', + ), + ), + ); + + $this->expectError('PHPUnit_Framework_Error', 'cycle detected' /* ... */); + $this->PhpAcl->build($config); + } + +/** + * test that with policy allow, only denies count + */ + public function testPolicy() { + // allow by default + $this->Acl->settings['adapter']['policy'] = PhpAcl::ALLOW; + $this->Acl->adapter($this->PhpAcl); + + $this->assertTrue($this->Acl->check('Role/sales', 'foo')); + $this->assertTrue($this->Acl->check('Role/sales', 'controllers/bla/create')); + $this->assertTrue($this->Acl->check('Role/default', 'foo')); + // undefined user, undefined aco + $this->assertTrue($this->Acl->check('foobar', 'foo/bar')); + + // deny rule: Role.sales -> controllers.*.delete + $this->assertFalse($this->Acl->check('Role/sales', 'controllers/bar/delete')); + $this->assertFalse($this->Acl->check('Role/sales', 'controllers/bar', 'delete')); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/AclComponentTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/AclComponentTest.php new file mode 100644 index 0000000..b16d7af --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/AclComponentTest.php @@ -0,0 +1,91 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Controller.Component + * @since CakePHP(tm) v 1.2.0.5435 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ +App::uses('AclComponent', 'Controller/Component'); +class_exists('AclComponent'); + +/** + * Test Case for AclComponent + * + * @package Cake.Test.Case.Controller.Component + */ +class AclComponentTest extends CakeTestCase { + +/** + * setUp method + * + * @return void + */ + public function setUp() { + parent::setUp(); + if (!class_exists('MockAclImplementation', false)) { + $this->getMock('AclInterface', array(), array(), 'MockAclImplementation'); + } + Configure::write('Acl.classname', 'MockAclImplementation'); + $Collection = new ComponentCollection(); + $this->Acl = new AclComponent($Collection); + } + +/** + * tearDown method + * + * @return void + */ + public function tearDown() { + parent::tearDown(); + unset($this->Acl); + } + +/** + * test that constructor throws an exception when Acl.classname is a + * non-existent class + * + * @expectedException CakeException + * @return void + */ + public function testConstrutorException() { + Configure::write('Acl.classname', 'AclClassNameThatDoesNotExist'); + $Collection = new ComponentCollection(); + $acl = new AclComponent($Collection); + } + +/** + * test that adapter() allows control of the internal implementation AclComponent uses. + * + * @return void + */ + public function testAdapter() { + $implementation = new MockAclImplementation(); + $implementation->expects($this->once())->method('initialize')->with($this->Acl); + $this->assertNull($this->Acl->adapter($implementation)); + + $this->assertEquals($this->Acl->adapter(), $implementation, 'Returned object is different %s'); + } + +/** + * test that adapter() whines when the class is not an AclBase + * + * @expectedException CakeException + * @return void + */ + public function testAdapterException() { + $thing = new StdClass(); + $this->Acl->adapter($thing); + } + +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/Auth/ActionsAuthorizeTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/Auth/ActionsAuthorizeTest.php new file mode 100644 index 0000000..6b06b37 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/Auth/ActionsAuthorizeTest.php @@ -0,0 +1,192 @@ +controller = $this->getMock('Controller', array(), array(), '', false); + $this->Acl = $this->getMock('AclComponent', array(), array(), '', false); + $this->Collection = $this->getMock('ComponentCollection'); + + $this->auth = new ActionsAuthorize($this->Collection); + $this->auth->settings['actionPath'] = '/controllers'; + } + +/** + * setup the mock acl. + * + * @return void + */ + protected function _mockAcl() { + $this->Collection->expects($this->any()) + ->method('load') + ->with('Acl') + ->will($this->returnValue($this->Acl)); + } + +/** + * test failure + * + * @return void + */ + public function testAuthorizeFailure() { + $user = array( + 'User' => array( + 'id' => 1, + 'user' => 'mariano' + ) + ); + $request = new CakeRequest('/posts/index', false); + $request->addParams(array( + 'plugin' => null, + 'controller' => 'posts', + 'action' => 'index' + )); + + $this->_mockAcl(); + + $this->Acl->expects($this->once()) + ->method('check') + ->with($user, 'controllers/Posts/index') + ->will($this->returnValue(false)); + + $this->assertFalse($this->auth->authorize($user['User'], $request)); + } + +/** + * test isAuthorized working. + * + * @return void + */ + public function testAuthorizeSuccess() { + $user = array( + 'User' => array( + 'id' => 1, + 'user' => 'mariano' + ) + ); + $request = new CakeRequest('/posts/index', false); + $request->addParams(array( + 'plugin' => null, + 'controller' => 'posts', + 'action' => 'index' + )); + + $this->_mockAcl(); + + $this->Acl->expects($this->once()) + ->method('check') + ->with($user, 'controllers/Posts/index') + ->will($this->returnValue(true)); + + $this->assertTrue($this->auth->authorize($user['User'], $request)); + } + +/** + * testAuthorizeSettings + * + * @return void + */ + public function testAuthorizeSettings() { + $request = new CakeRequest('/posts/index', false); + $request->addParams(array( + 'plugin' => null, + 'controller' => 'posts', + 'action' => 'index' + )); + + $this->_mockAcl(); + + $this->auth->settings['userModel'] = 'TestPlugin.TestPluginAuthUser'; + $user = array( + 'id' => 1, + 'user' => 'mariano' + ); + + $expected = array('TestPlugin.TestPluginAuthUser' => array('id' => 1, 'user' => 'mariano')); + $this->Acl->expects($this->once()) + ->method('check') + ->with($expected, 'controllers/Posts/index') + ->will($this->returnValue(true)); + + $this->assertTrue($this->auth->authorize($user, $request)); + } + +/** + * test action() + * + * @return void + */ + public function testActionMethod() { + $request = new CakeRequest('/posts/index', false); + $request->addParams(array( + 'plugin' => null, + 'controller' => 'posts', + 'action' => 'index' + )); + + $result = $this->auth->action($request); + $this->assertEquals('controllers/Posts/index', $result); + } + +/** + * Make sure that action() doesn't create double slashes anywhere. + * + * @return void + */ + public function testActionNoDoubleSlash() { + $this->auth->settings['actionPath'] = '/controllers/'; + $request = array( + 'plugin' => null, + 'controller' => 'posts', + 'action' => 'index' + ); + $result = $this->auth->action($request); + $this->assertEquals('controllers/Posts/index', $result); + } + +/** + * test action() and plugins + * + * @return void + */ + public function testActionWithPlugin() { + $request = new CakeRequest('/debug_kit/posts/index', false); + $request->addParams(array( + 'plugin' => 'debug_kit', + 'controller' => 'posts', + 'action' => 'index' + )); + + $result = $this->auth->action($request); + $this->assertEquals('controllers/DebugKit/Posts/index', $result); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/Auth/BasicAuthenticateTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/Auth/BasicAuthenticateTest.php new file mode 100644 index 0000000..b1affff --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/Auth/BasicAuthenticateTest.php @@ -0,0 +1,206 @@ +Collection = $this->getMock('ComponentCollection'); + $this->auth = new BasicAuthenticate($this->Collection, array( + 'fields' => array('username' => 'user', 'password' => 'password'), + 'userModel' => 'User', + 'realm' => 'localhost', + 'recursive' => 0 + )); + + $password = Security::hash('password', null, true); + $User = ClassRegistry::init('User'); + $User->updateAll(array('password' => $User->getDataSource()->value($password))); + $this->response = $this->getMock('CakeResponse'); + } + +/** + * test applying settings in the constructor + * + * @return void + */ + public function testConstructor() { + $object = new BasicAuthenticate($this->Collection, array( + 'userModel' => 'AuthUser', + 'fields' => array('username' => 'user', 'password' => 'password') + )); + $this->assertEquals('AuthUser', $object->settings['userModel']); + $this->assertEquals(array('username' => 'user', 'password' => 'password'), $object->settings['fields']); + $this->assertEquals(env('SERVER_NAME'), $object->settings['realm']); + } + +/** + * test the authenticate method + * + * @return void + */ + public function testAuthenticateNoData() { + $request = new CakeRequest('posts/index', false); + + $this->response->expects($this->once()) + ->method('header') + ->with('WWW-Authenticate: Basic realm="localhost"'); + + $this->assertFalse($this->auth->authenticate($request, $this->response)); + } + +/** + * test the authenticate method + * + * @return void + */ + public function testAuthenticateNoUsername() { + $request = new CakeRequest('posts/index', false); + $_SERVER['PHP_AUTH_PW'] = 'foobar'; + + $this->response->expects($this->once()) + ->method('header') + ->with('WWW-Authenticate: Basic realm="localhost"'); + + $this->assertFalse($this->auth->authenticate($request, $this->response)); + } + +/** + * test the authenticate method + * + * @return void + */ + public function testAuthenticateNoPassword() { + $request = new CakeRequest('posts/index', false); + $_SERVER['PHP_AUTH_USER'] = 'mariano'; + $_SERVER['PHP_AUTH_PW'] = null; + + $this->response->expects($this->once()) + ->method('header') + ->with('WWW-Authenticate: Basic realm="localhost"'); + + $this->assertFalse($this->auth->authenticate($request, $this->response)); + } + +/** + * test the authenticate method + * + * @return void + */ + public function testAuthenticateInjection() { + $request = new CakeRequest('posts/index', false); + $request->addParams(array('pass' => array(), 'named' => array())); + + $_SERVER['PHP_AUTH_USER'] = '> 1'; + $_SERVER['PHP_AUTH_PW'] = "' OR 1 = 1"; + + $this->assertFalse($this->auth->authenticate($request, $this->response)); + } + +/** + * test that challenge headers are sent when no credentials are found. + * + * @return void + */ + public function testAuthenticateChallenge() { + $request = new CakeRequest('posts/index', false); + $request->addParams(array('pass' => array(), 'named' => array())); + + $this->response->expects($this->at(0)) + ->method('header') + ->with('WWW-Authenticate: Basic realm="localhost"'); + + $this->response->expects($this->at(1)) + ->method('send'); + + $result = $this->auth->authenticate($request, $this->response); + $this->assertFalse($result); + } + +/** + * test authenticate sucesss + * + * @return void + */ + public function testAuthenticateSuccess() { + $request = new CakeRequest('posts/index', false); + $request->addParams(array('pass' => array(), 'named' => array())); + + $_SERVER['PHP_AUTH_USER'] = 'mariano'; + $_SERVER['PHP_AUTH_PW'] = 'password'; + + $result = $this->auth->authenticate($request, $this->response); + $expected = array( + 'id' => 1, + 'user' => 'mariano', + 'created' => '2007-03-17 01:16:23', + 'updated' => '2007-03-17 01:18:31' + ); + $this->assertEquals($expected, $result); + } + +/** + * test scope failure. + * + * @return void + */ + public function testAuthenticateFailReChallenge() { + $this->auth->settings['scope'] = array('user' => 'nate'); + $request = new CakeRequest('posts/index', false); + $request->addParams(array('pass' => array(), 'named' => array())); + + $_SERVER['PHP_AUTH_USER'] = 'mariano'; + $_SERVER['PHP_AUTH_PW'] = 'password'; + + $this->response->expects($this->at(0)) + ->method('header') + ->with('WWW-Authenticate: Basic realm="localhost"'); + + $this->response->expects($this->at(1)) + ->method('statusCode') + ->with(401); + + $this->response->expects($this->at(2)) + ->method('send'); + + $this->assertFalse($this->auth->authenticate($request, $this->response)); + } + +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/Auth/ControllerAuthorizeTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/Auth/ControllerAuthorizeTest.php new file mode 100644 index 0000000..a1dae91 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/Auth/ControllerAuthorizeTest.php @@ -0,0 +1,84 @@ +controller = $this->getMock('Controller', array('isAuthorized'), array(), '', false); + $this->components = $this->getMock('ComponentCollection'); + $this->components->expects($this->any()) + ->method('getController') + ->will($this->returnValue($this->controller)); + + $this->auth = new ControllerAuthorize($this->components); + } + +/** + * @expectedException PHPUnit_Framework_Error + */ + public function testControllerTypeError() { + $this->auth->controller(new StdClass()); + } + +/** + * @expectedException CakeException + */ + public function testControllerErrorOnMissingMethod() { + $this->auth->controller(new Controller()); + } + +/** + * test failure + * + * @return void + */ + public function testAuthorizeFailure() { + $user = array(); + $request = new CakeRequest('/posts/index', false); + $this->assertFalse($this->auth->authorize($user, $request)); + } + +/** + * test isAuthorized working. + * + * @return void + */ + public function testAuthorizeSuccess() { + $user = array('User' => array('username' => 'mark')); + $request = new CakeRequest('/posts/index', false); + + $this->controller->expects($this->once()) + ->method('isAuthorized') + ->with($user) + ->will($this->returnValue(true)); + + $this->assertTrue($this->auth->authorize($user, $request)); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/Auth/CrudAuthorizeTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/Auth/CrudAuthorizeTest.php new file mode 100644 index 0000000..859e424 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/Auth/CrudAuthorizeTest.php @@ -0,0 +1,185 @@ +Acl = $this->getMock('AclComponent', array(), array(), '', false); + $this->Components = $this->getMock('ComponentCollection'); + + $this->auth = new CrudAuthorize($this->Components); + } + +/** + * setup the mock acl. + * + * @return void + */ + protected function _mockAcl() { + $this->Components->expects($this->any()) + ->method('load') + ->with('Acl') + ->will($this->returnValue($this->Acl)); + } + +/** + * test authorize() without a mapped action, ensure an error is generated. + * + * @expectedException PHPUnit_Framework_Error_Warning + * @return void + */ + public function testAuthorizeNoMappedAction() { + $request = new CakeRequest('/posts/foobar', false); + $request->addParams(array( + 'controller' => 'posts', + 'action' => 'foobar' + )); + $user = array('User' => array('user' => 'mark')); + + $this->auth->authorize($user, $request); + } + +/** + * test check() passing + * + * @return void + */ + public function testAuthorizeCheckSuccess() { + $request = new CakeRequest('posts/index', false); + $request->addParams(array( + 'controller' => 'posts', + 'action' => 'index' + )); + $user = array('User' => array('user' => 'mark')); + + $this->_mockAcl(); + $this->Acl->expects($this->once()) + ->method('check') + ->with($user, 'Posts', 'read') + ->will($this->returnValue(true)); + + $this->assertTrue($this->auth->authorize($user['User'], $request)); + } + +/** + * test check() failing + * + * @return void + */ + public function testAuthorizeCheckFailure() { + $request = new CakeRequest('posts/index', false); + $request->addParams(array( + 'controller' => 'posts', + 'action' => 'index' + )); + $user = array('User' => array('user' => 'mark')); + + $this->_mockAcl(); + $this->Acl->expects($this->once()) + ->method('check') + ->with($user, 'Posts', 'read') + ->will($this->returnValue(false)); + + $this->assertFalse($this->auth->authorize($user['User'], $request)); + } + +/** + * test getting actionMap + * + * @return void + */ + public function testMapActionsGet() { + $result = $this->auth->mapActions(); + $expected = array( + 'create' => 'create', + 'read' => 'read', + 'update' => 'update', + 'delete' => 'delete', + 'index' => 'read', + 'add' => 'create', + 'edit' => 'update', + 'view' => 'read', + 'remove' => 'delete' + ); + $this->assertEquals($expected, $result); + } + +/** + * test adding into mapActions + * + * @return void + */ + public function testMapActionsSet() { + $map = array( + 'create' => array('generate'), + 'read' => array('listing', 'show'), + 'update' => array('update'), + 'random' => 'custom' + ); + $result = $this->auth->mapActions($map); + $this->assertNull($result); + + $result = $this->auth->mapActions(); + $expected = array( + 'add' => 'create', + 'create' => 'create', + 'read' => 'read', + 'index' => 'read', + 'add' => 'create', + 'edit' => 'update', + 'view' => 'read', + 'delete' => 'delete', + 'remove' => 'delete', + 'generate' => 'create', + 'listing' => 'read', + 'show' => 'read', + 'update' => 'update', + 'random' => 'custom', + ); + $this->assertEquals($expected, $result); + } + +/** + * test prefix routes getting auto mapped. + * + * @return void + */ + public function testAutoPrefixMapActions() { + Configure::write('Routing.prefixes', array('admin', 'manager')); + Router::reload(); + + $auth = new CrudAuthorize($this->Components); + $this->assertTrue(isset($auth->settings['actionMap']['admin_index'])); + } + +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/Auth/DigestAuthenticateTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/Auth/DigestAuthenticateTest.php new file mode 100644 index 0000000..f9ca831 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/Auth/DigestAuthenticateTest.php @@ -0,0 +1,306 @@ +Collection = $this->getMock('ComponentCollection'); + $this->server = $_SERVER; + $this->auth = new DigestAuthenticate($this->Collection, array( + 'fields' => array('username' => 'user', 'password' => 'password'), + 'userModel' => 'User', + 'realm' => 'localhost', + 'nonce' => 123, + 'opaque' => '123abc' + )); + + $password = DigestAuthenticate::password('mariano', 'cake', 'localhost'); + $User = ClassRegistry::init('User'); + $User->updateAll(array('password' => $User->getDataSource()->value($password))); + + $_SERVER['REQUEST_METHOD'] = 'GET'; + $this->response = $this->getMock('CakeResponse'); + } + +/** + * tearDown + * + * @return void + */ + public function tearDown() { + parent::tearDown(); + $_SERVER = $this->server; + } + +/** + * test applying settings in the constructor + * + * @return void + */ + public function testConstructor() { + $object = new DigestAuthenticate($this->Collection, array( + 'userModel' => 'AuthUser', + 'fields' => array('username' => 'user', 'password' => 'password'), + 'nonce' => 123456 + )); + $this->assertEquals('AuthUser', $object->settings['userModel']); + $this->assertEquals(array('username' => 'user', 'password' => 'password'), $object->settings['fields']); + $this->assertEquals(123456, $object->settings['nonce']); + $this->assertEquals(env('SERVER_NAME'), $object->settings['realm']); + } + +/** + * test the authenticate method + * + * @return void + */ + public function testAuthenticateNoData() { + $request = new CakeRequest('posts/index', false); + + $this->response->expects($this->once()) + ->method('header') + ->with('WWW-Authenticate: Digest realm="localhost",qop="auth",nonce="123",opaque="123abc"'); + + $this->assertFalse($this->auth->authenticate($request, $this->response)); + } + +/** + * test the authenticate method + * + * @return void + */ + public function testAuthenticateWrongUsername() { + $request = new CakeRequest('posts/index', false); + $request->addParams(array('pass' => array(), 'named' => array())); + + $_SERVER['PHP_AUTH_DIGEST'] = <<response->expects($this->at(0)) + ->method('header') + ->with('WWW-Authenticate: Digest realm="localhost",qop="auth",nonce="123",opaque="123abc"'); + + $this->response->expects($this->at(1)) + ->method('statusCode') + ->with(401); + + $this->response->expects($this->at(2)) + ->method('send'); + + $this->assertFalse($this->auth->authenticate($request, $this->response)); + } + +/** + * test that challenge headers are sent when no credentials are found. + * + * @return void + */ + public function testAuthenticateChallenge() { + $request = new CakeRequest('posts/index', false); + $request->addParams(array('pass' => array(), 'named' => array())); + + $this->response->expects($this->at(0)) + ->method('header') + ->with('WWW-Authenticate: Digest realm="localhost",qop="auth",nonce="123",opaque="123abc"'); + + $this->response->expects($this->at(1)) + ->method('statusCode') + ->with(401); + + $this->response->expects($this->at(2)) + ->method('send'); + + $result = $this->auth->authenticate($request, $this->response); + $this->assertFalse($result); + } + +/** + * test authenticate success + * + * @return void + */ + public function testAuthenticateSuccess() { + $request = new CakeRequest('posts/index', false); + $request->addParams(array('pass' => array(), 'named' => array())); + + $_SERVER['PHP_AUTH_DIGEST'] = <<auth->authenticate($request, $this->response); + $expected = array( + 'id' => 1, + 'user' => 'mariano', + 'created' => '2007-03-17 01:16:23', + 'updated' => '2007-03-17 01:18:31' + ); + $this->assertEquals($expected, $result); + } + +/** + * test scope failure. + * + * @return void + */ + public function testAuthenticateFailReChallenge() { + $this->auth->settings['scope'] = array('user' => 'nate'); + $request = new CakeRequest('posts/index', false); + $request->addParams(array('pass' => array(), 'named' => array())); + + $_SERVER['PHP_AUTH_DIGEST'] = <<response->expects($this->at(0)) + ->method('header') + ->with('WWW-Authenticate: Digest realm="localhost",qop="auth",nonce="123",opaque="123abc"'); + + $this->response->expects($this->at(1)) + ->method('statusCode') + ->with(401); + + $this->response->expects($this->at(2)) + ->method('send'); + + $this->assertFalse($this->auth->authenticate($request, $this->response)); + } + +/** + * testParseDigestAuthData method + * + * @return void + */ + public function testParseAuthData() { + $digest = << 'Mufasa', + 'realm' => 'testrealm@host.com', + 'nonce' => 'dcd98b7102dd2f0e8b11d0f600bfb0c093', + 'uri' => '/dir/index.html', + 'qop' => 'auth', + 'nc' => '00000001', + 'cnonce' => '0a4f113b', + 'response' => '6629fae49393a05397450978507c4ef1', + 'opaque' => '5ccc069c403ebaf9f0171e9517f40e41' + ); + $result = $this->auth->parseAuthData($digest); + $this->assertSame($expected, $result); + + $result = $this->auth->parseAuthData(''); + $this->assertNull($result); + } + +/** + * test parsing digest information with email addresses + * + * @return void + */ + public function testParseAuthEmailAddress() { + $digest = << 'mark@example.com', + 'realm' => 'testrealm@host.com', + 'nonce' => 'dcd98b7102dd2f0e8b11d0f600bfb0c093', + 'uri' => '/dir/index.html', + 'qop' => 'auth', + 'nc' => '00000001', + 'cnonce' => '0a4f113b', + 'response' => '6629fae49393a05397450978507c4ef1', + 'opaque' => '5ccc069c403ebaf9f0171e9517f40e41' + ); + $result = $this->auth->parseAuthData($digest); + $this->assertSame($expected, $result); + } + +/** + * test password hashing + * + * @return void + */ + public function testPassword() { + $result = DigestAuthenticate::password('mark', 'password', 'localhost'); + $expected = md5('mark:localhost:password'); + $this->assertEquals($expected, $result); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/Auth/FormAuthenticateTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/Auth/FormAuthenticateTest.php new file mode 100644 index 0000000..a65e04f --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/Auth/FormAuthenticateTest.php @@ -0,0 +1,193 @@ +Collection = $this->getMock('ComponentCollection'); + $this->auth = new FormAuthenticate($this->Collection, array( + 'fields' => array('username' => 'user', 'password' => 'password'), + 'userModel' => 'User' + )); + $password = Security::hash('password', null, true); + $User = ClassRegistry::init('User'); + $User->updateAll(array('password' => $User->getDataSource()->value($password))); + $this->response = $this->getMock('CakeResponse'); + } + +/** + * test applying settings in the constructor + * + * @return void + */ + public function testConstructor() { + $object = new FormAuthenticate($this->Collection, array( + 'userModel' => 'AuthUser', + 'fields' => array('username' => 'user', 'password' => 'password') + )); + $this->assertEquals('AuthUser', $object->settings['userModel']); + $this->assertEquals(array('username' => 'user', 'password' => 'password'), $object->settings['fields']); + } + +/** + * test the authenticate method + * + * @return void + */ + public function testAuthenticateNoData() { + $request = new CakeRequest('posts/index', false); + $request->data = array(); + $this->assertFalse($this->auth->authenticate($request, $this->response)); + } + +/** + * test the authenticate method + * + * @return void + */ + public function testAuthenticateNoUsername() { + $request = new CakeRequest('posts/index', false); + $request->data = array('User' => array('password' => 'foobar')); + $this->assertFalse($this->auth->authenticate($request, $this->response)); + } + +/** + * test the authenticate method + * + * @return void + */ + public function testAuthenticateNoPassword() { + $request = new CakeRequest('posts/index', false); + $request->data = array('User' => array('user' => 'mariano')); + $this->assertFalse($this->auth->authenticate($request, $this->response)); + } + +/** + * test the authenticate method + * + * @return void + */ + public function testAuthenticateInjection() { + $request = new CakeRequest('posts/index', false); + $request->data = array( + 'User' => array( + 'user' => '> 1', + 'password' => "' OR 1 = 1" + )); + $this->assertFalse($this->auth->authenticate($request, $this->response)); + } + +/** + * test authenticate success + * + * @return void + */ + public function testAuthenticateSuccess() { + $request = new CakeRequest('posts/index', false); + $request->data = array('User' => array( + 'user' => 'mariano', + 'password' => 'password' + )); + $result = $this->auth->authenticate($request, $this->response); + $expected = array( + 'id' => 1, + 'user' => 'mariano', + 'created' => '2007-03-17 01:16:23', + 'updated' => '2007-03-17 01:18:31' + ); + $this->assertEquals($expected, $result); + } + +/** + * test scope failure. + * + * @return void + */ + public function testAuthenticateScopeFail() { + $this->auth->settings['scope'] = array('user' => 'nate'); + $request = new CakeRequest('posts/index', false); + $request->data = array('User' => array( + 'user' => 'mariano', + 'password' => 'password' + )); + + $this->assertFalse($this->auth->authenticate($request, $this->response)); + } + +/** + * test a model in a plugin. + * + * @return void + */ + public function testPluginModel() { + Cache::delete('object_map', '_cake_core_'); + App::build(array( + 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS), + ), App::RESET); + CakePlugin::load('TestPlugin'); + + $PluginModel = ClassRegistry::init('TestPlugin.TestPluginAuthUser'); + $user['id'] = 1; + $user['username'] = 'gwoo'; + $user['password'] = Security::hash(Configure::read('Security.salt') . 'cake'); + $PluginModel->save($user, false); + + $this->auth->settings['userModel'] = 'TestPlugin.TestPluginAuthUser'; + $this->auth->settings['fields']['username'] = 'username'; + + $request = new CakeRequest('posts/index', false); + $request->data = array('TestPluginAuthUser' => array( + 'username' => 'gwoo', + 'password' => 'cake' + )); + + $result = $this->auth->authenticate($request, $this->response); + $expected = array( + 'id' => 1, + 'username' => 'gwoo', + 'created' => '2007-03-17 01:16:23' + ); + $this->assertEquals(self::date(), $result['updated']); + unset($result['updated']); + $this->assertEquals($expected, $result); + CakePlugin::unload(); + } + +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/AuthComponentTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/AuthComponentTest.php new file mode 100644 index 0000000..11546e1 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/AuthComponentTest.php @@ -0,0 +1,1290 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Controller.Component + * @since CakePHP(tm) v 1.2.0.5347 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ + +App::uses('Controller', 'Controller'); +App::uses('AuthComponent', 'Controller/Component'); +App::uses('AclComponent', 'Controller/Component'); +App::uses('FormAuthenticate', 'Controller/Component/Auth'); + +/** + * TestAuthComponent class + * + * @package Cake.Test.Case.Controller.Component + * @package Cake.Test.Case.Controller.Component + */ +class TestAuthComponent extends AuthComponent { + +/** + * testStop property + * + * @var bool false + */ + public $testStop = false; + +/** + * stop method + * + * @return void + */ + protected function _stop($status = 0) { + $this->testStop = true; + } + + public static function clearUser() { + self::$_user = array(); + } + +} + +/** + * AuthUser class + * + * @package Cake.Test.Case.Controller.Component + * @package Cake.Test.Case.Controller.Component + */ +class AuthUser extends CakeTestModel { + +/** + * name property + * + * @var string 'AuthUser' + */ + public $name = 'AuthUser'; + +/** + * useDbConfig property + * + * @var string 'test' + */ + public $useDbConfig = 'test'; + +} + +/** + * AuthTestController class + * + * @package Cake.Test.Case.Controller.Component + * @package Cake.Test.Case.Controller.Component + */ +class AuthTestController extends Controller { + +/** + * name property + * + * @var string 'AuthTest' + */ + public $name = 'AuthTest'; + +/** + * uses property + * + * @var array + */ + public $uses = array('AuthUser'); + +/** + * components property + * + * @var array + */ + public $components = array('Session', 'Auth'); + +/** + * testUrl property + * + * @var mixed null + */ + public $testUrl = null; + +/** + * construct method + * + * @return void + */ + public function __construct($request, $response) { + $request->addParams(Router::parse('/auth_test')); + $request->here = '/auth_test'; + $request->webroot = '/'; + Router::setRequestInfo($request); + parent::__construct($request, $response); + } + +/** + * login method + * + * @return void + */ + public function login() { + } + +/** + * admin_login method + * + * @return void + */ + public function admin_login() { + } + +/** + * admin_add method + * + * @return void + */ + public function admin_add() { + } + +/** + * logout method + * + * @return void + */ + public function logout() { + } + +/** + * add method + * + * @return void + */ + public function add() { + echo "add"; + } + +/** + * add method + * + * @return void + */ + public function camelCase() { + echo "camelCase"; + } + +/** + * redirect method + * + * @param string|array $url + * @param mixed $status + * @param mixed $exit + * @return void + */ + public function redirect($url, $status = null, $exit = true) { + $this->testUrl = Router::url($url); + return false; + } + +/** + * isAuthorized method + * + * @return void + */ + public function isAuthorized() { + } + +} + +/** + * AjaxAuthController class + * + * @package Cake.Test.Case.Controller.Component + */ +class AjaxAuthController extends Controller { + +/** + * name property + * + * @var string 'AjaxAuth' + */ + public $name = 'AjaxAuth'; + +/** + * components property + * + * @var array + */ + public $components = array('Session', 'TestAuth'); + +/** + * uses property + * + * @var array + */ + public $uses = array(); + +/** + * testUrl property + * + * @var mixed null + */ + public $testUrl = null; + +/** + * beforeFilter method + * + * @return void + */ + public function beforeFilter() { + $this->TestAuth->ajaxLogin = 'test_element'; + $this->TestAuth->userModel = 'AuthUser'; + $this->TestAuth->RequestHandler->ajaxLayout = 'ajax2'; + } + +/** + * add method + * + * @return void + */ + public function add() { + if ($this->TestAuth->testStop !== true) { + echo 'Added Record'; + } + } + +/** + * redirect method + * + * @param string|array $url + * @param mixed $status + * @param mixed $exit + * @return void + */ + public function redirect($url, $status = null, $exit = true) { + $this->testUrl = Router::url($url); + return false; + } + +} + +/** + * AuthComponentTest class + * + * @package Cake.Test.Case.Controller.Component + * @package Cake.Test.Case.Controller.Component + */ +class AuthComponentTest extends CakeTestCase { + +/** + * name property + * + * @var string 'Auth' + */ + public $name = 'Auth'; + +/** + * fixtures property + * + * @var array + */ + public $fixtures = array('core.auth_user'); + +/** + * initialized property + * + * @var bool false + */ + public $initialized = false; + +/** + * setUp method + * + * @return void + */ + public function setUp() { + parent::setUp(); + Configure::write('Security.salt', 'YJfIxfs2guVoUubWDYhG93b0qyJfIxfs2guwvniR2G0FgaC9mi'); + Configure::write('Security.cipherSeed', 770011223369876); + + $request = new CakeRequest(null, false); + + $this->Controller = new AuthTestController($request, $this->getMock('CakeResponse')); + + $collection = new ComponentCollection(); + $collection->init($this->Controller); + $this->Auth = new TestAuthComponent($collection); + $this->Auth->request = $request; + $this->Auth->response = $this->getMock('CakeResponse'); + + $this->Controller->Components->init($this->Controller); + + $this->initialized = true; + Router::reload(); + Router::connect('/:controller/:action/*'); + + $User = ClassRegistry::init('AuthUser'); + $User->updateAll(array('password' => $User->getDataSource()->value(Security::hash('cake', null, true)))); + } + +/** + * tearDown method + * + * @return void + */ + public function tearDown() { + parent::tearDown(); + + TestAuthComponent::clearUser(); + $this->Auth->Session->delete('Auth'); + $this->Auth->Session->delete('Message.auth'); + unset($this->Controller, $this->Auth); + } + +/** + * testNoAuth method + * + * @return void + */ + public function testNoAuth() { + $this->assertFalse($this->Auth->isAuthorized()); + } + +/** + * testIsErrorOrTests + * + * @return void + */ + public function testIsErrorOrTests() { + $this->Controller->Auth->initialize($this->Controller); + + $this->Controller->name = 'CakeError'; + $this->assertTrue($this->Controller->Auth->startup($this->Controller)); + + $this->Controller->name = 'Post'; + $this->Controller->request['action'] = 'thisdoesnotexist'; + $this->assertTrue($this->Controller->Auth->startup($this->Controller)); + + $this->Controller->scaffold = null; + $this->Controller->request['action'] = 'index'; + $this->assertFalse($this->Controller->Auth->startup($this->Controller)); + } + +/** + * testLogin method + * + * @return void + */ + public function testLogin() { + $this->getMock('FormAuthenticate', array(), array(), 'AuthLoginFormAuthenticate', false); + $this->Auth->authenticate = array( + 'AuthLoginForm' => array( + 'userModel' => 'AuthUser' + ) + ); + $this->Auth->Session = $this->getMock('SessionComponent', array('renew'), array(), '', false); + + $mocks = $this->Auth->constructAuthenticate(); + $this->mockObjects[] = $mocks[0]; + + $this->Auth->request->data = array( + 'AuthUser' => array( + 'username' => 'mark', + 'password' => Security::hash('cake', null, true) + ) + ); + + $user = array( + 'id' => 1, + 'username' => 'mark' + ); + + $mocks[0]->expects($this->once()) + ->method('authenticate') + ->with($this->Auth->request) + ->will($this->returnValue($user)); + + $this->Auth->Session->expects($this->once()) + ->method('renew'); + + $result = $this->Auth->login(); + $this->assertTrue($result); + + $this->assertTrue($this->Auth->loggedIn()); + $this->assertEquals($user, $this->Auth->user()); + } + +/** + * test that being redirected to the login page, with no post data does + * not set the session value. Saving the session value in this circumstance + * can cause the user to be redirected to an already public page. + * + * @return void + */ + public function testLoginActionNotSettingAuthRedirect() { + $_SERVER['HTTP_REFERER'] = '/pages/display/about'; + + $this->Controller->data = array(); + $this->Controller->request->addParams(Router::parse('auth_test/login')); + $this->Controller->request->url = 'auth_test/login'; + $this->Auth->Session->delete('Auth'); + + $this->Auth->loginRedirect = '/users/dashboard'; + $this->Auth->loginAction = 'auth_test/login'; + $this->Auth->userModel = 'AuthUser'; + + $this->Auth->startup($this->Controller); + $redirect = $this->Auth->Session->read('Auth.redirect'); + $this->assertNull($redirect); + } + +/** + * testAuthorizeFalse method + * + * @return void + */ + public function testAuthorizeFalse() { + $this->AuthUser = new AuthUser(); + $user = $this->AuthUser->find(); + $this->Auth->Session->write('Auth.User', $user['AuthUser']); + $this->Controller->Auth->userModel = 'AuthUser'; + $this->Controller->Auth->authorize = false; + $this->Controller->request->addParams(Router::parse('auth_test/add')); + $result = $this->Controller->Auth->startup($this->Controller); + $this->assertTrue($result); + + $this->Auth->Session->delete('Auth'); + $result = $this->Controller->Auth->startup($this->Controller); + $this->assertFalse($result); + $this->assertTrue($this->Auth->Session->check('Message.auth')); + + $this->Controller->request->addParams(Router::parse('auth_test/camelCase')); + $result = $this->Controller->Auth->startup($this->Controller); + $this->assertFalse($result); + } + +/** + * @expectedException CakeException + * @return void + */ + public function testIsAuthorizedMissingFile() { + $this->Controller->Auth->authorize = 'Missing'; + $this->Controller->Auth->isAuthorized(array('User' => array('id' => 1))); + } + +/** + * test that isAuthorized calls methods correctly + * + * @return void + */ + public function testIsAuthorizedDelegation() { + $this->getMock('BaseAuthorize', array('authorize'), array(), 'AuthMockOneAuthorize', false); + $this->getMock('BaseAuthorize', array('authorize'), array(), 'AuthMockTwoAuthorize', false); + $this->getMock('BaseAuthorize', array('authorize'), array(), 'AuthMockThreeAuthorize', false); + + $this->Auth->authorize = array( + 'AuthMockOne', + 'AuthMockTwo', + 'AuthMockThree' + ); + $mocks = $this->Auth->constructAuthorize(); + $request = $this->Auth->request; + + $this->assertEquals(3, count($mocks)); + $mocks[0]->expects($this->once()) + ->method('authorize') + ->with(array('User'), $request) + ->will($this->returnValue(false)); + + $mocks[1]->expects($this->once()) + ->method('authorize') + ->with(array('User'), $request) + ->will($this->returnValue(true)); + + $mocks[2]->expects($this->never()) + ->method('authorize'); + + $this->assertTrue($this->Auth->isAuthorized(array('User'), $request)); + } + +/** + * test that isAuthorized will use the session user if none is given. + * + * @return void + */ + public function testIsAuthorizedUsingUserInSession() { + $this->getMock('BaseAuthorize', array('authorize'), array(), 'AuthMockFourAuthorize', false); + $this->Auth->authorize = array('AuthMockFour'); + + $user = array('user' => 'mark'); + $this->Auth->Session->write('Auth.User', $user); + $mocks = $this->Auth->constructAuthorize(); + $request = $this->Controller->request; + + $mocks[0]->expects($this->once()) + ->method('authorize') + ->with($user, $request) + ->will($this->returnValue(true)); + + $this->assertTrue($this->Auth->isAuthorized(null, $request)); + } + +/** + * test that loadAuthorize resets the loaded objects each time. + * + * @return void + */ + public function testLoadAuthorizeResets() { + $this->Controller->Auth->authorize = array( + 'Controller' + ); + $result = $this->Controller->Auth->constructAuthorize(); + $this->assertEquals(1, count($result)); + + $result = $this->Controller->Auth->constructAuthorize(); + $this->assertEquals(1, count($result)); + } + +/** + * @expectedException CakeException + * @return void + */ + public function testLoadAuthenticateNoFile() { + $this->Controller->Auth->authenticate = 'Missing'; + $this->Controller->Auth->identify($this->Controller->request, $this->Controller->response); + } + +/** + * test the * key with authenticate + * + * @return void + */ + public function testAllConfigWithAuthorize() { + $this->Controller->Auth->authorize = array( + AuthComponent::ALL => array('actionPath' => 'controllers/'), + 'Actions' + ); + $objects = $this->Controller->Auth->constructAuthorize(); + $result = $objects[0]; + $this->assertEquals('controllers/', $result->settings['actionPath']); + } + +/** + * test that loadAuthorize resets the loaded objects each time. + * + * @return void + */ + public function testLoadAuthenticateResets() { + $this->Controller->Auth->authenticate = array( + 'Form' + ); + $result = $this->Controller->Auth->constructAuthenticate(); + $this->assertEquals(1, count($result)); + + $result = $this->Controller->Auth->constructAuthenticate(); + $this->assertEquals(1, count($result)); + } + +/** + * test the * key with authenticate + * + * @return void + */ + public function testAllConfigWithAuthenticate() { + $this->Controller->Auth->authenticate = array( + AuthComponent::ALL => array('userModel' => 'AuthUser'), + 'Form' + ); + $objects = $this->Controller->Auth->constructAuthenticate(); + $result = $objects[0]; + $this->assertEquals('AuthUser', $result->settings['userModel']); + } + +/** + * Tests that deny always takes precedence over allow + * + * @return void + */ + public function testAllowDenyAll() { + $this->Controller->Auth->initialize($this->Controller); + + $this->Controller->Auth->allow(); + $this->Controller->Auth->deny('add', 'camelCase'); + + $this->Controller->request['action'] = 'delete'; + $this->assertTrue($this->Controller->Auth->startup($this->Controller)); + + $this->Controller->request['action'] = 'add'; + $this->assertFalse($this->Controller->Auth->startup($this->Controller)); + + $this->Controller->request['action'] = 'camelCase'; + $this->assertFalse($this->Controller->Auth->startup($this->Controller)); + + $this->Controller->Auth->allow(); + $this->Controller->Auth->deny(array('add', 'camelCase')); + + $this->Controller->request['action'] = 'delete'; + $this->assertTrue($this->Controller->Auth->startup($this->Controller)); + + $this->Controller->request['action'] = 'camelCase'; + $this->assertFalse($this->Controller->Auth->startup($this->Controller)); + + $this->Controller->Auth->allow('*'); + $this->Controller->Auth->deny(); + + $this->Controller->request['action'] = 'camelCase'; + $this->assertFalse($this->Controller->Auth->startup($this->Controller)); + + $this->Controller->request['action'] = 'add'; + $this->assertFalse($this->Controller->Auth->startup($this->Controller)); + + $this->Controller->Auth->allow('camelCase'); + $this->Controller->Auth->deny(); + + $this->Controller->request['action'] = 'camelCase'; + $this->assertFalse($this->Controller->Auth->startup($this->Controller)); + + $this->Controller->request['action'] = 'login'; + $this->assertFalse($this->Controller->Auth->startup($this->Controller)); + + $this->Controller->Auth->deny(); + $this->Controller->Auth->allow(null); + + $this->Controller->request['action'] = 'camelCase'; + $this->assertTrue($this->Controller->Auth->startup($this->Controller)); + + $this->Controller->Auth->allow(); + $this->Controller->Auth->deny(null); + + $this->Controller->request['action'] = 'camelCase'; + $this->assertFalse($this->Controller->Auth->startup($this->Controller)); + } + +/** + * test that deny() converts camel case inputs to lowercase. + * + * @return void + */ + public function testDenyWithCamelCaseMethods() { + $this->Controller->Auth->initialize($this->Controller); + $this->Controller->Auth->allow(); + $this->Controller->Auth->deny('add', 'camelCase'); + + $url = '/auth_test/camelCase'; + $this->Controller->request->addParams(Router::parse($url)); + $this->Controller->request->query['url'] = Router::normalize($url); + + $this->assertFalse($this->Controller->Auth->startup($this->Controller)); + + $url = '/auth_test/CamelCase'; + $this->Controller->request->addParams(Router::parse($url)); + $this->Controller->request->query['url'] = Router::normalize($url); + $this->assertFalse($this->Controller->Auth->startup($this->Controller)); + } + +/** + * test that allow() and allowedActions work with camelCase method names. + * + * @return void + */ + public function testAllowedActionsWithCamelCaseMethods() { + $url = '/auth_test/camelCase'; + $this->Controller->request->addParams(Router::parse($url)); + $this->Controller->request->query['url'] = Router::normalize($url); + $this->Controller->Auth->initialize($this->Controller); + $this->Controller->Auth->loginAction = array('controller' => 'AuthTest', 'action' => 'login'); + $this->Controller->Auth->userModel = 'AuthUser'; + $this->Controller->Auth->allow(); + $result = $this->Controller->Auth->startup($this->Controller); + $this->assertTrue($result, 'startup() should return true, as action is allowed. %s'); + + $url = '/auth_test/camelCase'; + $this->Controller->request->addParams(Router::parse($url)); + $this->Controller->request->query['url'] = Router::normalize($url); + $this->Controller->Auth->initialize($this->Controller); + $this->Controller->Auth->loginAction = array('controller' => 'AuthTest', 'action' => 'login'); + $this->Controller->Auth->userModel = 'AuthUser'; + $this->Controller->Auth->allowedActions = array('delete', 'camelCase', 'add'); + $result = $this->Controller->Auth->startup($this->Controller); + $this->assertTrue($result, 'startup() should return true, as action is allowed. %s'); + + $this->Controller->Auth->allowedActions = array('delete', 'add'); + $result = $this->Controller->Auth->startup($this->Controller); + $this->assertFalse($result, 'startup() should return false, as action is not allowed. %s'); + + $url = '/auth_test/delete'; + $this->Controller->request->addParams(Router::parse($url)); + $this->Controller->request->query['url'] = Router::normalize($url); + $this->Controller->Auth->initialize($this->Controller); + $this->Controller->Auth->loginAction = array('controller' => 'AuthTest', 'action' => 'login'); + $this->Controller->Auth->userModel = 'AuthUser'; + + $this->Controller->Auth->allow(array('delete', 'add')); + $result = $this->Controller->Auth->startup($this->Controller); + $this->assertTrue($result, 'startup() should return true, as action is allowed. %s'); + } + + public function testAllowedActionsSetWithAllowMethod() { + $url = '/auth_test/action_name'; + $this->Controller->request->addParams(Router::parse($url)); + $this->Controller->request->query['url'] = Router::normalize($url); + $this->Controller->Auth->initialize($this->Controller); + $this->Controller->Auth->allow('action_name', 'anotherAction'); + $this->assertEquals(array('action_name', 'anotherAction'), $this->Controller->Auth->allowedActions); + } + +/** + * testLoginRedirect method + * + * @return void + */ + public function testLoginRedirect() { + $_SERVER['HTTP_REFERER'] = false; + $_ENV['HTTP_REFERER'] = false; + putenv('HTTP_REFERER='); + + $this->Auth->Session->write('Auth', array( + 'AuthUser' => array('id' => '1', 'username' => 'nate') + )); + + $this->Auth->request->addParams(Router::parse('users/login')); + $this->Auth->request->url = 'users/login'; + $this->Auth->initialize($this->Controller); + + $this->Auth->loginRedirect = array( + 'controller' => 'pages', 'action' => 'display', 'welcome' + ); + $this->Auth->startup($this->Controller); + $expected = Router::normalize($this->Auth->loginRedirect); + $this->assertEquals($expected, $this->Auth->redirect()); + + $this->Auth->Session->delete('Auth'); + + //empty referer no session + $_SERVER['HTTP_REFERER'] = false; + $_ENV['HTTP_REFERER'] = false; + putenv('HTTP_REFERER='); + $url = '/posts/view/1'; + + $this->Auth->Session->write('Auth', array( + 'AuthUser' => array('id' => '1', 'username' => 'nate')) + ); + $this->Controller->testUrl = null; + $this->Auth->request->addParams(Router::parse($url)); + array_push($this->Controller->methods, 'view', 'edit', 'index'); + + $this->Auth->initialize($this->Controller); + $this->Auth->authorize = 'controller'; + + $this->Auth->loginAction = array( + 'controller' => 'AuthTest', 'action' => 'login' + ); + $this->Auth->startup($this->Controller); + $expected = Router::normalize('/AuthTest/login'); + $this->assertEquals($expected, $this->Controller->testUrl); + + $this->Auth->Session->delete('Auth'); + $_SERVER['HTTP_REFERER'] = $_ENV['HTTP_REFERER'] = Router::url('/admin', true); + $this->Auth->Session->write('Auth', array( + 'AuthUser' => array('id' => '1', 'username' => 'nate') + )); + $this->Auth->request->params['action'] = 'login'; + $this->Auth->request->url = 'auth_test/login'; + $this->Auth->initialize($this->Controller); + $this->Auth->loginAction = 'auth_test/login'; + $this->Auth->loginRedirect = false; + $this->Auth->startup($this->Controller); + $expected = Router::normalize('/admin'); + $this->assertEquals($expected, $this->Auth->redirect()); + + // Ticket #4750 + // Named Parameters + $this->Controller->request = $this->Auth->request; + $this->Auth->Session->delete('Auth'); + $url = '/posts/index/year:2008/month:feb'; + $this->Auth->request->addParams(Router::parse($url)); + $this->Auth->request->url = $this->Auth->request->here = Router::normalize($url); + $this->Auth->initialize($this->Controller); + $this->Auth->loginAction = array('controller' => 'AuthTest', 'action' => 'login'); + $this->Auth->startup($this->Controller); + $expected = Router::normalize('posts/index/year:2008/month:feb'); + $this->assertEquals($expected, $this->Auth->Session->read('Auth.redirect')); + + // Passed Arguments + $this->Auth->Session->delete('Auth'); + $url = '/posts/view/1'; + $this->Auth->request->addParams(Router::parse($url)); + $this->Auth->request->url = $this->Auth->request->here = Router::normalize($url); + $this->Auth->initialize($this->Controller); + $this->Auth->loginAction = array('controller' => 'AuthTest', 'action' => 'login'); + $this->Auth->startup($this->Controller); + $expected = Router::normalize('posts/view/1'); + $this->assertEquals($expected, $this->Auth->Session->read('Auth.redirect')); + + // QueryString parameters + $_back = $_GET; + $_GET = array( + 'print' => 'true', + 'refer' => 'menu' + ); + $this->Auth->Session->delete('Auth'); + $url = '/posts/index/29'; + $this->Auth->request->addParams(Router::parse($url)); + $this->Auth->request->url = $this->Auth->request->here = Router::normalize($url); + $this->Auth->request->query = $_GET; + + $this->Auth->initialize($this->Controller); + $this->Auth->loginAction = array('controller' => 'AuthTest', 'action' => 'login'); + $this->Auth->startup($this->Controller); + $expected = Router::normalize('posts/index/29?print=true&refer=menu'); + $this->assertEquals($expected, $this->Auth->Session->read('Auth.redirect')); + + $_GET = $_back; + + // External Authed Action + $_SERVER['HTTP_REFERER'] = 'http://webmail.example.com/view/message'; + $this->Auth->Session->delete('Auth'); + $url = '/posts/edit/1'; + $request = new CakeRequest($url); + $request->query = array(); + $this->Auth->request = $this->Controller->request = $request; + $this->Auth->request->addParams(Router::parse($url)); + $this->Auth->request->url = $this->Auth->request->here = Router::normalize($url); + $this->Auth->initialize($this->Controller); + $this->Auth->loginAction = array('controller' => 'AuthTest', 'action' => 'login'); + $this->Auth->startup($this->Controller); + $expected = Router::normalize('/posts/edit/1'); + $this->assertEquals($expected, $this->Auth->Session->read('Auth.redirect')); + + // External Direct Login Link + $_SERVER['HTTP_REFERER'] = 'http://webmail.example.com/view/message'; + $this->Auth->Session->delete('Auth'); + $url = '/AuthTest/login'; + $this->Auth->request = $this->Controller->request = new CakeRequest($url); + $this->Auth->request->addParams(Router::parse($url)); + $this->Auth->request->url = Router::normalize($url); + $this->Auth->initialize($this->Controller); + $this->Auth->loginAction = array('controller' => 'AuthTest', 'action' => 'login'); + $this->Auth->startup($this->Controller); + $expected = Router::normalize('/'); + $this->assertEquals($expected, $this->Auth->Session->read('Auth.redirect')); + + $this->Auth->Session->delete('Auth'); + } + +/** + * Default to loginRedirect, if set, on authError. + * + * @return void + */ + public function testDefaultToLoginRedirect() { + $_SERVER['HTTP_REFERER'] = false; + $_ENV['HTTP_REFERER'] = false; + putenv('HTTP_REFERER='); + + $url = '/party/on'; + $this->Auth->request = $CakeRequest = new CakeRequest($url); + $this->Auth->request->addParams(Router::parse($url)); + $this->Auth->authorize = array('Controller'); + $this->Auth->login(array('username' => 'mariano', 'password' => 'cake')); + $this->Auth->loginRedirect = array( + 'controller' => 'something', 'action' => 'else', + ); + + $CakeResponse = new CakeResponse(); + $Controller = $this->getMock( + 'Controller', + array('on', 'redirect'), + array($CakeRequest, $CakeResponse) + ); + + $expected = Router::url($this->Auth->loginRedirect, true); + $Controller->expects($this->once()) + ->method('redirect') + ->with($this->equalTo($expected)); + $this->Auth->startup($Controller); + } + +/** + * Test that no redirects or authorization tests occur on the loginAction + * + * @return void + */ + public function testNoRedirectOnLoginAction() { + $controller = $this->getMock('Controller'); + $controller->methods = array('login'); + + $url = '/AuthTest/login'; + $this->Auth->request = $controller->request = new CakeRequest($url); + $this->Auth->request->addParams(Router::parse($url)); + $this->Auth->loginAction = array('controller' => 'AuthTest', 'action' => 'login'); + $this->Auth->authorize = array('Controller'); + + $controller->expects($this->never()) + ->method('redirect'); + + $this->Auth->startup($controller); + } + +/** + * Ensure that no redirect is performed when a 404 is reached + * And the user doesn't have a session. + * + * @return void + */ + public function testNoRedirectOn404() { + $this->Auth->Session->delete('Auth'); + $this->Auth->initialize($this->Controller); + $this->Auth->request->addParams(Router::parse('auth_test/something_totally_wrong')); + $result = $this->Auth->startup($this->Controller); + $this->assertTrue($result, 'Auth redirected a missing action %s'); + } + +/** + * testAdminRoute method + * + * @return void + */ + public function testAdminRoute() { + $pref = Configure::read('Routing.prefixes'); + Configure::write('Routing.prefixes', array('admin')); + Router::reload(); + require CAKE . 'Config' . DS . 'routes.php'; + + $url = '/admin/auth_test/add'; + $this->Auth->request->addParams(Router::parse($url)); + $this->Auth->request->query['url'] = ltrim($url, '/'); + $this->Auth->request->base = ''; + + Router::setRequestInfo($this->Auth->request); + $this->Auth->initialize($this->Controller); + + $this->Auth->loginAction = array( + 'admin' => true, 'controller' => 'auth_test', 'action' => 'login' + ); + + $this->Auth->startup($this->Controller); + $this->assertEquals('/admin/auth_test/login', $this->Controller->testUrl); + + Configure::write('Routing.prefixes', $pref); + } + +/** + * testAjaxLogin method + * + * @return void + */ + public function testAjaxLogin() { + App::build(array( + 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS) + )); + $_SERVER['HTTP_X_REQUESTED_WITH'] = "XMLHttpRequest"; + + App::uses('Dispatcher', 'Routing'); + + ob_start(); + $Dispatcher = new Dispatcher(); + $Dispatcher->dispatch(new CakeRequest('/ajax_auth/add'), new CakeResponse(), array('return' => 1)); + $result = ob_get_clean(); + + $this->assertEquals("Ajax!\nthis is the test element", str_replace("\r\n", "\n", $result)); + unset($_SERVER['HTTP_X_REQUESTED_WITH']); + } + +/** + * testLoginActionRedirect method + * + * @return void + */ + public function testLoginActionRedirect() { + $admin = Configure::read('Routing.prefixes'); + Configure::write('Routing.prefixes', array('admin')); + Router::reload(); + require CAKE . 'Config' . DS . 'routes.php'; + + $url = '/admin/auth_test/login'; + $this->Auth->request->addParams(Router::parse($url)); + $this->Auth->request->url = ltrim($url, '/'); + Router::setRequestInfo(array( + array( + 'pass' => array(), 'action' => 'admin_login', 'plugin' => null, 'controller' => 'auth_test', + 'admin' => true, + ), + array( + 'base' => null, 'here' => $url, + 'webroot' => '/', 'passedArgs' => array(), + ) + )); + + $this->Auth->initialize($this->Controller); + $this->Auth->loginAction = array('admin' => true, 'controller' => 'auth_test', 'action' => 'login'); + $this->Auth->startup($this->Controller); + + $this->assertNull($this->Controller->testUrl); + + Configure::write('Routing.prefixes', $admin); + } + +/** + * Stateless auth methods like Basic should populate data that can be + * accessed by $this->user(). + * + * @return void + */ + public function testStatelessAuthWorksWithUser() { + $_SERVER['PHP_AUTH_USER'] = 'mariano'; + $_SERVER['PHP_AUTH_PW'] = 'cake'; + $url = '/auth_test/add'; + $this->Auth->request->addParams(Router::parse($url)); + + $this->Auth->authenticate = array( + 'Basic' => array('userModel' => 'AuthUser') + ); + $this->Auth->startup($this->Controller); + + $result = $this->Auth->user(); + $this->assertEquals('mariano', $result['username']); + + $result = $this->Auth->user('username'); + $this->assertEquals('mariano', $result); + } + +/** + * Tests that shutdown destroys the redirect session var + * + * @return void + */ + public function testShutDown() { + $this->Auth->Session->write('Auth.User', 'not empty'); + $this->Auth->Session->write('Auth.redirect', 'foo'); + $this->Controller->Auth->loggedIn(true); + + $this->Controller->Auth->shutdown($this->Controller); + $this->assertNull($this->Auth->Session->read('Auth.redirect')); + } + +/** + * test $settings in Controller::$components + * + * @return void + */ + public function testComponentSettings() { + $request = new CakeRequest(null, false); + $this->Controller = new AuthTestController($request, $this->getMock('CakeResponse')); + + $this->Controller->components = array( + 'Auth' => array( + 'loginAction' => array('controller' => 'people', 'action' => 'login'), + 'logoutRedirect' => array('controller' => 'people', 'action' => 'login'), + ), + 'Session' + ); + $this->Controller->Components->init($this->Controller); + $this->Controller->Components->trigger('initialize', array(&$this->Controller)); + Router::reload(); + + $expected = array( + 'loginAction' => array('controller' => 'people', 'action' => 'login'), + 'logoutRedirect' => array('controller' => 'people', 'action' => 'login'), + ); + $this->assertEquals($expected['loginAction'], $this->Controller->Auth->loginAction); + $this->assertEquals($expected['logoutRedirect'], $this->Controller->Auth->logoutRedirect); + } + +/** + * test that logout deletes the session variables. and returns the correct url + * + * @return void + */ + public function testLogout() { + $this->Auth->Session->write('Auth.User.id', '1'); + $this->Auth->Session->write('Auth.redirect', '/users/login'); + $this->Auth->logoutRedirect = '/'; + $result = $this->Auth->logout(); + + $this->assertEquals('/', $result); + $this->assertNull($this->Auth->Session->read('Auth.AuthUser')); + $this->assertNull($this->Auth->Session->read('Auth.redirect')); + } + +/** + * Logout should trigger a logout method on authentication objects. + * + * @return void + */ + public function testLogoutTrigger() { + $this->getMock('BaseAuthenticate', array('authenticate', 'logout'), array(), 'LogoutTriggerMockAuthenticate', false); + + $this->Auth->authenticate = array('LogoutTriggerMock'); + $mock = $this->Auth->constructAuthenticate(); + $mock[0]->expects($this->once()) + ->method('logout'); + + $this->Auth->logout(); + } + +/** + * test mapActions loading and delegating to authorize objects. + * + * @return void + */ + public function testMapActionsDelegation() { + $this->getMock('BaseAuthorize', array('authorize'), array(), 'MapActionMockAuthorize', false); + $this->Auth->authorize = array('MapActionMock'); + $mock = $this->Auth->constructAuthorize(); + $mock[0]->expects($this->once()) + ->method('mapActions') + ->with(array('create' => array('my_action'))); + + $this->Auth->mapActions(array('create' => array('my_action'))); + } + +/** + * test logging in with a request. + * + * @return void + */ + public function testLoginWithRequestData() { + $this->getMock('FormAuthenticate', array(), array(), 'RequestLoginMockAuthenticate', false); + $request = new CakeRequest('users/login', false); + $user = array('username' => 'mark', 'role' => 'admin'); + + $this->Auth->request = $request; + $this->Auth->authenticate = array('RequestLoginMock'); + $mock = $this->Auth->constructAuthenticate(); + $mock[0]->expects($this->once()) + ->method('authenticate') + ->with($request) + ->will($this->returnValue($user)); + + $this->assertTrue($this->Auth->login()); + $this->assertEquals($user['username'], $this->Auth->user('username')); + } + +/** + * test login() with user data + * + * @return void + */ + public function testLoginWithUserData() { + $this->assertFalse($this->Auth->loggedIn()); + + $user = array( + 'username' => 'mariano', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', + 'updated' => '2007-03-17 01:18:31' + ); + $this->assertTrue($this->Auth->login($user)); + $this->assertTrue($this->Auth->loggedIn()); + $this->assertEquals($user['username'], $this->Auth->user('username')); + } + +/** + * test flash settings. + * + * @return void + */ + public function testFlashSettings() { + $this->Auth->Session = $this->getMock('SessionComponent', array(), array(), '', false); + $this->Auth->Session->expects($this->once()) + ->method('setFlash') + ->with('Auth failure', 'custom', array(1), 'auth-key'); + + $this->Auth->flash = array( + 'element' => 'custom', + 'params' => array(1), + 'key' => 'auth-key' + ); + $this->Auth->flash('Auth failure'); + } + +/** + * test the various states of Auth::redirect() + * + * @return void + */ + public function testRedirectSet() { + $value = array('controller' => 'users', 'action' => 'home'); + $result = $this->Auth->redirect($value); + $this->assertEquals('/users/home', $result); + $this->assertEquals($value, $this->Auth->Session->read('Auth.redirect')); + } + +/** + * test redirect using Auth.redirect from the session. + * + * @return void + */ + public function testRedirectSessionRead() { + $this->Auth->loginAction = array('controller' => 'users', 'action' => 'login'); + $this->Auth->Session->write('Auth.redirect', '/users/home'); + + $result = $this->Auth->redirect(); + $this->assertEquals('/users/home', $result); + $this->assertFalse($this->Auth->Session->check('Auth.redirect')); + } + +/** + * test that redirect does not return loginAction if that is what's stored in Auth.redirect. + * instead loginRedirect should be used. + * + * @return void + */ + public function testRedirectSessionReadEqualToLoginAction() { + $this->Auth->loginAction = array('controller' => 'users', 'action' => 'login'); + $this->Auth->loginRedirect = array('controller' => 'users', 'action' => 'home'); + $this->Auth->Session->write('Auth.redirect', array('controller' => 'users', 'action' => 'login')); + + $result = $this->Auth->redirect(); + $this->assertEquals('/users/home', $result); + $this->assertFalse($this->Auth->Session->check('Auth.redirect')); + } + +/** + * test password hashing + * + * @return void + */ + public function testPassword() { + $result = $this->Auth->password('password'); + $expected = Security::hash('password', null, true); + $this->assertEquals($expected, $result); + } + +/** + * testUser method + * + * @return void + */ + public function testUser() { + $data = array( + 'User' => array( + 'id' => '2', + 'username' => 'mark', + 'group_id' => 1, + 'Group' => array( + 'id' => '1', + 'name' => 'Members' + ), + )); + $this->Auth->Session->write('Auth', $data); + + $result = $this->Auth->user(); + $this->assertEquals($data['User'], $result); + + $result = $this->Auth->user('username'); + $this->assertEquals($data['User']['username'], $result); + + $result = $this->Auth->user('Group.name'); + $this->assertEquals($data['User']['Group']['name'], $result); + + $result = $this->Auth->user('invalid'); + $this->assertEquals(null, $result); + + $result = $this->Auth->user('Company.invalid'); + $this->assertEquals(null, $result); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/CookieComponentTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/CookieComponentTest.php new file mode 100644 index 0000000..6ed65a6 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/CookieComponentTest.php @@ -0,0 +1,602 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Controller.Component + * @since CakePHP(tm) v 1.2.0.5435 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ + +App::uses('Component', 'Controller'); +App::uses('Controller', 'Controller'); +App::uses('CookieComponent', 'Controller/Component'); + + +/** + * CookieComponentTestController class + * + * @package Cake.Test.Case.Controller.Component + */ +class CookieComponentTestController extends Controller { + +/** + * components property + * + * @var array + */ + public $components = array('Cookie'); + +/** + * beforeFilter method + * + * @return void + */ + public function beforeFilter() { + $this->Cookie->name = 'CakeTestCookie'; + $this->Cookie->time = 10; + $this->Cookie->path = '/'; + $this->Cookie->domain = ''; + $this->Cookie->secure = false; + $this->Cookie->key = 'somerandomhaskey'; + } + +} + +/** + * CookieComponentTest class + * + * @package Cake.Test.Case.Controller.Component + */ +class CookieComponentTest extends CakeTestCase { + +/** + * Controller property + * + * @var CookieComponentTestController + */ + public $Controller; + +/** + * start + * + * @return void + */ + public function setUp() { + $_COOKIE = array(); + $this->Controller = new CookieComponentTestController(new CakeRequest(), new CakeResponse()); + $this->Controller->constructClasses(); + $this->Cookie = $this->Controller->Cookie; + + $this->Cookie->name = 'CakeTestCookie'; + $this->Cookie->time = 10; + $this->Cookie->path = '/'; + $this->Cookie->domain = ''; + $this->Cookie->secure = false; + $this->Cookie->key = 'somerandomhaskey'; + + $this->Cookie->startup($this->Controller); + } + +/** + * end + * + * @return void + */ + public function tearDown() { + $this->Cookie->destroy(); + } + +/** + * sets up some default cookie data. + * + * @return void + */ + protected function _setCookieData() { + $this->Cookie->write(array('Encrytped_array' => array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' => 'CakePHP Rocks!'))); + $this->Cookie->write(array('Encrytped_multi_cookies.name' => 'CakePHP')); + $this->Cookie->write(array('Encrytped_multi_cookies.version' => '1.2.0.x')); + $this->Cookie->write(array('Encrytped_multi_cookies.tag' => 'CakePHP Rocks!')); + + $this->Cookie->write(array('Plain_array' => array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' => 'CakePHP Rocks!')), null, false); + $this->Cookie->write(array('Plain_multi_cookies.name' => 'CakePHP'), null, false); + $this->Cookie->write(array('Plain_multi_cookies.version' => '1.2.0.x'), null, false); + $this->Cookie->write(array('Plain_multi_cookies.tag' => 'CakePHP Rocks!'), null, false); + } + +/** + * test that initialize sets settings from components array + * + * @return void + */ + public function testSettings() { + $settings = array( + 'time' => '5 days', + 'path' => '/' + ); + $Cookie = new CookieComponent(new ComponentCollection(), $settings); + $this->assertEquals($Cookie->time, $settings['time']); + $this->assertEquals($Cookie->path, $settings['path']); + } + +/** + * testCookieName + * + * @return void + */ + public function testCookieName() { + $this->assertEquals('CakeTestCookie', $this->Cookie->name); + } + +/** + * testReadEncryptedCookieData + * + * @return void + */ + public function testReadEncryptedCookieData() { + $this->_setCookieData(); + $data = $this->Cookie->read('Encrytped_array'); + $expected = array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' => 'CakePHP Rocks!'); + $this->assertEquals($expected, $data); + + $data = $this->Cookie->read('Encrytped_multi_cookies'); + $expected = array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' => 'CakePHP Rocks!'); + $this->assertEquals($expected, $data); + } + +/** + * testReadPlainCookieData + * + * @return void + */ + public function testReadPlainCookieData() { + $this->_setCookieData(); + $data = $this->Cookie->read('Plain_array'); + $expected = array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' => 'CakePHP Rocks!'); + $this->assertEquals($expected, $data); + + $data = $this->Cookie->read('Plain_multi_cookies'); + $expected = array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' => 'CakePHP Rocks!'); + $this->assertEquals($expected, $data); + } + +/** + * test read() after switching the cookie name. + * + * @return void + */ + public function testReadWithNameSwitch() { + $_COOKIE = array( + 'CakeTestCookie' => array( + 'key' => 'value' + ), + 'OtherTestCookie' => array( + 'key' => 'other value' + ) + ); + $this->assertEquals('value', $this->Cookie->read('key')); + + $this->Cookie->name = 'OtherTestCookie'; + $this->assertEquals('other value', $this->Cookie->read('key')); + } + +/** + * test a simple write() + * + * @return void + */ + public function testWriteSimple() { + $this->Cookie->write('Testing', 'value'); + $result = $this->Cookie->read('Testing'); + + $this->assertEquals('value', $result); + } + +/** + * test write with httpOnly cookies + * + * @return void + */ + public function testWriteHttpOnly() { + $this->Cookie->httpOnly = true; + $this->Cookie->secure = false; + $this->Cookie->write('Testing', 'value', false); + $expected = array( + 'name' => $this->Cookie->name . '[Testing]', + 'value' => 'value', + 'expire' => time() + 10, + 'path' => '/', + 'domain' => '', + 'secure' => false, + 'httpOnly' => true); + $result = $this->Controller->response->cookie($this->Cookie->name . '[Testing]'); + $this->assertEquals($expected, $result); + } + +/** + * test delete with httpOnly + * + * @return void + */ + public function testDeleteHttpOnly() { + $this->Cookie->httpOnly = true; + $this->Cookie->secure = false; + $this->Cookie->delete('Testing', false); + $expected = array( + 'name' => $this->Cookie->name . '[Testing]', + 'value' => '', + 'expire' => time() - 42000, + 'path' => '/', + 'domain' => '', + 'secure' => false, + 'httpOnly' => true); + $result = $this->Controller->response->cookie($this->Cookie->name . '[Testing]'); + $this->assertEquals($expected, $result); + } + +/** + * testWritePlainCookieArray + * + * @return void + */ + public function testWritePlainCookieArray() { + $this->Cookie->write(array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' => 'CakePHP Rocks!'), null, false); + + $this->assertEquals('CakePHP', $this->Cookie->read('name')); + $this->assertEquals('1.2.0.x', $this->Cookie->read('version')); + $this->assertEquals('CakePHP Rocks!', $this->Cookie->read('tag')); + + $this->Cookie->delete('name'); + $this->Cookie->delete('version'); + $this->Cookie->delete('tag'); + } + +/** + * test writing values that are not scalars + * + * @return void + */ + public function testWriteArrayValues() { + $this->Cookie->secure = false; + $this->Cookie->write('Testing', array(1, 2, 3), false); + $expected = array( + 'name' => $this->Cookie->name . '[Testing]', + 'value' => '[1,2,3]', + 'expire' => time() + 10, + 'path' => '/', + 'domain' => '', + 'secure' => false, + 'httpOnly' => false); + $result = $this->Controller->response->cookie($this->Cookie->name . '[Testing]'); + $this->assertEquals($expected, $result); + } + +/** + * testReadingCookieValue + * + * @return void + */ + public function testReadingCookieValue() { + $this->_setCookieData(); + $data = $this->Cookie->read(); + $expected = array( + 'Encrytped_array' => array( + 'name' => 'CakePHP', + 'version' => '1.2.0.x', + 'tag' => 'CakePHP Rocks!'), + 'Encrytped_multi_cookies' => array( + 'name' => 'CakePHP', + 'version' => '1.2.0.x', + 'tag' => 'CakePHP Rocks!'), + 'Plain_array' => array( + 'name' => 'CakePHP', + 'version' => '1.2.0.x', + 'tag' => 'CakePHP Rocks!'), + 'Plain_multi_cookies' => array( + 'name' => 'CakePHP', + 'version' => '1.2.0.x', + 'tag' => 'CakePHP Rocks!')); + $this->assertEquals($expected, $data); + } + +/** + * testDeleteCookieValue + * + * @return void + */ + public function testDeleteCookieValue() { + $this->_setCookieData(); + $this->Cookie->delete('Encrytped_multi_cookies.name'); + $data = $this->Cookie->read('Encrytped_multi_cookies'); + $expected = array('version' => '1.2.0.x', 'tag' => 'CakePHP Rocks!'); + $this->assertEquals($expected, $data); + + $this->Cookie->delete('Encrytped_array'); + $data = $this->Cookie->read('Encrytped_array'); + $this->assertNull($data); + + $this->Cookie->delete('Plain_multi_cookies.name'); + $data = $this->Cookie->read('Plain_multi_cookies'); + $expected = array('version' => '1.2.0.x', 'tag' => 'CakePHP Rocks!'); + $this->assertEquals($expected, $data); + + $this->Cookie->delete('Plain_array'); + $data = $this->Cookie->read('Plain_array'); + $this->assertNull($data); + } + +/** + * testReadingCookieArray + * + * @return void + */ + public function testReadingCookieArray() { + $this->_setCookieData(); + + $data = $this->Cookie->read('Encrytped_array.name'); + $expected = 'CakePHP'; + $this->assertEquals($expected, $data); + + $data = $this->Cookie->read('Encrytped_array.version'); + $expected = '1.2.0.x'; + $this->assertEquals($expected, $data); + + $data = $this->Cookie->read('Encrytped_array.tag'); + $expected = 'CakePHP Rocks!'; + $this->assertEquals($expected, $data); + + $data = $this->Cookie->read('Encrytped_multi_cookies.name'); + $expected = 'CakePHP'; + $this->assertEquals($expected, $data); + + $data = $this->Cookie->read('Encrytped_multi_cookies.version'); + $expected = '1.2.0.x'; + $this->assertEquals($expected, $data); + + $data = $this->Cookie->read('Encrytped_multi_cookies.tag'); + $expected = 'CakePHP Rocks!'; + $this->assertEquals($expected, $data); + + $data = $this->Cookie->read('Plain_array.name'); + $expected = 'CakePHP'; + $this->assertEquals($expected, $data); + + $data = $this->Cookie->read('Plain_array.version'); + $expected = '1.2.0.x'; + $this->assertEquals($expected, $data); + + $data = $this->Cookie->read('Plain_array.tag'); + $expected = 'CakePHP Rocks!'; + $this->assertEquals($expected, $data); + + $data = $this->Cookie->read('Plain_multi_cookies.name'); + $expected = 'CakePHP'; + $this->assertEquals($expected, $data); + + $data = $this->Cookie->read('Plain_multi_cookies.version'); + $expected = '1.2.0.x'; + $this->assertEquals($expected, $data); + + $data = $this->Cookie->read('Plain_multi_cookies.tag'); + $expected = 'CakePHP Rocks!'; + $this->assertEquals($expected, $data); + } + +/** + * testReadingCookieDataOnStartup + * + * @return void + */ + public function testReadingCookieDataOnStartup() { + $data = $this->Cookie->read('Encrytped_array'); + $this->assertNull($data); + + $data = $this->Cookie->read('Encrytped_multi_cookies'); + $this->assertNull($data); + + $data = $this->Cookie->read('Plain_array'); + $this->assertNull($data); + + $data = $this->Cookie->read('Plain_multi_cookies'); + $this->assertNull($data); + + $_COOKIE['CakeTestCookie'] = array( + 'Encrytped_array' => $this->__encrypt(array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' => 'CakePHP Rocks!')), + 'Encrytped_multi_cookies' => array( + 'name' => $this->__encrypt('CakePHP'), + 'version' => $this->__encrypt('1.2.0.x'), + 'tag' => $this->__encrypt('CakePHP Rocks!')), + 'Plain_array' => '{"name":"CakePHP","version":"1.2.0.x","tag":"CakePHP Rocks!"}', + 'Plain_multi_cookies' => array( + 'name' => 'CakePHP', + 'version' => '1.2.0.x', + 'tag' => 'CakePHP Rocks!')); + + $this->Cookie->startup(new CookieComponentTestController()); + + $data = $this->Cookie->read('Encrytped_array'); + $expected = array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' => 'CakePHP Rocks!'); + $this->assertEquals($expected, $data); + + $data = $this->Cookie->read('Encrytped_multi_cookies'); + $expected = array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' => 'CakePHP Rocks!'); + $this->assertEquals($expected, $data); + + $data = $this->Cookie->read('Plain_array'); + $expected = array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' => 'CakePHP Rocks!'); + $this->assertEquals($expected, $data); + + $data = $this->Cookie->read('Plain_multi_cookies'); + $expected = array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' => 'CakePHP Rocks!'); + $this->assertEquals($expected, $data); + $this->Cookie->destroy(); + unset($_COOKIE['CakeTestCookie']); + } + +/** + * testReadingCookieDataWithoutStartup + * + * @return void + */ + public function testReadingCookieDataWithoutStartup() { + $data = $this->Cookie->read('Encrytped_array'); + $expected = null; + $this->assertEquals($expected, $data); + + $data = $this->Cookie->read('Encrytped_multi_cookies'); + $expected = null; + $this->assertEquals($expected, $data); + + $data = $this->Cookie->read('Plain_array'); + $expected = null; + $this->assertEquals($expected, $data); + + $data = $this->Cookie->read('Plain_multi_cookies'); + $expected = null; + $this->assertEquals($expected, $data); + + $_COOKIE['CakeTestCookie'] = array( + 'Encrytped_array' => $this->__encrypt(array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' => 'CakePHP Rocks!')), + 'Encrytped_multi_cookies' => array( + 'name' => $this->__encrypt('CakePHP'), + 'version' => $this->__encrypt('1.2.0.x'), + 'tag' => $this->__encrypt('CakePHP Rocks!')), + 'Plain_array' => '{"name":"CakePHP","version":"1.2.0.x","tag":"CakePHP Rocks!"}', + 'Plain_multi_cookies' => array( + 'name' => 'CakePHP', + 'version' => '1.2.0.x', + 'tag' => 'CakePHP Rocks!')); + + $data = $this->Cookie->read('Encrytped_array'); + $expected = array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' => 'CakePHP Rocks!'); + $this->assertEquals($expected, $data); + + $data = $this->Cookie->read('Encrytped_multi_cookies'); + $expected = array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' => 'CakePHP Rocks!'); + $this->assertEquals($expected, $data); + + $data = $this->Cookie->read('Plain_array'); + $expected = array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' => 'CakePHP Rocks!'); + $this->assertEquals($expected, $data); + + $data = $this->Cookie->read('Plain_multi_cookies'); + $expected = array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' => 'CakePHP Rocks!'); + $this->assertEquals($expected, $data); + $this->Cookie->destroy(); + unset($_COOKIE['CakeTestCookie']); + } + +/** + * Test Reading legacy cookie values. + * + * @return void + */ + public function testReadLegacyCookieValue() { + $_COOKIE['CakeTestCookie'] = array( + 'Legacy' => array('value' => $this->_oldImplode(array(1, 2, 3))) + ); + $result = $this->Cookie->read('Legacy.value'); + $expected = array(1, 2, 3); + $this->assertEquals($expected, $result); + } + +/** + * Test reading empty values. + */ + public function testReadEmpty() { + $_COOKIE['CakeTestCookie'] = array( + 'JSON' => '{"name":"value"}', + 'Empty' => '', + 'String' => '{"somewhat:"broken"}' + ); + $this->assertEquals(array('name' => 'value'), $this->Cookie->read('JSON')); + $this->assertEquals('value', $this->Cookie->read('JSON.name')); + $this->assertEquals('', $this->Cookie->read('Empty')); + $this->assertEquals('{"somewhat:"broken"}', $this->Cookie->read('String')); + } + +/** + * test that no error is issued for non array data. + * + * @return void + */ + public function testNoErrorOnNonArrayData() { + $this->Cookie->destroy(); + $_COOKIE['CakeTestCookie'] = 'kaboom'; + + $this->assertNull($this->Cookie->read('value')); + } + +/** + * test that deleting a top level keys kills the child elements too. + * + * @return void + */ + public function testDeleteRemovesChildren() { + $_COOKIE['CakeTestCookie'] = array( + 'User' => array('email' => 'example@example.com', 'name' => 'mark'), + 'other' => 'value' + ); + $this->assertEquals('mark', $this->Cookie->read('User.name')); + + $this->Cookie->delete('User'); + $this->assertNull($this->Cookie->read('User.email')); + $this->Cookie->destroy(); + } + +/** + * Test deleting recursively with keys that don't exist. + * + * @return void + */ + public function testDeleteChildrenNotExist() { + $this->assertNull($this->Cookie->delete('NotFound')); + $this->assertNull($this->Cookie->delete('Not.Found')); + } + +/** + * Helper method for generating old style encoded cookie values. + * + * @return string. + */ + protected function _oldImplode(array $array) { + $string = ''; + foreach ($array as $key => $value) { + $string .= ',' . $key . '|' . $value; + } + return substr($string, 1); + } + +/** + * Implode method to keep keys are multidimensional arrays + * + * @param array $array Map of key and values + * @return string String in the form key1|value1,key2|value2 + */ + protected function _implode(array $array) { + return json_encode($array); + } + +/** + * encrypt method + * + * @param array|string $value + * @return string + */ + protected function __encrypt($value) { + if (is_array($value)) { + $value = $this->_implode($value); + } + return "Q2FrZQ==." . base64_encode(Security::cipher($value, $this->Cookie->key)); + } + +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/EmailComponentTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/EmailComponentTest.php new file mode 100644 index 0000000..4e81833 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/EmailComponentTest.php @@ -0,0 +1,889 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Controller.Component + * @since CakePHP(tm) v 1.2.0.5347 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ +App::uses('Controller', 'Controller'); +App::uses('EmailComponent', 'Controller/Component'); +App::uses('AbstractTransport', 'Network/Email'); + +/** + * EmailTestComponent class + * + * @package Cake.Test.Case.Controller.Component + */ +class EmailTestComponent extends EmailComponent { + +/** + * Convenience method for testing. + * + * @return string + */ + public function strip($content, $message = false) { + return parent::_strip($content, $message); + } + +} + +/** + * DebugCompTransport class + * + * @package Cake.Test.Case.Controller.Component + */ +class DebugCompTransport extends AbstractTransport { + +/** + * Last email + * + * @var string + */ + public static $lastEmail = null; + +/** + * Send mail + * + * @params object $email CakeEmail + * @return boolean + */ + public function send(CakeEmail $email) { + $email->addHeaders(array('Date' => EmailComponentTest::$sentDate)); + $headers = $email->getHeaders(array_fill_keys(array('from', 'replyTo', 'readReceipt', 'returnPath', 'to', 'cc', 'bcc', 'subject'), true)); + $to = $headers['To']; + $subject = $headers['Subject']; + unset($headers['To'], $headers['Subject']); + + $message = implode("\n", $email->message()); + + $last = '
';
+		$last .= sprintf("%s %s\n", 'To:', $to);
+		$last .= sprintf("%s %s\n", 'From:', $headers['From']);
+		$last .= sprintf("%s %s\n", 'Subject:', $subject);
+		$last .= sprintf("%s\n\n%s", 'Header:', $this->_headersToString($headers, "\n"));
+		$last .= sprintf("%s\n\n%s", 'Message:', $message);
+		$last .= '
'; + + self::$lastEmail = $last; + + return true; + } + +} + +/** + * EmailTestController class + * + * @package Cake.Test.Case.Controller.Component + */ +class EmailTestController extends Controller { + +/** + * name property + * + * @var string 'EmailTest' + */ + public $name = 'EmailTest'; + +/** + * uses property + * + * @var mixed null + */ + public $uses = null; + +/** + * components property + * + * @var array + */ + public $components = array('Session', 'EmailTest'); + +} + +/** + * EmailTest class + * + * @package Cake.Test.Case.Controller.Component + */ +class EmailComponentTest extends CakeTestCase { + +/** + * Controller property + * + * @var EmailTestController + */ + public $Controller; + +/** + * name property + * + * @var string 'Email' + */ + public $name = 'Email'; + +/** + * sentDate + * + * @var string + */ + public static $sentDate = null; + +/** + * setUp method + * + * @return void + */ + public function setUp() { + parent::setUp(); + + Configure::write('App.encoding', 'UTF-8'); + + $this->Controller = new EmailTestController(); + $this->Controller->Components->init($this->Controller); + $this->Controller->EmailTest->initialize($this->Controller, array()); + + self::$sentDate = date(DATE_RFC2822); + + App::build(array( + 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS) + )); + } + +/** + * testSendFormats method + * + * @return void + */ + public function testSendFormats() { + $this->Controller->EmailTest->to = 'postmaster@example.com'; + $this->Controller->EmailTest->from = 'noreply@example.com'; + $this->Controller->EmailTest->subject = 'Cake SMTP test'; + $this->Controller->EmailTest->replyTo = 'noreply@example.com'; + $this->Controller->EmailTest->template = null; + $this->Controller->EmailTest->delivery = 'DebugComp'; + $this->Controller->EmailTest->messageId = false; + + $date = self::$sentDate; + $message = <<To: postmaster@example.com +From: noreply@example.com +Subject: Cake SMTP test +Header: + +From: noreply@example.com +Reply-To: noreply@example.com +X-Mailer: CakePHP Email Component +Date: $date +MIME-Version: 1.0 +Content-Type: {CONTENTTYPE} +Content-Transfer-Encoding: 8bitMessage: + +This is the body of the message + + +MSGBLOC; + + $this->Controller->EmailTest->sendAs = 'text'; + $expect = str_replace('{CONTENTTYPE}', 'text/plain; charset=UTF-8', $message); + $this->assertTrue($this->Controller->EmailTest->send('This is the body of the message')); + $this->assertTextEquals(DebugCompTransport::$lastEmail, $expect); + + $this->Controller->EmailTest->sendAs = 'html'; + $expect = str_replace('{CONTENTTYPE}', 'text/html; charset=UTF-8', $message); + $this->assertTrue($this->Controller->EmailTest->send('This is the body of the message')); + $this->assertTextEquals(DebugCompTransport::$lastEmail, $expect); + } + +/** + * testTemplates method + * + * @return void + */ + public function testTemplates() { + ClassRegistry::flush(); + + $this->Controller->EmailTest->to = 'postmaster@example.com'; + $this->Controller->EmailTest->from = 'noreply@example.com'; + $this->Controller->EmailTest->subject = 'Cake SMTP test'; + $this->Controller->EmailTest->replyTo = 'noreply@example.com'; + + $this->Controller->EmailTest->delivery = 'DebugComp'; + $this->Controller->EmailTest->messageId = false; + + $date = self::$sentDate; + $header = <<Controller->EmailTest->layout = 'default'; + $this->Controller->EmailTest->template = 'default'; + $this->Controller->set('title_for_layout', 'Email Test'); + + $text = << + + + + Email Test + + + +

This is the body of the message

+

This email was sent using the CakePHP Framework

+ + +HTMLBLOC; + + $this->Controller->EmailTest->sendAs = 'text'; + $expect = '
' . str_replace('{CONTENTTYPE}', 'text/plain; charset=UTF-8', $header) . $text . "\n" . '
'; + $this->assertTrue($this->Controller->EmailTest->send('This is the body of the message')); + $this->assertTextEquals(DebugCompTransport::$lastEmail, $expect); + + $this->Controller->EmailTest->sendAs = 'html'; + $expect = '
' . str_replace('{CONTENTTYPE}', 'text/html; charset=UTF-8', $header) . $html . "\n" . '
'; + $this->assertTrue($this->Controller->EmailTest->send('This is the body of the message')); + $this->assertTextEquals(DebugCompTransport::$lastEmail, $expect); + + $this->Controller->EmailTest->sendAs = 'both'; + $expect = str_replace('{CONTENTTYPE}', 'multipart/mixed; boundary="{boundary}"', $header); + $expect .= "--{boundary}\n" . + 'Content-Type: multipart/alternative; boundary="alt-{boundary}"' . "\n\n" . + '--alt-{boundary}' . "\n" . + 'Content-Type: text/plain; charset=UTF-8' . "\n" . + 'Content-Transfer-Encoding: 8bit' . "\n\n" . + $text . + "\n\n" . + '--alt-{boundary}' . "\n" . + 'Content-Type: text/html; charset=UTF-8' . "\n" . + 'Content-Transfer-Encoding: 8bit' . "\n\n" . + $html . + "\n\n" . + '--alt-{boundary}--' . "\n\n\n" . + '--{boundary}--' . "\n"; + + $expect = '
' . $expect . '
'; + + $this->assertTrue($this->Controller->EmailTest->send('This is the body of the message')); + $this->assertTextEquals( + $expect, + preg_replace('/[a-z0-9]{32}/i', '{boundary}', DebugCompTransport::$lastEmail) + ); + + $html = << + + + + Email Test + + + +

This is the body of the message

+

This email was sent using the CakePHP Framework

+ + + +HTMLBLOC; + + $this->Controller->EmailTest->sendAs = 'html'; + $expect = '
' . str_replace('{CONTENTTYPE}', 'text/html; charset=UTF-8', $header) . $html . '
'; + $this->assertTrue($this->Controller->EmailTest->send('This is the body of the message', 'default', 'thin')); + $this->assertTextEquals(DebugCompTransport::$lastEmail, $expect); + } + +/** + * test that elements used in email templates get helpers. + * + * @return void + */ + public function testTemplateNestedElements() { + $this->Controller->EmailTest->to = 'postmaster@example.com'; + $this->Controller->EmailTest->from = 'noreply@example.com'; + $this->Controller->EmailTest->subject = 'Cake SMTP test'; + $this->Controller->EmailTest->replyTo = 'noreply@example.com'; + + $this->Controller->EmailTest->delivery = 'DebugComp'; + $this->Controller->EmailTest->messageId = false; + $this->Controller->EmailTest->layout = 'default'; + $this->Controller->EmailTest->template = 'nested_element'; + $this->Controller->EmailTest->sendAs = 'html'; + $this->Controller->helpers = array('Html'); + + $this->Controller->EmailTest->send(); + $result = DebugCompTransport::$lastEmail; + $this->assertRegExp('/Test/', $result); + $this->assertRegExp('/http\:\/\/example\.com/', $result); + } + +/** + * testSendDebug method + * + * @return void + */ + public function testSendDebug() { + $this->Controller->EmailTest->to = 'postmaster@example.com'; + $this->Controller->EmailTest->from = 'noreply@example.com'; + $this->Controller->EmailTest->cc = 'cc@example.com'; + $this->Controller->EmailTest->bcc = 'bcc@example.com'; + $this->Controller->EmailTest->subject = 'Cake Debug Test'; + $this->Controller->EmailTest->replyTo = 'noreply@example.com'; + $this->Controller->EmailTest->template = null; + + $this->Controller->EmailTest->delivery = 'DebugComp'; + $this->assertTrue($this->Controller->EmailTest->send('This is the body of the message')); + $result = DebugCompTransport::$lastEmail; + + $this->assertRegExp('/To: postmaster@example.com\n/', $result); + $this->assertRegExp('/Subject: Cake Debug Test\n/', $result); + $this->assertRegExp('/Reply-To: noreply@example.com\n/', $result); + $this->assertRegExp('/From: noreply@example.com\n/', $result); + $this->assertRegExp('/Cc: cc@example.com\n/', $result); + $this->assertRegExp('/Bcc: bcc@example.com\n/', $result); + $this->assertRegExp('/Date: ' . preg_quote(self::$sentDate) . '\n/', $result); + $this->assertRegExp('/X-Mailer: CakePHP Email Component\n/', $result); + $this->assertRegExp('/Content-Type: text\/plain; charset=UTF-8\n/', $result); + $this->assertRegExp('/Content-Transfer-Encoding: 8bitMessage:\n/', $result); + $this->assertRegExp('/This is the body of the message/', $result); + } + +/** + * test send with delivery = debug and not using sessions. + * + * @return void + */ + public function testSendDebugWithNoSessions() { + $session = $this->Controller->Session; + unset($this->Controller->Session); + $this->Controller->EmailTest->to = 'postmaster@example.com'; + $this->Controller->EmailTest->from = 'noreply@example.com'; + $this->Controller->EmailTest->subject = 'Cake Debug Test'; + $this->Controller->EmailTest->replyTo = 'noreply@example.com'; + $this->Controller->EmailTest->template = null; + + $this->Controller->EmailTest->delivery = 'DebugComp'; + $this->Controller->EmailTest->send('This is the body of the message'); + $result = DebugCompTransport::$lastEmail; + + $this->assertRegExp('/To: postmaster@example.com\n/', $result); + $this->assertRegExp('/Subject: Cake Debug Test\n/', $result); + $this->assertRegExp('/Reply-To: noreply@example.com\n/', $result); + $this->assertRegExp('/From: noreply@example.com\n/', $result); + $this->assertRegExp('/Date: ' . preg_quote(self::$sentDate) . '\n/', $result); + $this->assertRegExp('/X-Mailer: CakePHP Email Component\n/', $result); + $this->assertRegExp('/Content-Type: text\/plain; charset=UTF-8\n/', $result); + $this->assertRegExp('/Content-Transfer-Encoding: 8bitMessage:\n/', $result); + $this->assertRegExp('/This is the body of the message/', $result); + $this->Controller->Session = $session; + } + +/** + * testMessageRetrievalWithoutTemplate method + * + * @return void + */ + public function testMessageRetrievalWithoutTemplate() { + App::build(array( + 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS) + )); + + $this->Controller->EmailTest->to = 'postmaster@example.com'; + $this->Controller->EmailTest->from = 'noreply@example.com'; + $this->Controller->EmailTest->subject = 'Cake Debug Test'; + $this->Controller->EmailTest->replyTo = 'noreply@example.com'; + $this->Controller->EmailTest->layout = 'default'; + $this->Controller->EmailTest->template = null; + + $this->Controller->EmailTest->delivery = 'DebugComp'; + + $text = $html = "This is the body of the message\n"; + + $this->Controller->EmailTest->sendAs = 'both'; + $this->assertTrue($this->Controller->EmailTest->send('This is the body of the message')); + $this->assertTextEquals($this->Controller->EmailTest->textMessage, $text); + $this->assertTextEquals($this->Controller->EmailTest->htmlMessage, $html); + + $this->Controller->EmailTest->sendAs = 'text'; + $this->assertTrue($this->Controller->EmailTest->send('This is the body of the message')); + $this->assertTextEquals($this->Controller->EmailTest->textMessage, $text); + $this->assertNull($this->Controller->EmailTest->htmlMessage); + + $this->Controller->EmailTest->sendAs = 'html'; + $this->assertTrue($this->Controller->EmailTest->send('This is the body of the message')); + $this->assertNull($this->Controller->EmailTest->textMessage); + $this->assertTextEquals($this->Controller->EmailTest->htmlMessage, $html); + } + +/** + * testMessageRetrievalWithTemplate method + * + * @return void + */ + public function testMessageRetrievalWithTemplate() { + App::build(array( + 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS) + )); + + $this->Controller->set('value', 22091985); + $this->Controller->set('title_for_layout', 'EmailTest'); + + $this->Controller->EmailTest->to = 'postmaster@example.com'; + $this->Controller->EmailTest->from = 'noreply@example.com'; + $this->Controller->EmailTest->subject = 'Cake Debug Test'; + $this->Controller->EmailTest->replyTo = 'noreply@example.com'; + $this->Controller->EmailTest->layout = 'default'; + $this->Controller->EmailTest->template = 'custom'; + + $this->Controller->EmailTest->delivery = 'DebugComp'; + + $text = << + + + + EmailTest + + + +

Here is your value: 22091985

+ +

This email was sent using the CakePHP Framework

+ + +HTMLBLOC; + + $this->Controller->EmailTest->sendAs = 'both'; + $this->assertTrue($this->Controller->EmailTest->send()); + $this->assertTextEquals($this->Controller->EmailTest->textMessage, $text); + $this->assertTextEquals($this->Controller->EmailTest->htmlMessage, $html); + + $this->Controller->EmailTest->sendAs = 'text'; + $this->assertTrue($this->Controller->EmailTest->send()); + $this->assertTextEquals($this->Controller->EmailTest->textMessage, $text); + $this->assertNull($this->Controller->EmailTest->htmlMessage); + + $this->Controller->EmailTest->sendAs = 'html'; + $this->assertTrue($this->Controller->EmailTest->send()); + $this->assertNull($this->Controller->EmailTest->textMessage); + $this->assertTextEquals($this->Controller->EmailTest->htmlMessage, $html); + } + +/** + * testMessageRetrievalWithHelper method + * + * @return void + */ + public function testMessageRetrievalWithHelper() { + App::build(array( + 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS) + )); + + $timestamp = time(); + $this->Controller->set('time', $timestamp); + $this->Controller->set('title_for_layout', 'EmailTest'); + $this->Controller->helpers = array('Time'); + + $this->Controller->EmailTest->to = 'postmaster@example.com'; + $this->Controller->EmailTest->from = 'noreply@example.com'; + $this->Controller->EmailTest->subject = 'Cake Debug Test'; + $this->Controller->EmailTest->replyTo = 'noreply@example.com'; + $this->Controller->EmailTest->layout = 'default'; + $this->Controller->EmailTest->template = 'custom_helper'; + $this->Controller->EmailTest->sendAs = 'text'; + $this->Controller->EmailTest->delivery = 'DebugComp'; + + $this->assertTrue($this->Controller->EmailTest->send()); + $this->assertTrue((bool)strpos($this->Controller->EmailTest->textMessage, 'Right now: ' . date('Y-m-d\TH:i:s\Z', $timestamp))); + } + +/** + * testContentArray method + * + * @return void + */ + public function testSendContentArray() { + $this->Controller->EmailTest->to = 'postmaster@example.com'; + $this->Controller->EmailTest->from = 'noreply@example.com'; + $this->Controller->EmailTest->subject = 'Cake Debug Test'; + $this->Controller->EmailTest->replyTo = 'noreply@example.com'; + $this->Controller->EmailTest->template = null; + $this->Controller->EmailTest->delivery = 'DebugComp'; + + $content = array('First line', 'Second line', 'Third line'); + $this->assertTrue($this->Controller->EmailTest->send($content)); + $result = DebugCompTransport::$lastEmail; + + $this->assertRegExp('/To: postmaster@example.com\n/', $result); + $this->assertRegExp('/Subject: Cake Debug Test\n/', $result); + $this->assertRegExp('/Reply-To: noreply@example.com\n/', $result); + $this->assertRegExp('/From: noreply@example.com\n/', $result); + $this->assertRegExp('/X-Mailer: CakePHP Email Component\n/', $result); + $this->assertRegExp('/Content-Type: text\/plain; charset=UTF-8\n/', $result); + $this->assertRegExp('/Content-Transfer-Encoding: 8bitMessage:\n/', $result); + $this->assertRegExp('/First line\n/', $result); + $this->assertRegExp('/Second line\n/', $result); + $this->assertRegExp('/Third line\n/', $result); + } + +/** + * test setting a custom date. + * + * @return void + */ + public function testDateProperty() { + $this->Controller->EmailTest->to = 'postmaster@example.com'; + $this->Controller->EmailTest->from = 'noreply@example.com'; + $this->Controller->EmailTest->subject = 'Cake Debug Test'; + $this->Controller->EmailTest->date = self::$sentDate = 'Today!'; + $this->Controller->EmailTest->template = null; + $this->Controller->EmailTest->delivery = 'DebugComp'; + + $this->assertTrue($this->Controller->EmailTest->send('test message')); + $result = DebugCompTransport::$lastEmail; + $this->assertRegExp('/Date: Today!\n/', $result); + } + +/** + * testContentStripping method + * + * @return void + */ + public function testContentStripping() { + $content = "Previous content\n--alt-\nContent-TypeContent-Type:: text/html; charsetcharset==utf-8\nContent-Transfer-Encoding: 8bit"; + $content .= "\n\n

My own html content

"; + + $result = $this->Controller->EmailTest->strip($content, true); + $expected = "Previous content\n--alt-\n text/html; utf-8\n 8bit\n\n

My own html content

"; + $this->assertEquals($expected, $result); + + $content = '

Some HTML content with an email link'; + $result = $this->Controller->EmailTest->strip($content, true); + $expected = $content; + $this->assertEquals($expected, $result); + + $content = '

Some HTML content with an '; + $content .= 'email link'; + $result = $this->Controller->EmailTest->strip($content, true); + $expected = $content; + $this->assertEquals($expected, $result); + } + +/** + * test that the _encode() will set mb_internal_encoding. + * + * @return void + */ + public function testEncodeSettingInternalCharset() { + $this->skipIf(!function_exists('mb_internal_encoding'), 'Missing mb_* functions, cannot run test.'); + + $restore = mb_internal_encoding(); + mb_internal_encoding('ISO-8859-1'); + + $this->Controller->charset = 'UTF-8'; + $this->Controller->EmailTest->to = 'postmaster@example.com'; + $this->Controller->EmailTest->from = 'noreply@example.com'; + $this->Controller->EmailTest->subject = 'هذه رسالة بعنوان طويل مرسل للمستلم'; + $this->Controller->EmailTest->replyTo = 'noreply@example.com'; + $this->Controller->EmailTest->template = null; + $this->Controller->EmailTest->delivery = 'DebugComp'; + + $this->Controller->EmailTest->sendAs = 'text'; + $this->assertTrue($this->Controller->EmailTest->send('This is the body of the message')); + + $subject = '=?UTF-8?B?2YfYsNmHINix2LPYp9mE2Kkg2KjYudmG2YjYp9mGINi32YjZitmEINmF2LE=?=' . "\r\n" . ' =?UTF-8?B?2LPZhCDZhNmE2YXYs9iq2YTZhQ==?='; + + preg_match('/Subject: (.*)Header:/s', DebugCompTransport::$lastEmail, $matches); + $this->assertEquals(trim($matches[1]), $subject); + + $result = mb_internal_encoding(); + $this->assertEquals('ISO-8859-1', $result); + + mb_internal_encoding($restore); + } + +/** + * testMultibyte method + * + * @return void + */ + public function testMultibyte() { + $this->Controller->charset = 'UTF-8'; + $this->Controller->EmailTest->to = 'postmaster@example.com'; + $this->Controller->EmailTest->from = 'noreply@example.com'; + $this->Controller->EmailTest->subject = 'هذه رسالة بعنوان طويل مرسل للمستلم'; + $this->Controller->EmailTest->replyTo = 'noreply@example.com'; + $this->Controller->EmailTest->template = null; + $this->Controller->EmailTest->delivery = 'DebugComp'; + + $subject = '=?UTF-8?B?2YfYsNmHINix2LPYp9mE2Kkg2KjYudmG2YjYp9mGINi32YjZitmEINmF2LE=?=' . "\r\n" . ' =?UTF-8?B?2LPZhCDZhNmE2YXYs9iq2YTZhQ==?='; + + $this->Controller->EmailTest->sendAs = 'text'; + $this->assertTrue($this->Controller->EmailTest->send('This is the body of the message')); + preg_match('/Subject: (.*)Header:/s', DebugCompTransport::$lastEmail, $matches); + $this->assertEquals(trim($matches[1]), $subject); + + $this->Controller->EmailTest->sendAs = 'html'; + $this->assertTrue($this->Controller->EmailTest->send('This is the body of the message')); + preg_match('/Subject: (.*)Header:/s', DebugCompTransport::$lastEmail, $matches); + $this->assertEquals(trim($matches[1]), $subject); + + $this->Controller->EmailTest->sendAs = 'both'; + $this->assertTrue($this->Controller->EmailTest->send('This is the body of the message')); + preg_match('/Subject: (.*)Header:/s', DebugCompTransport::$lastEmail, $matches); + $this->assertEquals(trim($matches[1]), $subject); + } + +/** + * undocumented function + * + * @return void + */ + public function testSendWithAttachments() { + $this->Controller->EmailTest->to = 'postmaster@example.com'; + $this->Controller->EmailTest->from = 'noreply@example.com'; + $this->Controller->EmailTest->subject = 'Attachment Test'; + $this->Controller->EmailTest->replyTo = 'noreply@example.com'; + $this->Controller->EmailTest->template = null; + $this->Controller->EmailTest->delivery = 'DebugComp'; + $this->Controller->EmailTest->attachments = array( + __FILE__, + 'some-name.php' => __FILE__ + ); + $body = '

This is the body of the message

'; + + $this->Controller->EmailTest->sendAs = 'text'; + $this->assertTrue($this->Controller->EmailTest->send($body)); + $msg = DebugCompTransport::$lastEmail; + $this->assertRegExp('/' . preg_quote('Content-Disposition: attachment; filename="EmailComponentTest.php"') . '/', $msg); + $this->assertRegExp('/' . preg_quote('Content-Disposition: attachment; filename="some-name.php"') . '/', $msg); + } + +/** + * testSendAsIsNotIgnoredIfAttachmentsPresent method + * + * @return void + */ + public function testSendAsIsNotIgnoredIfAttachmentsPresent() { + $this->Controller->EmailTest->to = 'postmaster@example.com'; + $this->Controller->EmailTest->from = 'noreply@example.com'; + $this->Controller->EmailTest->subject = 'Attachment Test'; + $this->Controller->EmailTest->replyTo = 'noreply@example.com'; + $this->Controller->EmailTest->template = null; + $this->Controller->EmailTest->delivery = 'DebugComp'; + $this->Controller->EmailTest->attachments = array(__FILE__); + $body = '

This is the body of the message

'; + + $this->Controller->EmailTest->sendAs = 'html'; + $this->assertTrue($this->Controller->EmailTest->send($body)); + $msg = DebugCompTransport::$lastEmail; + $this->assertNotRegExp('/text\/plain/', $msg); + $this->assertRegExp('/text\/html/', $msg); + + $this->Controller->EmailTest->sendAs = 'text'; + $this->assertTrue($this->Controller->EmailTest->send($body)); + $msg = DebugCompTransport::$lastEmail; + $this->assertRegExp('/text\/plain/', $msg); + $this->assertNotRegExp('/text\/html/', $msg); + + $this->Controller->EmailTest->sendAs = 'both'; + $this->assertTrue($this->Controller->EmailTest->send($body)); + $msg = DebugCompTransport::$lastEmail; + + $this->assertRegExp('/text\/plain/', $msg); + $this->assertRegExp('/text\/html/', $msg); + $this->assertRegExp('/multipart\/alternative/', $msg); + } + +/** + * testNoDoubleNewlinesInHeaders function + * + * @return void + */ + public function testNoDoubleNewlinesInHeaders() { + $this->Controller->EmailTest->to = 'postmaster@example.com'; + $this->Controller->EmailTest->from = 'noreply@example.com'; + $this->Controller->EmailTest->subject = 'Attachment Test'; + $this->Controller->EmailTest->replyTo = 'noreply@example.com'; + $this->Controller->EmailTest->template = null; + $this->Controller->EmailTest->delivery = 'DebugComp'; + $body = '

This is the body of the message

'; + + $this->Controller->EmailTest->sendAs = 'both'; + $this->assertTrue($this->Controller->EmailTest->send($body)); + $msg = DebugCompTransport::$lastEmail; + + $this->assertNotRegExp('/\n\nContent-Transfer-Encoding/', $msg); + $this->assertRegExp('/\nContent-Transfer-Encoding/', $msg); + } + +/** + * testReset method + * + * @return void + */ + public function testReset() { + $this->Controller->EmailTest->template = 'default'; + $this->Controller->EmailTest->to = 'test.recipient@example.com'; + $this->Controller->EmailTest->from = 'test.sender@example.com'; + $this->Controller->EmailTest->replyTo = 'test.replyto@example.com'; + $this->Controller->EmailTest->return = 'test.return@example.com'; + $this->Controller->EmailTest->cc = array('cc1@example.com', 'cc2@example.com'); + $this->Controller->EmailTest->bcc = array('bcc1@example.com', 'bcc2@example.com'); + $this->Controller->EmailTest->date = 'Today!'; + $this->Controller->EmailTest->subject = 'Test subject'; + $this->Controller->EmailTest->additionalParams = 'X-additional-header'; + $this->Controller->EmailTest->delivery = 'smtp'; + $this->Controller->EmailTest->smtpOptions['host'] = 'blah'; + $this->Controller->EmailTest->smtpOptions['timeout'] = 0.2; + $this->Controller->EmailTest->attachments = array('attachment1', 'attachment2'); + $this->Controller->EmailTest->textMessage = 'This is the body of the message'; + $this->Controller->EmailTest->htmlMessage = 'This is the body of the message'; + $this->Controller->EmailTest->messageId = false; + + try { + $this->Controller->EmailTest->send('Should not work'); + $this->fail('No exception'); + } catch (SocketException $e) { + $this->assertTrue(true, 'SocketException raised'); + } + + $this->Controller->EmailTest->reset(); + + $this->assertNull($this->Controller->EmailTest->template); + $this->assertSame($this->Controller->EmailTest->to, array()); + $this->assertNull($this->Controller->EmailTest->from); + $this->assertNull($this->Controller->EmailTest->replyTo); + $this->assertNull($this->Controller->EmailTest->return); + $this->assertSame($this->Controller->EmailTest->cc, array()); + $this->assertSame($this->Controller->EmailTest->bcc, array()); + $this->assertNull($this->Controller->EmailTest->date); + $this->assertNull($this->Controller->EmailTest->subject); + $this->assertNull($this->Controller->EmailTest->additionalParams); + $this->assertNull($this->Controller->EmailTest->smtpError); + $this->assertSame($this->Controller->EmailTest->attachments, array()); + $this->assertNull($this->Controller->EmailTest->textMessage); + $this->assertTrue($this->Controller->EmailTest->messageId); + $this->assertEquals('mail', $this->Controller->EmailTest->delivery); + } + + public function testPluginCustomViewClass() { + App::build(array( + 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS), + 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS) + )); + + $this->Controller->view = 'TestPlugin.Email'; + + $this->Controller->EmailTest->to = 'postmaster@example.com'; + $this->Controller->EmailTest->from = 'noreply@example.com'; + $this->Controller->EmailTest->subject = 'CustomViewClass test'; + $this->Controller->EmailTest->delivery = 'DebugComp'; + $body = 'Body of message'; + + $this->assertTrue($this->Controller->EmailTest->send($body)); + $result = DebugCompTransport::$lastEmail; + + $this->assertRegExp('/Body of message/', $result); + } + +/** + * testStartup method + * + * @return void + */ + public function testStartup() { + $this->assertNull($this->Controller->EmailTest->startup($this->Controller)); + } + +/** + * testMessageId method + * + * @return void + */ + public function testMessageId() { + $this->Controller->EmailTest->to = 'postmaster@example.com'; + $this->Controller->EmailTest->from = 'noreply@example.com'; + $this->Controller->EmailTest->subject = 'Cake Debug Test'; + $this->Controller->EmailTest->replyTo = 'noreply@example.com'; + $this->Controller->EmailTest->template = null; + + $this->Controller->EmailTest->delivery = 'DebugComp'; + $this->assertTrue($this->Controller->EmailTest->send('This is the body of the message')); + $result = DebugCompTransport::$lastEmail; + + $host = env('HTTP_HOST') ? env('HTTP_HOST') : php_uname('n'); + $this->assertRegExp('/Message-ID: \<[a-f0-9]{8}[a-f0-9]{4}[a-f0-9]{4}[a-f0-9]{4}[a-f0-9]{12}@' . $host . '\>\n/', $result); + + $this->Controller->EmailTest->messageId = '<22091985.998877@example.com>'; + + $this->assertTrue($this->Controller->EmailTest->send('This is the body of the message')); + $result = DebugCompTransport::$lastEmail; + + $this->assertRegExp('/Message-ID: <22091985.998877@example.com>\n/', $result); + + $this->Controller->EmailTest->messageId = false; + + $this->assertTrue($this->Controller->EmailTest->send('This is the body of the message')); + $result = DebugCompTransport::$lastEmail; + + $this->assertNotRegExp('/Message-ID:/', $result); + } + +/** + * Make sure from/to are not double encoded when UTF-8 is present + */ + public function testEncodingFrom() { + $this->Controller->EmailTest->to = 'Teßt '; + $this->Controller->EmailTest->from = 'Teßt '; + $this->Controller->EmailTest->subject = 'Cake Debug Test'; + $this->Controller->EmailTest->replyTo = 'noreply@example.com'; + $this->Controller->EmailTest->template = null; + + $this->Controller->EmailTest->delivery = 'DebugComp'; + $this->assertTrue($this->Controller->EmailTest->send('This is the body of the message')); + $result = DebugCompTransport::$lastEmail; + + $this->assertContains('From: =?UTF-8?B?VGXDn3Qg?= ', $result); + $this->assertContains('To: =?UTF-8?B?VGXDn3Qg?= ', $result); + } + +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/PaginatorComponentTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/PaginatorComponentTest.php new file mode 100644 index 0000000..1908e92 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/PaginatorComponentTest.php @@ -0,0 +1,1194 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Controller.Component + * @since CakePHP(tm) v 2.0 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ + +App::uses('Controller', 'Controller'); +App::uses('PaginatorComponent', 'Controller/Component'); +App::uses('CakeRequest', 'Network'); +App::uses('CakeResponse', 'Network'); + +/** + * PaginatorTestController class + * + * @package Cake.Test.Case.Controller.Component + */ +class PaginatorTestController extends Controller { + +/** + * name property + * + * @var string 'PaginatorTest' + */ + public $name = 'PaginatorTest'; + +/** + * components property + * + * @var array + */ + public $components = array('Paginator'); +} + +/** + * PaginatorControllerPost class + * + * @package Cake.Test.Case.Controller.Component + */ +class PaginatorControllerPost extends CakeTestModel { + +/** + * name property + * + * @var string 'PaginatorControllerPost' + */ + public $name = 'PaginatorControllerPost'; + +/** + * useTable property + * + * @var string 'posts' + */ + public $useTable = 'posts'; + +/** + * invalidFields property + * + * @var array + */ + public $invalidFields = array('name' => 'error_msg'); + +/** + * lastQueries property + * + * @var array + */ + public $lastQueries = array(); + +/** + * belongsTo property + * + * @var array + */ + public $belongsTo = array('PaginatorAuthor' => array('foreignKey' => 'author_id')); + +/** + * beforeFind method + * + * @param mixed $query + * @return void + */ + public function beforeFind($query) { + array_unshift($this->lastQueries, $query); + } + +/** + * find method + * + * @param mixed $type + * @param array $options + * @return void + */ + public function find($conditions = null, $fields = array(), $order = null, $recursive = null) { + if ($conditions == 'popular') { + $conditions = array($this->name . '.' . $this->primaryKey . ' > ' => '1'); + $options = Hash::merge($fields, compact('conditions')); + return parent::find('all', $options); + } + return parent::find($conditions, $fields); + } + +} + +/** + * ControllerPaginateModel class + * + * @package Cake.Test.Case.Controller.Component + */ +class ControllerPaginateModel extends CakeTestModel { + +/** + * name property + * + * @var string 'ControllerPaginateModel' + */ + public $name = 'ControllerPaginateModel'; + +/** + * useTable property + * + * @var string 'comments' + */ + public $useTable = 'comments'; + +/** + * paginate method + * + * @return void + */ + public function paginate($conditions, $fields, $order, $limit, $page, $recursive, $extra) { + $this->extra = $extra; + } + +/** + * paginateCount + * + * @return void + */ + public function paginateCount($conditions, $recursive, $extra) { + $this->extraCount = $extra; + } + +} + +/** + * PaginatorControllerComment class + * + * @package Cake.Test.Case.Controller.Component + */ +class PaginatorControllerComment extends CakeTestModel { + +/** + * name property + * + * @var string 'Comment' + */ + public $name = 'Comment'; + +/** + * useTable property + * + * @var string 'comments' + */ + public $useTable = 'comments'; + +/** + * alias property + * + * @var string 'PaginatorControllerComment' + */ + public $alias = 'PaginatorControllerComment'; +} + +/** + * PaginatorAuthor class + * + * @package Cake.Test.Case.Controller.Component + */ +class PaginatorAuthor extends CakeTestModel { + +/** + * name property + * + * @var string 'PaginatorAuthor' + */ + public $name = 'PaginatorAuthor'; + +/** + * useTable property + * + * @var string 'authors' + */ + public $useTable = 'authors'; + +/** + * alias property + * + * @var string 'PaginatorAuthor' + */ + public $alias = 'PaginatorAuthor'; + +/** + * alias property + * + * @var string 'PaginatorAuthor' + */ + public $virtualFields = array( + 'joined_offset' => 'PaginatorAuthor.id + 1' + ); + +} + +/** + * PaginatorCustomPost class + * + * @package Cake.Test.Case.Controller.Component + */ +class PaginatorCustomPost extends CakeTestModel { + +/** + * useTable property + * + * @var string + */ + public $useTable = 'posts'; + +/** + * belongsTo property + * + * @var string + */ + public $belongsTo = array('Author'); + +/** + * findMethods property + * + * @var array + */ + public $findMethods = array( + 'published' => true, + 'totals' => true, + 'totalsOperation' => true + ); + +/** + * _findPublished custom find + * + * @return array + */ + protected function _findPublished($state, $query, $results = array()) { + if ($state === 'before') { + $query['conditions']['published'] = 'Y'; + return $query; + } + return $results; + } + +/** + * _findTotals custom find + * + * @return array + */ + protected function _findTotals($state, $query, $results = array()) { + if ($state == 'before') { + $query['fields'] = array('author_id'); + $this->virtualFields['total_posts'] = "COUNT({$this->alias}.id)"; + $query['fields'][] = 'total_posts'; + $query['group'] = array('author_id'); + $query['order'] = array('author_id' => 'ASC'); + return $query; + } + $this->virtualFields = array(); + return $results; + } + +/** + * _findTotalsOperation custom find + * + * @return array + */ + protected function _findTotalsOperation($state, $query, $results = array()) { + if ($state == 'before') { + if (!empty($query['operation']) && $query['operation'] === 'count') { + unset($query['limit']); + $query['recursive'] = -1; + $query['fields'] = array('COUNT(DISTINCT author_id) AS count'); + return $query; + } + $query['recursive'] = 0; + $query['callbacks'] = 'before'; + $query['fields'] = array('author_id', 'Author.user'); + $this->virtualFields['total_posts'] = "COUNT({$this->alias}.id)"; + $query['fields'][] = 'total_posts'; + $query['group'] = array('author_id', 'Author.user'); + $query['order'] = array('author_id' => 'ASC'); + return $query; + } + $this->virtualFields = array(); + return $results; + } + +} + +class PaginatorComponentTest extends CakeTestCase { + +/** + * fixtures property + * + * @var array + */ + public $fixtures = array('core.post', 'core.comment', 'core.author'); + +/** + * setup + * + * @return void + */ + public function setUp() { + parent::setUp(); + $this->request = new CakeRequest('controller_posts/index'); + $this->request->params['pass'] = $this->request->params['named'] = array(); + $this->Controller = new Controller($this->request); + $this->Paginator = new PaginatorComponent($this->getMock('ComponentCollection'), array()); + $this->Paginator->Controller = $this->Controller; + $this->Controller->Post = $this->getMock('Model'); + $this->Controller->Post->alias = 'Post'; + } + +/** + * testPaginate method + * + * @return void + */ + public function testPaginate() { + $Controller = new PaginatorTestController($this->request); + $Controller->uses = array('PaginatorControllerPost', 'PaginatorControllerComment'); + $Controller->request->params['pass'] = array('1'); + $Controller->request->query = array(); + $Controller->constructClasses(); + + $results = Hash::extract($Controller->Paginator->paginate('PaginatorControllerPost'), '{n}.PaginatorControllerPost.id'); + $this->assertEquals(array(1, 2, 3), $results); + + $results = Hash::extract($Controller->Paginator->paginate('PaginatorControllerComment'), '{n}.PaginatorControllerComment.id'); + $this->assertEquals(array(1, 2, 3, 4, 5, 6), $results); + + $Controller->modelClass = null; + + $Controller->uses[0] = 'Plugin.PaginatorControllerPost'; + $results = Hash::extract($Controller->Paginator->paginate(), '{n}.PaginatorControllerPost.id'); + $this->assertEquals(array(1, 2, 3), $results); + + $Controller->request->params['named'] = array('page' => '-1'); + $results = Hash::extract($Controller->Paginator->paginate('PaginatorControllerPost'), '{n}.PaginatorControllerPost.id'); + $this->assertEquals(1, $Controller->params['paging']['PaginatorControllerPost']['page']); + $this->assertEquals(array(1, 2, 3), $results); + + $Controller->request->params['named'] = array('sort' => 'PaginatorControllerPost.id', 'direction' => 'asc'); + $results = Hash::extract($Controller->Paginator->paginate('PaginatorControllerPost'), '{n}.PaginatorControllerPost.id'); + $this->assertEquals(1, $Controller->params['paging']['PaginatorControllerPost']['page']); + $this->assertEquals(array(1, 2, 3), $results); + + $Controller->request->params['named'] = array('sort' => 'PaginatorControllerPost.id', 'direction' => 'desc'); + $results = Hash::extract($Controller->Paginator->paginate('PaginatorControllerPost'), '{n}.PaginatorControllerPost.id'); + $this->assertEquals(1, $Controller->params['paging']['PaginatorControllerPost']['page']); + $this->assertEquals(array(3, 2, 1), $results); + + $Controller->request->params['named'] = array('sort' => 'id', 'direction' => 'desc'); + $results = Hash::extract($Controller->Paginator->paginate('PaginatorControllerPost'), '{n}.PaginatorControllerPost.id'); + $this->assertEquals(1, $Controller->params['paging']['PaginatorControllerPost']['page']); + $this->assertEquals(array(3, 2, 1), $results); + + $Controller->request->params['named'] = array('sort' => 'NotExisting.field', 'direction' => 'desc'); + $results = Hash::extract($Controller->Paginator->paginate('PaginatorControllerPost'), '{n}.PaginatorControllerPost.id'); + $this->assertEquals(1, $Controller->params['paging']['PaginatorControllerPost']['page'], 'Invalid field in query %s'); + $this->assertEquals(array(1, 2, 3), $results); + + $Controller->request->params['named'] = array( + 'sort' => 'PaginatorControllerPost.author_id', 'direction' => 'allYourBase' + ); + $results = Hash::extract($Controller->Paginator->paginate('PaginatorControllerPost'), '{n}.PaginatorControllerPost.id'); + $this->assertEquals(array('PaginatorControllerPost.author_id' => 'asc'), $Controller->PaginatorControllerPost->lastQueries[1]['order'][0]); + $this->assertEquals(array(1, 3, 2), $results); + + $Controller->request->params['named'] = array(); + $Controller->Paginator->settings = array('limit' => 0, 'maxLimit' => 10, 'paramType' => 'named'); + $Controller->Paginator->paginate('PaginatorControllerPost'); + $this->assertSame(1, $Controller->params['paging']['PaginatorControllerPost']['page']); + $this->assertSame($Controller->params['paging']['PaginatorControllerPost']['pageCount'], 3); + $this->assertSame($Controller->params['paging']['PaginatorControllerPost']['prevPage'], false); + $this->assertSame($Controller->params['paging']['PaginatorControllerPost']['nextPage'], true); + + $Controller->request->params['named'] = array(); + $Controller->Paginator->settings = array('limit' => 'garbage!', 'maxLimit' => 10, 'paramType' => 'named'); + $Controller->Paginator->paginate('PaginatorControllerPost'); + $this->assertSame(1, $Controller->params['paging']['PaginatorControllerPost']['page']); + $this->assertSame($Controller->params['paging']['PaginatorControllerPost']['pageCount'], 3); + $this->assertSame($Controller->params['paging']['PaginatorControllerPost']['prevPage'], false); + $this->assertSame($Controller->params['paging']['PaginatorControllerPost']['nextPage'], true); + + $Controller->request->params['named'] = array(); + $Controller->Paginator->settings = array('limit' => '-1', 'maxLimit' => 10, 'paramType' => 'named'); + $Controller->Paginator->paginate('PaginatorControllerPost'); + + $this->assertSame($Controller->params['paging']['PaginatorControllerPost']['limit'], 1); + $this->assertSame(1, $Controller->params['paging']['PaginatorControllerPost']['page']); + $this->assertSame($Controller->params['paging']['PaginatorControllerPost']['pageCount'], 3); + $this->assertSame($Controller->params['paging']['PaginatorControllerPost']['prevPage'], false); + $this->assertSame($Controller->params['paging']['PaginatorControllerPost']['nextPage'], true); + + $Controller->Paginator->settings = array('conditions' => array('PaginatorAuthor.user' => 'mariano')); + $Controller->Paginator->paginate('PaginatorControllerPost'); + + $this->assertSame(2, $Controller->params['paging']['PaginatorControllerPost']['count']); + } + +/** + * Test that non-numeric values are rejected for page, and limit + * + * @return void + */ + public function testPageParamCasting() { + $this->Controller->Post->expects($this->at(0)) + ->method('hasMethod') + ->with('paginate') + ->will($this->returnValue(false)); + + $this->Controller->Post->expects($this->at(1)) + ->method('find') + ->will($this->returnValue(array('stuff'))); + + $this->Controller->Post->expects($this->at(2)) + ->method('hasMethod') + ->with('paginateCount') + ->will($this->returnValue(false)); + + $this->Controller->Post->expects($this->at(3)) + ->method('find') + ->will($this->returnValue(2)); + + $this->request->params['named'] = array('page' => '1 " onclick="alert(\'xss\');">'); + $this->Paginator->settings = array('limit' => 1, 'maxLimit' => 10, 'paramType' => 'named'); + $this->Paginator->paginate('Post'); + $this->assertSame(1, $this->request->params['paging']['Post']['page'], 'XSS exploit opened'); + } + +/** + * testPaginateExtraParams method + * + * @return void + */ + public function testPaginateExtraParams() { + $Controller = new PaginatorTestController($this->request); + + $Controller->uses = array('PaginatorControllerPost', 'PaginatorControllerComment'); + $Controller->request->params['pass'] = array('1'); + $Controller->params['url'] = array(); + $Controller->constructClasses(); + + $Controller->request->params['named'] = array('page' => '-1', 'contain' => array('PaginatorControllerComment')); + $result = $Controller->Paginator->paginate('PaginatorControllerPost'); + $this->assertEquals(1, $Controller->params['paging']['PaginatorControllerPost']['page']); + $this->assertEquals(array(1, 2, 3), Hash::extract($result, '{n}.PaginatorControllerPost.id')); + $this->assertTrue(!isset($Controller->PaginatorControllerPost->lastQueries[1]['contain'])); + + $Controller->request->params['named'] = array('page' => '-1'); + $Controller->Paginator->settings = array( + 'PaginatorControllerPost' => array( + 'contain' => array('PaginatorControllerComment'), + 'maxLimit' => 10, + 'paramType' => 'named' + ), + ); + $result = $Controller->Paginator->paginate('PaginatorControllerPost'); + $this->assertEquals(1, $Controller->params['paging']['PaginatorControllerPost']['page']); + $this->assertEquals(array(1, 2, 3), Hash::extract($result, '{n}.PaginatorControllerPost.id')); + $this->assertTrue(isset($Controller->PaginatorControllerPost->lastQueries[1]['contain'])); + + $Controller->Paginator->settings = array( + 'PaginatorControllerPost' => array( + 'popular', 'fields' => array('id', 'title'), 'maxLimit' => 10, 'paramType' => 'named' + ), + ); + $result = $Controller->Paginator->paginate('PaginatorControllerPost'); + $this->assertEquals(array(2, 3), Hash::extract($result, '{n}.PaginatorControllerPost.id')); + $this->assertEquals(array('PaginatorControllerPost.id > ' => '1'), $Controller->PaginatorControllerPost->lastQueries[1]['conditions']); + + $Controller->request->params['named'] = array('limit' => 12); + $Controller->Paginator->settings = array('limit' => 30, 'maxLimit' => 100, 'paramType' => 'named'); + $result = $Controller->Paginator->paginate('PaginatorControllerPost'); + $paging = $Controller->params['paging']['PaginatorControllerPost']; + + $this->assertEquals(12, $Controller->PaginatorControllerPost->lastQueries[1]['limit']); + $this->assertEquals(12, $paging['options']['limit']); + + $Controller = new PaginatorTestController($this->request); + $Controller->uses = array('ControllerPaginateModel'); + $Controller->request->query = array(); + $Controller->constructClasses(); + $Controller->Paginator->settings = array( + 'ControllerPaginateModel' => array( + 'contain' => array('ControllerPaginateModel'), + 'group' => 'Comment.author_id', + 'maxLimit' => 10, + 'paramType' => 'named' + ) + ); + $result = $Controller->Paginator->paginate('ControllerPaginateModel'); + $expected = array( + 'contain' => array('ControllerPaginateModel'), + 'group' => 'Comment.author_id', + 'maxLimit' => 10, + 'paramType' => 'named' + ); + $this->assertEquals($expected, $Controller->ControllerPaginateModel->extra); + $this->assertEquals($expected, $Controller->ControllerPaginateModel->extraCount); + + $Controller->Paginator->settings = array( + 'ControllerPaginateModel' => array( + 'foo', 'contain' => array('ControllerPaginateModel'), + 'group' => 'Comment.author_id', + 'maxLimit' => 10, + 'paramType' => 'named' + ) + ); + $Controller->Paginator->paginate('ControllerPaginateModel'); + $expected = array( + 'contain' => array('ControllerPaginateModel'), + 'group' => 'Comment.author_id', + 'type' => 'foo', + 'maxLimit' => 10, + 'paramType' => 'named' + ); + $this->assertEquals($expected, $Controller->ControllerPaginateModel->extra); + $this->assertEquals($expected, $Controller->ControllerPaginateModel->extraCount); + } + +/** + * Test that special paginate types are called and that the type param doesn't leak out into defaults or options. + * + * @return void + */ + public function testPaginateSpecialType() { + $Controller = new PaginatorTestController($this->request); + $Controller->uses = array('PaginatorControllerPost', 'PaginatorControllerComment'); + $Controller->passedArgs[] = '1'; + $Controller->params['url'] = array(); + $Controller->constructClasses(); + + $Controller->Paginator->settings = array( + 'PaginatorControllerPost' => array( + 'popular', + 'fields' => array('id', 'title'), + 'maxLimit' => 10, + 'paramType' => 'named' + ) + ); + $result = $Controller->Paginator->paginate('PaginatorControllerPost'); + + $this->assertEquals(array(2, 3), Hash::extract($result, '{n}.PaginatorControllerPost.id')); + $this->assertEquals( + $Controller->PaginatorControllerPost->lastQueries[1]['conditions'], + array('PaginatorControllerPost.id > ' => '1') + ); + $this->assertFalse(isset($Controller->params['paging']['PaginatorControllerPost']['options'][0])); + } + +/** + * testDefaultPaginateParams method + * + * @return void + */ + public function testDefaultPaginateParams() { + $Controller = new PaginatorTestController($this->request); + $Controller->modelClass = 'PaginatorControllerPost'; + $Controller->params['url'] = array(); + $Controller->constructClasses(); + $Controller->Paginator->settings = array( + 'order' => 'PaginatorControllerPost.id DESC', + 'maxLimit' => 10, + 'paramType' => 'named' + ); + $results = Hash::extract($Controller->Paginator->paginate('PaginatorControllerPost'), '{n}.PaginatorControllerPost.id'); + $this->assertEquals('PaginatorControllerPost.id DESC', $Controller->params['paging']['PaginatorControllerPost']['order']); + $this->assertEquals(array(3, 2, 1), $results); + } + +/** + * test paginate() and virtualField interactions + * + * @return void + */ + public function testPaginateOrderVirtualField() { + $Controller = new PaginatorTestController($this->request); + $Controller->uses = array('PaginatorControllerPost', 'PaginatorControllerComment'); + $Controller->params['url'] = array(); + $Controller->constructClasses(); + $Controller->PaginatorControllerPost->virtualFields = array( + 'offset_test' => 'PaginatorControllerPost.id + 1' + ); + + $Controller->Paginator->settings = array( + 'fields' => array('id', 'title', 'offset_test'), + 'order' => array('offset_test' => 'DESC'), + 'maxLimit' => 10, + 'paramType' => 'named' + ); + $result = $Controller->Paginator->paginate('PaginatorControllerPost'); + $this->assertEquals(array(4, 3, 2), Hash::extract($result, '{n}.PaginatorControllerPost.offset_test')); + + $Controller->request->params['named'] = array('sort' => 'offset_test', 'direction' => 'asc'); + $result = $Controller->Paginator->paginate('PaginatorControllerPost'); + $this->assertEquals(array(2, 3, 4), Hash::extract($result, '{n}.PaginatorControllerPost.offset_test')); + } + +/** + * test paginate() and virtualField on joined model + * + * @return void + */ + public function testPaginateOrderVirtualFieldJoinedModel() { + $Controller = new PaginatorTestController($this->request); + $Controller->uses = array('PaginatorControllerPost'); + $Controller->params['url'] = array(); + $Controller->constructClasses(); + $Controller->PaginatorControllerPost->recursive = 0; + $Controller->Paginator->settings = array( + 'order' => array('PaginatorAuthor.joined_offset' => 'DESC'), + 'maxLimit' => 10, + 'paramType' => 'named' + ); + $result = $Controller->Paginator->paginate('PaginatorControllerPost'); + $this->assertEquals(array(4, 2, 2), Hash::extract($result, '{n}.PaginatorAuthor.joined_offset')); + + $Controller->request->params['named'] = array('sort' => 'PaginatorAuthor.joined_offset', 'direction' => 'asc'); + $result = $Controller->Paginator->paginate('PaginatorControllerPost'); + $this->assertEquals(array(2, 2, 4), Hash::extract($result, '{n}.PaginatorAuthor.joined_offset')); + } + +/** + * Tests for missing models + * + * @expectedException MissingModelException + */ + public function testPaginateMissingModel() { + $Controller = new PaginatorTestController($this->request); + $Controller->constructClasses(); + $Controller->Paginator->paginate('MissingModel'); + } + +/** + * test that option merging prefers specific models + * + * @return void + */ + public function testMergeOptionsModelSpecific() { + $this->Paginator->settings = array( + 'page' => 1, + 'limit' => 20, + 'maxLimit' => 100, + 'paramType' => 'named', + 'Post' => array( + 'page' => 1, + 'limit' => 10, + 'maxLimit' => 50, + 'paramType' => 'named', + ) + ); + $result = $this->Paginator->mergeOptions('Silly'); + $this->assertEquals($this->Paginator->settings, $result); + + $result = $this->Paginator->mergeOptions('Post'); + $expected = array('page' => 1, 'limit' => 10, 'paramType' => 'named', 'maxLimit' => 50); + $this->assertEquals($expected, $result); + } + +/** + * test mergeOptions with named params. + * + * @return void + */ + public function testMergeOptionsNamedParams() { + $this->request->params['named'] = array( + 'page' => 10, + 'limit' => 10 + ); + $this->Paginator->settings = array( + 'page' => 1, + 'limit' => 20, + 'maxLimit' => 100, + 'paramType' => 'named', + ); + $result = $this->Paginator->mergeOptions('Post'); + $expected = array('page' => 10, 'limit' => 10, 'maxLimit' => 100, 'paramType' => 'named'); + $this->assertEquals($expected, $result); + } + +/** + * test merging options from the querystring. + * + * @return void + */ + public function testMergeOptionsQueryString() { + $this->request->params['named'] = array( + 'page' => 10, + 'limit' => 10 + ); + $this->request->query = array( + 'page' => 99, + 'limit' => 75 + ); + $this->Paginator->settings = array( + 'page' => 1, + 'limit' => 20, + 'maxLimit' => 100, + 'paramType' => 'querystring', + ); + $result = $this->Paginator->mergeOptions('Post'); + $expected = array('page' => 99, 'limit' => 75, 'maxLimit' => 100, 'paramType' => 'querystring'); + $this->assertEquals($expected, $result); + } + +/** + * test that the default whitelist doesn't let people screw with things they should not be allowed to. + * + * @return void + */ + public function testMergeOptionsDefaultWhiteList() { + $this->request->params['named'] = array( + 'page' => 10, + 'limit' => 10, + 'fields' => array('bad.stuff'), + 'recursive' => 1000, + 'conditions' => array('bad.stuff'), + 'contain' => array('bad') + ); + $this->Paginator->settings = array( + 'page' => 1, + 'limit' => 20, + 'maxLimit' => 100, + 'paramType' => 'named', + ); + $result = $this->Paginator->mergeOptions('Post'); + $expected = array('page' => 10, 'limit' => 10, 'maxLimit' => 100, 'paramType' => 'named'); + $this->assertEquals($expected, $result); + } + +/** + * test that modifying the whitelist works. + * + * @return void + */ + public function testMergeOptionsExtraWhitelist() { + $this->request->params['named'] = array( + 'page' => 10, + 'limit' => 10, + 'fields' => array('bad.stuff'), + 'recursive' => 1000, + 'conditions' => array('bad.stuff'), + 'contain' => array('bad') + ); + $this->Paginator->settings = array( + 'page' => 1, + 'limit' => 20, + 'maxLimit' => 100, + 'paramType' => 'named', + ); + $this->Paginator->whitelist[] = 'fields'; + $result = $this->Paginator->mergeOptions('Post'); + $expected = array( + 'page' => 10, 'limit' => 10, 'maxLimit' => 100, 'paramType' => 'named', 'fields' => array('bad.stuff') + ); + $this->assertEquals($expected, $result); + } + +/** + * test that invalid directions are ignored. + * + * @return void + */ + public function testValidateSortInvalidDirection() { + $model = $this->getMock('Model'); + $model->alias = 'model'; + $model->expects($this->any())->method('hasField')->will($this->returnValue(true)); + + $options = array('sort' => 'something', 'direction' => 'boogers'); + $result = $this->Paginator->validateSort($model, $options); + + $this->assertEquals('asc', $result['order']['model.something']); + } + +/** + * Test that a really large page number gets clamped to the max page size. + */ + public function testOutOfRangePageNumberGetsClamped() { + $Controller = new PaginatorTestController($this->request); + $Controller->uses = array('PaginatorControllerPost'); + $Controller->params['named'] = array( + 'page' => 3000, + ); + $Controller->constructClasses(); + $Controller->PaginatorControllerPost->recursive = 0; + $Controller->Paginator->paginate('PaginatorControllerPost'); + $this->assertEquals( + 1, + $Controller->request->params['paging']['PaginatorControllerPost']['page'], + 'Super big page number should be capped to max number of pages' + ); + + $Controller->paginate = array( + 'conditions' => array('PaginatorControllerPost.id >' => 100) + ); + $Controller->Paginator->paginate('PaginatorControllerPost'); + $this->assertEquals( + 1, + $Controller->request->params['paging']['PaginatorControllerPost']['page'], + 'Page number should not be 0' + ); + } + +/** + * test that fields not in whitelist won't be part of order conditions. + * + * @return void + */ + public function testValidateSortWhitelistFailure() { + $model = $this->getMock('Model'); + $model->alias = 'model'; + $model->expects($this->any())->method('hasField')->will($this->returnValue(true)); + + $options = array('sort' => 'body', 'direction' => 'asc'); + $result = $this->Paginator->validateSort($model, $options, array('title', 'id')); + + $this->assertNull($result['order']); + } + +/** + * test that virtual fields work. + * + * @return void + */ + public function testValidateSortVirtualField() { + $model = $this->getMock('Model'); + $model->alias = 'model'; + + $model->expects($this->at(0)) + ->method('hasField') + ->with('something') + ->will($this->returnValue(false)); + + $model->expects($this->at(1)) + ->method('hasField') + ->with('something', true) + ->will($this->returnValue(true)); + + $options = array('sort' => 'something', 'direction' => 'desc'); + $result = $this->Paginator->validateSort($model, $options); + + $this->assertEquals('desc', $result['order']['something']); + } + +/** + * test that multiple sort works. + * + * @return void + */ + public function testValidateSortMultiple() { + $model = $this->getMock('Model'); + $model->alias = 'model'; + $model->expects($this->any())->method('hasField')->will($this->returnValue(true)); + + $options = array('order' => array( + 'author_id' => 'asc', + 'title' => 'asc' + )); + $result = $this->Paginator->validateSort($model, $options); + $expected = array( + 'model.author_id' => 'asc', + 'model.title' => 'asc' + ); + + $this->assertEquals($expected, $result['order']); + } + +/** + * Test that no sort doesn't trigger an error. + * + * @return void + */ + public function testValidateSortNoSort() { + $model = $this->getMock('Model'); + $model->alias = 'model'; + $model->expects($this->any())->method('hasField')->will($this->returnValue(true)); + + $options = array('direction' => 'asc'); + $result = $this->Paginator->validateSort($model, $options, array('title', 'id')); + $this->assertFalse(isset($result['order'])); + + $options = array('order' => 'invalid desc'); + $result = $this->Paginator->validateSort($model, $options, array('title', 'id')); + + $this->assertEquals($options['order'], $result['order']); + } + +/** + * test that maxLimit is respected + * + * @return void + */ + public function testCheckLimit() { + $result = $this->Paginator->checkLimit(array('limit' => 1000000, 'maxLimit' => 100)); + $this->assertEquals(100, $result['limit']); + + $result = $this->Paginator->checkLimit(array('limit' => 'sheep!', 'maxLimit' => 100)); + $this->assertEquals(1, $result['limit']); + + $result = $this->Paginator->checkLimit(array('limit' => '-1', 'maxLimit' => 100)); + $this->assertEquals(1, $result['limit']); + + $result = $this->Paginator->checkLimit(array('limit' => null, 'maxLimit' => 100)); + $this->assertEquals(1, $result['limit']); + + $result = $this->Paginator->checkLimit(array('limit' => 0, 'maxLimit' => 100)); + $this->assertEquals(1, $result['limit']); + } + +/** + * testPaginateMaxLimit + * + * @return void + */ + public function testPaginateMaxLimit() { + $Controller = new Controller($this->request); + + $Controller->uses = array('PaginatorControllerPost', 'ControllerComment'); + $Controller->passedArgs[] = '1'; + $Controller->constructClasses(); + + $Controller->request->params['named'] = array( + 'contain' => array('ControllerComment'), 'limit' => '1000' + ); + $result = $Controller->paginate('PaginatorControllerPost'); + $this->assertEquals(100, $Controller->params['paging']['PaginatorControllerPost']['options']['limit']); + + $Controller->request->params['named'] = array( + 'contain' => array('ControllerComment'), 'limit' => '1000', 'maxLimit' => 1000 + ); + $result = $Controller->paginate('PaginatorControllerPost'); + $this->assertEquals(100, $Controller->params['paging']['PaginatorControllerPost']['options']['limit']); + + $Controller->request->params['named'] = array('contain' => array('ControllerComment'), 'limit' => '10'); + $result = $Controller->paginate('PaginatorControllerPost'); + $this->assertEquals(10, $Controller->params['paging']['PaginatorControllerPost']['options']['limit']); + + $Controller->request->params['named'] = array('contain' => array('ControllerComment'), 'limit' => '1000'); + $Controller->paginate = array('maxLimit' => 2000, 'paramType' => 'named'); + $result = $Controller->paginate('PaginatorControllerPost'); + $this->assertEquals(1000, $Controller->params['paging']['PaginatorControllerPost']['options']['limit']); + + $Controller->request->params['named'] = array('contain' => array('ControllerComment'), 'limit' => '5000'); + $result = $Controller->paginate('PaginatorControllerPost'); + $this->assertEquals(2000, $Controller->params['paging']['PaginatorControllerPost']['options']['limit']); + } + +/** + * test paginate() and virtualField overlapping with real fields. + * + * @return void + */ + public function testPaginateOrderVirtualFieldSharedWithRealField() { + $Controller = new Controller($this->request); + $Controller->uses = array('PaginatorControllerPost', 'PaginatorControllerComment'); + $Controller->constructClasses(); + $Controller->PaginatorControllerComment->virtualFields = array( + 'title' => 'PaginatorControllerComment.comment' + ); + $Controller->PaginatorControllerComment->bindModel(array( + 'belongsTo' => array( + 'PaginatorControllerPost' => array( + 'className' => 'PaginatorControllerPost', + 'foreignKey' => 'article_id' + ) + ) + ), false); + + $Controller->paginate = array( + 'fields' => array('PaginatorControllerComment.id', 'title', 'PaginatorControllerPost.title'), + ); + $Controller->passedArgs = array('sort' => 'PaginatorControllerPost.title', 'dir' => 'asc'); + $result = $Controller->paginate('PaginatorControllerComment'); + $this->assertEquals(array(1, 2, 3, 4, 5, 6), Hash::extract($result, '{n}.PaginatorControllerComment.id')); + } + +/** + * test paginate() and custom find, to make sure the correct count is returned. + * + * @return void + */ + public function testPaginateCustomFind() { + $Controller =& new Controller($this->request); + $Controller->uses = array('PaginatorCustomPost'); + $Controller->constructClasses(); + $data = array('author_id' => 3, 'title' => 'Fourth Article', 'body' => 'Article Body, unpublished', 'published' => 'N'); + $Controller->PaginatorCustomPost->create($data); + $result = $Controller->PaginatorCustomPost->save(); + $this->assertTrue(!empty($result)); + + $result = $Controller->paginate(); + $this->assertEquals(array(1, 2, 3, 4), Hash::extract($result, '{n}.PaginatorCustomPost.id')); + + $result = $Controller->params['paging']['PaginatorCustomPost']; + $this->assertEquals(4, $result['current']); + $this->assertEquals(4, $result['count']); + + $Controller->paginate = array('published'); + $result = $Controller->paginate(); + $this->assertEquals(array(1, 2, 3), Hash::extract($result, '{n}.PaginatorCustomPost.id')); + + $result = $Controller->params['paging']['PaginatorCustomPost']; + $this->assertEquals(3, $result['current']); + $this->assertEquals(3, $result['count']); + + $Controller->paginate = array('published', 'limit' => 2); + $result = $Controller->paginate(); + $this->assertEquals(array(1, 2), Hash::extract($result, '{n}.PaginatorCustomPost.id')); + + $result = $Controller->params['paging']['PaginatorCustomPost']; + $this->assertEquals(2, $result['current']); + $this->assertEquals(3, $result['count']); + $this->assertEquals(2, $result['pageCount']); + $this->assertTrue($result['nextPage']); + $this->assertFalse($result['prevPage']); + } +/** + * test paginate() and custom find with fields array, to make sure the correct count is returned. + * + * @return void + */ + public function testPaginateCustomFindFieldsArray() { + $Controller =& new Controller($this->request); + $Controller->uses = array('PaginatorCustomPost'); + $Controller->constructClasses(); + $data = array('author_id' => 3, 'title' => 'Fourth Article', 'body' => 'Article Body, unpublished', 'published' => 'N'); + $Controller->PaginatorCustomPost->create($data); + $result = $Controller->PaginatorCustomPost->save(); + $this->assertTrue(!empty($result)); + + $Controller->paginate = array( + 'list', + 'conditions' => array('PaginatorCustomPost.published' => 'Y'), + 'limit' => 2 + ); + $result = $Controller->paginate(); + $expected = array( + 1 => 'First Post', + 2 => 'Second Post', + ); + $this->assertEquals($expected, $result); + $result = $Controller->params['paging']['PaginatorCustomPost']; + $this->assertEquals(2, $result['current']); + $this->assertEquals(3, $result['count']); + $this->assertEquals(2, $result['pageCount']); + $this->assertTrue($result['nextPage']); + $this->assertFalse($result['prevPage']); + } + +/** + * test paginate() and custom find with fields array, to make sure the correct count is returned. + * + * @return void + */ + public function testPaginateCustomFindGroupBy() { + $Controller =& new Controller($this->request); + $Controller->uses = array('PaginatorCustomPost'); + $Controller->constructClasses(); + $data = array('author_id' => 2, 'title' => 'Fourth Article', 'body' => 'Article Body, unpublished', 'published' => 'N'); + $Controller->PaginatorCustomPost->create($data); + $result = $Controller->PaginatorCustomPost->save(); + $this->assertTrue(!empty($result)); + + $Controller->paginate = array( + 'totals', + 'limit' => 2 + ); + $result = $Controller->paginate(); + $expected = array( + array( + 'PaginatorCustomPost' => array( + 'author_id' => '1', + 'total_posts' => '2' + ) + ), + array( + 'PaginatorCustomPost' => array( + 'author_id' => '2', + 'total_posts' => '1' + ) + ) + ); + $this->assertEquals($expected, $result); + $result = $Controller->params['paging']['PaginatorCustomPost']; + $this->assertEquals(2, $result['current']); + $this->assertEquals(3, $result['count']); + $this->assertEquals(2, $result['pageCount']); + $this->assertTrue($result['nextPage']); + $this->assertFalse($result['prevPage']); + + $Controller->paginate = array( + 'totals', + 'limit' => 2, + 'page' => 2 + ); + $result = $Controller->paginate(); + $expected = array( + array( + 'PaginatorCustomPost' => array( + 'author_id' => '3', + 'total_posts' => '1' + ) + ), + ); + $this->assertEquals($expected, $result); + $result = $Controller->params['paging']['PaginatorCustomPost']; + $this->assertEquals(1, $result['current']); + $this->assertEquals(3, $result['count']); + $this->assertEquals(2, $result['pageCount']); + $this->assertFalse($result['nextPage']); + $this->assertTrue($result['prevPage']); + } + +/** + * test paginate() and custom find with returning other query on count operation, + * to make sure the correct count is returned. + * + * @return void + */ + public function testPaginateCustomFindCount() { + $Controller =& new Controller($this->request); + $Controller->uses = array('PaginatorCustomPost'); + $Controller->constructClasses(); + $data = array('author_id' => 2, 'title' => 'Fourth Article', 'body' => 'Article Body, unpublished', 'published' => 'N'); + $Controller->PaginatorCustomPost->create($data); + $result = $Controller->PaginatorCustomPost->save(); + $this->assertTrue(!empty($result)); + + $Controller->paginate = array( + 'totalsOperation', + 'limit' => 2 + ); + $result = $Controller->paginate(); + $expected = array( + array( + 'PaginatorCustomPost' => array( + 'author_id' => '1', + 'total_posts' => '2' + ), + 'Author' => array( + 'user' => 'mariano', + ) + ), + array( + 'PaginatorCustomPost' => array( + 'author_id' => '2', + 'total_posts' => '1' + ), + 'Author' => array( + 'user' => 'nate' + ) + ) + ); + $this->assertEquals($expected, $result); + $result = $Controller->params['paging']['PaginatorCustomPost']; + $this->assertEquals(2, $result['current']); + $this->assertEquals(3, $result['count']); + $this->assertEquals(2, $result['pageCount']); + $this->assertTrue($result['nextPage']); + $this->assertFalse($result['prevPage']); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/RequestHandlerComponentTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/RequestHandlerComponentTest.php new file mode 100644 index 0000000..fb6c431 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/RequestHandlerComponentTest.php @@ -0,0 +1,879 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Controller.Component + * @since CakePHP(tm) v 1.2.0.5435 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ +App::uses('Controller', 'Controller'); +App::uses('RequestHandlerComponent', 'Controller/Component'); +App::uses('CakeRequest', 'Network'); +App::uses('CakeResponse', 'Network'); +App::uses('Router', 'Routing'); + +/** + * RequestHandlerTestController class + * + * @package Cake.Test.Case.Controller.Component + */ +class RequestHandlerTestController extends Controller { + +/** + * uses property + * + * @var mixed null + */ + public $uses = null; + +/** + * test method for ajax redirection + * + * @return void + */ + public function destination() { + $this->viewPath = 'Posts'; + $this->render('index'); + } + +/** + * test method for ajax redirection + parameter parsing + * + * @return void + */ + public function param_method($one = null, $two = null) { + echo "one: $one two: $two"; + $this->autoRender = false; + } + +/** + * test method for testing layout rendering when isAjax() + * + * @return void + */ + public function ajax2_layout() { + if ($this->autoLayout) { + $this->layout = 'ajax2'; + } + $this->destination(); + } + +} + + +/** + * RequestHandlerComponentTest class + * + * @package Cake.Test.Case.Controller.Component + */ +class RequestHandlerComponentTest extends CakeTestCase { + +/** + * Controller property + * + * @var RequestHandlerTestController + */ + public $Controller; + +/** + * RequestHandler property + * + * @var RequestHandlerComponent + */ + public $RequestHandler; + +/** + * setUp method + * + * @return void + */ + public function setUp() { + parent::setUp(); + $this->_init(); + } + +/** + * init method + * + * @return void + */ + protected function _init() { + $request = new CakeRequest('controller_posts/index'); + $response = new CakeResponse(); + $this->Controller = new RequestHandlerTestController($request, $response); + $this->Controller->constructClasses(); + $this->RequestHandler = new RequestHandlerComponent($this->Controller->Components); + $this->_extensions = Router::extensions(); + } + +/** + * tearDown method + * + * @return void + */ + public function tearDown() { + parent::tearDown(); + unset($this->RequestHandler, $this->Controller); + if (!headers_sent()) { + header('Content-type: text/html'); //reset content type. + } + call_user_func_array('Router::parseExtensions', $this->_extensions); + } + +/** + * Test that the constructor sets the settings. + * + * @return void + */ + public function testConstructorSettings() { + $settings = array( + 'ajaxLayout' => 'test_ajax' + ); + $Collection = new ComponentCollection(); + $Collection->init($this->Controller); + $RequestHandler = new RequestHandlerComponent($Collection, $settings); + $this->assertEquals('test_ajax', $RequestHandler->ajaxLayout); + } + +/** + * testInitializeCallback method + * + * @return void + */ + public function testInitializeCallback() { + $this->assertNull($this->RequestHandler->ext); + $this->Controller->request->params['ext'] = 'rss'; + $this->RequestHandler->initialize($this->Controller); + $this->assertEquals('rss', $this->RequestHandler->ext); + } + +/** + * test that a mapped Accept-type header will set $this->ext correctly. + * + * @return void + */ + public function testInitializeContentTypeSettingExt() { + $this->assertNull($this->RequestHandler->ext); + + $_SERVER['HTTP_ACCEPT'] = 'application/json'; + Router::parseExtensions('json'); + + $this->RequestHandler->initialize($this->Controller); + $this->assertEquals('json', $this->RequestHandler->ext); + } + +/** + * Test that RequestHandler sets $this->ext when jQuery sends its wonky-ish headers. + * + * @return void + */ + public function testInitializeContentTypeWithjQueryAccept() { + $_SERVER['HTTP_ACCEPT'] = 'application/json, text/javascript, */*; q=0.01'; + $this->assertNull($this->RequestHandler->ext); + Router::parseExtensions('json'); + + $this->RequestHandler->initialize($this->Controller); + $this->assertEquals('json', $this->RequestHandler->ext); + } + +/** + * Test that RequestHandler sets $this->ext when jQuery sends its wonky-ish headers + * and the application is configured to handle multiple extensions + * + * @return void + */ + public function testInitializeContentTypeWithjQueryAcceptAndMultiplesExtensions() { + $_SERVER['HTTP_ACCEPT'] = 'application/json, text/javascript, */*; q=0.01'; + $this->assertNull($this->RequestHandler->ext); + Router::parseExtensions('rss', 'json'); + + $this->RequestHandler->initialize($this->Controller); + $this->assertEquals('json', $this->RequestHandler->ext); + } + +/** + * Test that RequestHandler does not set $this->ext when multiple accepts are sent. + * + * @return void + */ + public function testInitializeNoContentTypeWithSingleAccept() { + $_SERVER['HTTP_ACCEPT'] = 'application/json, text/html, */*; q=0.01'; + $this->assertNull($this->RequestHandler->ext); + Router::parseExtensions('json'); + + $this->RequestHandler->initialize($this->Controller); + $this->assertNull($this->RequestHandler->ext); + } + +/** + * Test that ext is not set with multiple accepted content types. + * + * @return void + */ + public function testInitializeNoContentTypeWithMultipleAcceptedTypes() { + $_SERVER['HTTP_ACCEPT'] = 'application/json, text/javascript, application/xml, */*; q=0.01'; + $this->assertNull($this->RequestHandler->ext); + Router::parseExtensions('xml', 'json'); + + $this->RequestHandler->initialize($this->Controller); + $this->assertNull($this->RequestHandler->ext); + } + +/** + * Test that ext is not set with confusing android accepts headers. + * + * @return void + */ + public function testInitializeAmbiguousAndroidAccepts() { + $_SERVER['HTTP_ACCEPT'] = 'application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5'; + $this->assertNull($this->RequestHandler->ext); + Router::parseExtensions('html', 'xml'); + + $this->RequestHandler->initialize($this->Controller); + $this->assertNull($this->RequestHandler->ext); + } + +/** + * Test that a type mismatch doesn't incorrectly set the ext + * + * @return void + */ + public function testInitializeContentTypeAndExtensionMismatch() { + $this->assertNull($this->RequestHandler->ext); + $extensions = Router::extensions(); + Router::parseExtensions('xml'); + + $this->Controller->request = $this->getMock('CakeRequest'); + $this->Controller->request->expects($this->any()) + ->method('accepts') + ->will($this->returnValue(array('application/json'))); + + $this->RequestHandler->initialize($this->Controller); + $this->assertNull($this->RequestHandler->ext); + + call_user_func_array(array('Router', 'parseExtensions'), $extensions); + } + +/** + * testDisabling method + * + * @return void + */ + public function testDisabling() { + $_SERVER['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest'; + $this->_init(); + $this->RequestHandler->initialize($this->Controller); + $this->Controller->beforeFilter(); + $this->RequestHandler->startup($this->Controller); + $this->assertEquals(true, $this->Controller->params['isAjax']); + } + +/** + * testAutoResponseType method + * + * @return void + */ + public function testAutoResponseType() { + $this->Controller->ext = '.thtml'; + $this->Controller->request->params['ext'] = 'rss'; + $this->RequestHandler->initialize($this->Controller); + $this->RequestHandler->startup($this->Controller); + $this->assertEquals('.ctp', $this->Controller->ext); + } + +/** + * testAutoAjaxLayout method + * + * @return void + */ + public function testAutoAjaxLayout() { + $_SERVER['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest'; + $this->RequestHandler->startup($this->Controller); + $this->assertEquals($this->Controller->layout, $this->RequestHandler->ajaxLayout); + + $this->_init(); + $this->Controller->request->params['ext'] = 'js'; + $this->RequestHandler->initialize($this->Controller); + $this->RequestHandler->startup($this->Controller); + $this->assertNotEquals('ajax', $this->Controller->layout); + + unset($_SERVER['HTTP_X_REQUESTED_WITH']); + } + +/** + * testStartupCallback method + * + * @return void + */ + public function testStartupCallback() { + $_SERVER['REQUEST_METHOD'] = 'PUT'; + $_SERVER['CONTENT_TYPE'] = 'application/xml'; + $this->Controller->request = $this->getMock('CakeRequest', array('_readInput')); + $this->RequestHandler->startup($this->Controller); + $this->assertTrue(is_array($this->Controller->data)); + $this->assertFalse(is_object($this->Controller->data)); + } + +/** + * testStartupCallback with charset. + * + * @return void + */ + public function testStartupCallbackCharset() { + $_SERVER['REQUEST_METHOD'] = 'PUT'; + $_SERVER['CONTENT_TYPE'] = 'application/xml; charset=UTF-8'; + $this->Controller->request = $this->getMock('CakeRequest', array('_readInput')); + $this->RequestHandler->startup($this->Controller); + $this->assertTrue(is_array($this->Controller->data)); + $this->assertFalse(is_object($this->Controller->data)); + } + +/** + * Test mapping a new type and having startup process it. + * + * @return void + */ + public function testStartupCustomTypeProcess() { + if (!function_exists('str_getcsv')) { + $this->markTestSkipped('Need "str_getcsv" for this test.'); + } + $_SERVER['REQUEST_METHOD'] = 'POST'; + $_SERVER['CONTENT_TYPE'] = 'text/csv'; + $this->Controller->request = $this->getMock('CakeRequest', array('_readInput')); + $this->Controller->request->expects($this->once()) + ->method('_readInput') + ->will($this->returnValue('"A","csv","string"')); + $this->RequestHandler->addInputType('csv', array('str_getcsv')); + $this->RequestHandler->startup($this->Controller); + $expected = array( + 'A', 'csv', 'string' + ); + $this->assertEquals($expected, $this->Controller->request->data); + } + +/** + * testNonAjaxRedirect method + * + * @return void + */ + public function testNonAjaxRedirect() { + $this->RequestHandler->initialize($this->Controller); + $this->RequestHandler->startup($this->Controller); + $this->assertNull($this->RequestHandler->beforeRedirect($this->Controller, '/')); + } + +/** + * testRenderAs method + * + * @return void + */ + public function testRenderAs() { + $this->assertFalse(in_array('Rss', $this->Controller->helpers)); + $this->RequestHandler->renderAs($this->Controller, 'rss'); + $this->assertTrue(in_array('Rss', $this->Controller->helpers)); + + $this->Controller->viewPath = 'request_handler_test\\rss'; + $this->RequestHandler->renderAs($this->Controller, 'js'); + $this->assertEquals('request_handler_test' . DS . 'js', $this->Controller->viewPath); + } + +/** + * test that attachment headers work with renderAs + * + * @return void + */ + public function testRenderAsWithAttachment() { + $this->RequestHandler->request = $this->getMock('CakeRequest'); + $this->RequestHandler->request->expects($this->any()) + ->method('parseAccept') + ->will($this->returnValue(array('1.0' => array('application/xml')))); + + $this->RequestHandler->response = $this->getMock('CakeResponse', array('type', 'download', 'charset')); + $this->RequestHandler->response->expects($this->at(0)) + ->method('type') + ->with('application/xml'); + $this->RequestHandler->response->expects($this->at(1)) + ->method('charset') + ->with('UTF-8'); + $this->RequestHandler->response->expects($this->at(2)) + ->method('download') + ->with('myfile.xml'); + + $this->RequestHandler->renderAs($this->Controller, 'xml', array('attachment' => 'myfile.xml')); + + $this->assertEquals('Xml', $this->Controller->viewClass); + } + +/** + * test that respondAs works as expected. + * + * @return void + */ + public function testRespondAs() { + $this->RequestHandler->response = $this->getMock('CakeResponse', array('type')); + $this->RequestHandler->response->expects($this->at(0))->method('type') + ->with('application/json'); + $this->RequestHandler->response->expects($this->at(1))->method('type') + ->with('text/xml'); + + $result = $this->RequestHandler->respondAs('json'); + $this->assertTrue($result); + $result = $this->RequestHandler->respondAs('text/xml'); + $this->assertTrue($result); + } + +/** + * test that attachment headers work with respondAs + * + * @return void + */ + public function testRespondAsWithAttachment() { + $this->RequestHandler = $this->getMock( + 'RequestHandlerComponent', + array('_header'), + array(&$this->Controller->Components) + ); + $this->RequestHandler->response = $this->getMock('CakeResponse', array('type', 'download')); + $this->RequestHandler->request = $this->getMock('CakeRequest'); + + $this->RequestHandler->request->expects($this->once()) + ->method('parseAccept') + ->will($this->returnValue(array('1.0' => array('application/xml')))); + + $this->RequestHandler->response->expects($this->once())->method('download') + ->with('myfile.xml'); + $this->RequestHandler->response->expects($this->once())->method('type') + ->with('application/xml'); + + $result = $this->RequestHandler->respondAs('xml', array('attachment' => 'myfile.xml')); + $this->assertTrue($result); + } + +/** + * test that calling renderAs() more than once continues to work. + * + * @link #6466 + * @return void + */ + public function testRenderAsCalledTwice() { + $this->RequestHandler->renderAs($this->Controller, 'print'); + $this->assertEquals('RequestHandlerTest' . DS . 'print', $this->Controller->viewPath); + $this->assertEquals('print', $this->Controller->layoutPath); + + $this->RequestHandler->renderAs($this->Controller, 'js'); + $this->assertEquals('RequestHandlerTest' . DS . 'js', $this->Controller->viewPath); + $this->assertEquals('js', $this->Controller->layoutPath); + $this->assertTrue(in_array('Js', $this->Controller->helpers)); + } + +/** + * testRequestClientTypes method + * + * @return void + */ + public function testRequestClientTypes() { + $_SERVER['HTTP_X_PROTOTYPE_VERSION'] = '1.5'; + $this->assertEquals('1.5', $this->RequestHandler->getAjaxVersion()); + + unset($_SERVER['HTTP_X_REQUESTED_WITH'], $_SERVER['HTTP_X_PROTOTYPE_VERSION']); + $this->assertFalse($this->RequestHandler->getAjaxVersion()); + } + +/** + * Tests the detection of various Flash versions + * + * @return void + */ + public function testFlashDetection() { + $request = $this->getMock('CakeRequest'); + $request->expects($this->once())->method('is') + ->with('flash') + ->will($this->returnValue(true)); + + $this->RequestHandler->request = $request; + $this->assertTrue($this->RequestHandler->isFlash()); + } + +/** + * testRequestContentTypes method + * + * @return void + */ + public function testRequestContentTypes() { + $_SERVER['REQUEST_METHOD'] = 'GET'; + $this->assertNull($this->RequestHandler->requestedWith()); + + $_SERVER['REQUEST_METHOD'] = 'POST'; + $_SERVER['CONTENT_TYPE'] = 'application/json'; + $this->assertEquals('json', $this->RequestHandler->requestedWith()); + + $result = $this->RequestHandler->requestedWith(array('json', 'xml')); + $this->assertEquals('json', $result); + + $result = $this->RequestHandler->requestedWith(array('rss', 'atom')); + $this->assertFalse($result); + + $_SERVER['HTTP_ACCEPT'] = 'text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,*/*'; + $this->assertTrue($this->RequestHandler->isXml()); + $this->assertFalse($this->RequestHandler->isAtom()); + $this->assertFalse($this->RequestHandler->isRSS()); + + $_SERVER['HTTP_ACCEPT'] = 'application/atom+xml,text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,*/*'; + $this->assertTrue($this->RequestHandler->isAtom()); + $this->assertFalse($this->RequestHandler->isRSS()); + + $_SERVER['HTTP_ACCEPT'] = 'application/rss+xml,text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,*/*'; + $this->assertFalse($this->RequestHandler->isAtom()); + $this->assertTrue($this->RequestHandler->isRSS()); + + $this->assertFalse($this->RequestHandler->isWap()); + $_SERVER['HTTP_ACCEPT'] = 'text/vnd.wap.wml,text/html,text/plain,image/png,*/*'; + $this->assertTrue($this->RequestHandler->isWap()); + + $_SERVER['HTTP_ACCEPT'] = 'application/rss+xml,text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,*/*'; + } + +/** + * testResponseContentType method + * + * @return void + */ + public function testResponseContentType() { + $this->assertEquals('html', $this->RequestHandler->responseType()); + $this->assertTrue($this->RequestHandler->respondAs('atom')); + $this->assertEquals('atom', $this->RequestHandler->responseType()); + } + +/** + * testMobileDeviceDetection method + * + * @return void + */ + public function testMobileDeviceDetection() { + $request = $this->getMock('CakeRequest'); + $request->expects($this->once())->method('is') + ->with('mobile') + ->will($this->returnValue(true)); + + $this->RequestHandler->request = $request; + $this->assertTrue($this->RequestHandler->isMobile()); + } + +/** + * testRequestProperties method + * + * @return void + */ + public function testRequestProperties() { + $request = $this->getMock('CakeRequest'); + $request->expects($this->once())->method('is') + ->with('ssl') + ->will($this->returnValue(true)); + + $this->RequestHandler->request = $request; + $this->assertTrue($this->RequestHandler->isSsl()); + } + +/** + * testRequestMethod method + * + * @return void + */ + public function testRequestMethod() { + $request = $this->getMock('CakeRequest'); + $request->expects($this->at(0))->method('is') + ->with('get') + ->will($this->returnValue(true)); + + $request->expects($this->at(1))->method('is') + ->with('post') + ->will($this->returnValue(false)); + + $request->expects($this->at(2))->method('is') + ->with('delete') + ->will($this->returnValue(true)); + + $request->expects($this->at(3))->method('is') + ->with('put') + ->will($this->returnValue(false)); + + $this->RequestHandler->request = $request; + $this->assertTrue($this->RequestHandler->isGet()); + $this->assertFalse($this->RequestHandler->isPost()); + $this->assertTrue($this->RequestHandler->isDelete()); + $this->assertFalse($this->RequestHandler->isPut()); + } + +/** + * test that map alias converts aliases to content types. + * + * @return void + */ + public function testMapAlias() { + $result = $this->RequestHandler->mapAlias('xml'); + $this->assertEquals('application/xml', $result); + + $result = $this->RequestHandler->mapAlias('text/html'); + $this->assertNull($result); + + $result = $this->RequestHandler->mapAlias('wap'); + $this->assertEquals('text/vnd.wap.wml', $result); + + $result = $this->RequestHandler->mapAlias(array('xml', 'js', 'json')); + $expected = array('application/xml', 'text/javascript', 'application/json'); + $this->assertEquals($expected, $result); + } + +/** + * test accepts() on the component + * + * @return void + */ + public function testAccepts() { + $_SERVER['HTTP_ACCEPT'] = 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5'; + $this->assertTrue($this->RequestHandler->accepts(array('js', 'xml', 'html'))); + $this->assertFalse($this->RequestHandler->accepts(array('gif', 'jpeg', 'foo'))); + + $_SERVER['HTTP_ACCEPT'] = '*/*;q=0.5'; + $this->assertFalse($this->RequestHandler->accepts('rss')); + } + +/** + * test accepts and prefers methods. + * + * @return void + */ + public function testPrefers() { + $_SERVER['HTTP_ACCEPT'] = 'text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,*/*'; + $this->assertNotEquals('rss', $this->RequestHandler->prefers()); + $this->RequestHandler->ext = 'rss'; + $this->assertEquals('rss', $this->RequestHandler->prefers()); + $this->assertFalse($this->RequestHandler->prefers('xml')); + $this->assertEquals('xml', $this->RequestHandler->prefers(array('js', 'xml', 'xhtml'))); + $this->assertFalse($this->RequestHandler->prefers(array('red', 'blue'))); + $this->assertEquals('xhtml', $this->RequestHandler->prefers(array('js', 'json', 'xhtml'))); + $this->assertTrue($this->RequestHandler->prefers(array('rss')), 'Should return true if input matches ext.'); + $this->assertFalse($this->RequestHandler->prefers(array('html')), 'No match with ext, return false.'); + + $_SERVER['HTTP_ACCEPT'] = 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5'; + $this->_init(); + $this->assertEquals('xml', $this->RequestHandler->prefers()); + + $_SERVER['HTTP_ACCEPT'] = '*/*;q=0.5'; + $this->assertEquals('html', $this->RequestHandler->prefers()); + $this->assertFalse($this->RequestHandler->prefers('rss')); + } + +/** + * testCustomContent method + * + * @return void + */ + public function testCustomContent() { + $_SERVER['HTTP_ACCEPT'] = 'text/x-mobile,text/html;q=0.9,text/plain;q=0.8,*/*;q=0.5'; + $this->RequestHandler->setContent('mobile', 'text/x-mobile'); + $this->RequestHandler->startup($this->Controller); + $this->assertEquals('mobile', $this->RequestHandler->prefers()); + } + +/** + * testClientProperties method + * + * @return void + */ + public function testClientProperties() { + $request = $this->getMock('CakeRequest'); + $request->expects($this->once())->method('referer'); + $request->expects($this->once())->method('clientIp')->will($this->returnValue(false)); + + $this->RequestHandler->request = $request; + + $this->RequestHandler->getReferer(); + $this->RequestHandler->getClientIP(false); + } + +/** + * test that ajax requests involving redirects trigger requestAction instead. + * + * @return void + */ + public function testAjaxRedirectAsRequestAction() { + App::build(array( + 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS) + ), App::RESET); + + $this->Controller->RequestHandler = $this->getMock('RequestHandlerComponent', array('_stop'), array(&$this->Controller->Components)); + $this->Controller->request = $this->getMock('CakeRequest'); + $this->Controller->response = $this->getMock('CakeResponse', array('_sendHeader')); + $this->Controller->RequestHandler->request = $this->Controller->request; + $this->Controller->RequestHandler->response = $this->Controller->response; + $this->Controller->request->expects($this->any())->method('is')->will($this->returnValue(true)); + $this->Controller->RequestHandler->expects($this->once())->method('_stop'); + + ob_start(); + $this->Controller->RequestHandler->beforeRedirect( + $this->Controller, array('controller' => 'request_handler_test', 'action' => 'destination') + ); + $result = ob_get_clean(); + $this->assertRegExp('/posts index/', $result, 'RequestAction redirect failed.'); + + App::build(); + } + +/** + * test that ajax requests involving redirects don't force no layout + * this would cause the ajax layout to not be rendered. + * + * @return void + */ + public function testAjaxRedirectAsRequestActionStillRenderingLayout() { + App::build(array( + 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS) + ), App::RESET); + + $this->Controller->RequestHandler = $this->getMock('RequestHandlerComponent', array('_stop'), array(&$this->Controller->Components)); + $this->Controller->request = $this->getMock('CakeRequest'); + $this->Controller->response = $this->getMock('CakeResponse', array('_sendHeader')); + $this->Controller->RequestHandler->request = $this->Controller->request; + $this->Controller->RequestHandler->response = $this->Controller->response; + $this->Controller->request->expects($this->any())->method('is')->will($this->returnValue(true)); + $this->Controller->RequestHandler->expects($this->once())->method('_stop'); + + ob_start(); + $this->Controller->RequestHandler->beforeRedirect( + $this->Controller, array('controller' => 'request_handler_test', 'action' => 'ajax2_layout') + ); + $result = ob_get_clean(); + $this->assertRegExp('/posts index/', $result, 'RequestAction redirect failed.'); + $this->assertRegExp('/Ajax!/', $result, 'Layout was not rendered.'); + + App::build(); + } + +/** + * test that the beforeRedirect callback properly converts + * array urls into their correct string ones, and adds base => false so + * the correct urls are generated. + * + * @link http://cakephp.lighthouseapp.com/projects/42648-cakephp-1x/tickets/276 + * @return void + */ + public function testBeforeRedirectCallbackWithArrayUrl() { + $_SERVER['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest'; + + Router::setRequestInfo(array( + array('plugin' => null, 'controller' => 'accounts', 'action' => 'index', 'pass' => array(), 'named' => array(), 'form' => array(), 'url' => array('url' => 'accounts/')), + array('base' => '/officespace', 'here' => '/officespace/accounts/', 'webroot' => '/officespace/') + )); + + $RequestHandler = $this->getMock('RequestHandlerComponent', array('_stop'), array(&$this->Controller->Components)); + $RequestHandler->response = $this->getMock('CakeResponse', array('_sendHeader')); + $RequestHandler->request = new CakeRequest('posts/index'); + $RequestHandler->response = $this->getMock('CakeResponse', array('_sendHeader')); + + ob_start(); + $RequestHandler->beforeRedirect( + $this->Controller, + array('controller' => 'request_handler_test', 'action' => 'param_method', 'first', 'second') + ); + $result = ob_get_clean(); + $this->assertEquals('one: first two: second', $result); + } + +/** + * assure that beforeRedirect with a status code will correctly set the status header + * + * @return void + */ + public function testBeforeRedirectCallingHeader() { + $_SERVER['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest'; + + $controller = $this->getMock('Controller', array('header')); + $RequestHandler = $this->getMock('RequestHandlerComponent', array('_stop'), array(&$this->Controller->Components)); + $RequestHandler->response = $this->getMock('CakeResponse', array('_sendHeader','statusCode')); + $RequestHandler->request = $this->getMock('CakeRequest'); + $RequestHandler->request->expects($this->once())->method('is') + ->with('ajax') + ->will($this->returnValue(true)); + + $RequestHandler->response->expects($this->once())->method('statusCode')->with(403); + + ob_start(); + $RequestHandler->beforeRedirect($controller, 'request_handler_test/param_method/first/second', 403); + $result = ob_get_clean(); + } + +/** + * @expectedException CakeException + * @return void + */ + public function testAddInputTypeException() { + $this->RequestHandler->addInputType('csv', array('I am not callable')); + } + +/** + * Test checkNotModified method + * + * @return void + **/ + public function testCheckNotModifiedByEtagStar() { + $_SERVER['HTTP_IF_NONE_MATCH'] = '*'; + $RequestHandler = $this->getMock('RequestHandlerComponent', array('_stop'), array(&$this->Controller->Components)); + $RequestHandler->response = $this->getMock('CakeResponse', array('notModified')); + $RequestHandler->response->etag('something'); + $RequestHandler->response->expects($this->once())->method('notModified'); + $this->assertFalse($RequestHandler->beforeRender($this->Controller)); + } + +/** + * Test checkNotModified method + * + * @return void + **/ + public function testCheckNotModifiedByEtagExact() { + $_SERVER['HTTP_IF_NONE_MATCH'] = 'W/"something", "other"'; + $RequestHandler = $this->getMock('RequestHandlerComponent', array('_stop'), array(&$this->Controller->Components)); + $RequestHandler->response = $this->getMock('CakeResponse', array('notModified')); + $RequestHandler->response->etag('something', true); + $RequestHandler->response->expects($this->once())->method('notModified'); + $this->assertFalse($RequestHandler->beforeRender($this->Controller)); + } + +/** + * Test checkNotModified method + * + * @return void + **/ + public function testCheckNotModifiedByEtagAndTime() { + $_SERVER['HTTP_IF_NONE_MATCH'] = 'W/"something", "other"'; + $_SERVER['HTTP_IF_MODIFIED_SINCE'] = '2012-01-01 00:00:00'; + $RequestHandler = $this->getMock('RequestHandlerComponent', array('_stop'), array(&$this->Controller->Components)); + $RequestHandler->response = $this->getMock('CakeResponse', array('notModified')); + $RequestHandler->response->etag('something', true); + $RequestHandler->response->modified('2012-01-01 00:00:00'); + $RequestHandler->response->expects($this->once())->method('notModified'); + $this->assertFalse($RequestHandler->beforeRender($this->Controller)); + } + +/** + * Test checkNotModified method + * + * @return void + **/ + public function testCheckNotModifiedNoInfo() { + $RequestHandler = $this->getMock('RequestHandlerComponent', array('_stop'), array(&$this->Controller->Components)); + $RequestHandler->response = $this->getMock('CakeResponse', array('notModified')); + $RequestHandler->response->expects($this->never())->method('notModified'); + $this->assertNull($RequestHandler->beforeRender($this->Controller)); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/SecurityComponentTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/SecurityComponentTest.php new file mode 100644 index 0000000..84f7803 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/SecurityComponentTest.php @@ -0,0 +1,1375 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Controller.Component + * @since CakePHP(tm) v 1.2.0.5435 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ + +App::uses('SecurityComponent', 'Controller/Component'); +App::uses('Controller', 'Controller'); + +/** + * TestSecurityComponent + * + * @package Cake.Test.Case.Controller.Component + */ +class TestSecurityComponent extends SecurityComponent { + +/** + * validatePost method + * + * @param Controller $controller + * @return boolean + */ + public function validatePost(Controller $controller) { + return $this->_validatePost($controller); + } + +} + +/** + * SecurityTestController + * + * @package Cake.Test.Case.Controller.Component + */ +class SecurityTestController extends Controller { + +/** + * name property + * + * @var string 'SecurityTest' + */ + public $name = 'SecurityTest'; + +/** + * components property + * + * @var array + */ + public $components = array('Session', 'TestSecurity'); + +/** + * failed property + * + * @var boolean false + */ + public $failed = false; + +/** + * Used for keeping track of headers in test + * + * @var array + */ + public $testHeaders = array(); + +/** + * fail method + * + * @return void + */ + public function fail() { + $this->failed = true; + } + +/** + * redirect method + * + * @param string|array $url + * @param mixed $code + * @param mixed $exit + * @return void + */ + public function redirect($url, $status = null, $exit = true) { + return $status; + } + +/** + * Convenience method for header() + * + * @param string $status + * @return void + */ + public function header($status) { + $this->testHeaders[] = $status; + } + +} + +class BrokenCallbackController extends Controller { + + public $name = 'UncallableCallback'; + + public $components = array('Session', 'TestSecurity'); + + public function index() { + } + + protected function _fail() { + } + +} + +/** + * SecurityComponentTest class + * + * @package Cake.Test.Case.Controller.Component + */ +class SecurityComponentTest extends CakeTestCase { + +/** + * Controller property + * + * @var SecurityTestController + */ + public $Controller; + +/** + * oldSalt property + * + * @var string + */ + public $oldSalt; + +/** + * setUp method + * + * @return void + */ + public function setUp() { + parent::setUp(); + + $request = new CakeRequest('posts/index', false); + $request->addParams(array('controller' => 'posts', 'action' => 'index')); + $this->Controller = new SecurityTestController($request); + $this->Controller->Components->init($this->Controller); + $this->Controller->Security = $this->Controller->TestSecurity; + $this->Controller->Security->blackHoleCallback = 'fail'; + $this->Security = $this->Controller->Security; + $this->Security->csrfCheck = false; + + Configure::write('Security.salt', 'foo!'); + } + +/** + * Tear-down method. Resets environment state. + * + * @return void + */ + public function tearDown() { + parent::tearDown(); + $this->Controller->Session->delete('_Token'); + unset($this->Controller->Security); + unset($this->Controller->Component); + unset($this->Controller); + } + +/** + * Test that requests are still blackholed when controller has incorrect + * visibility keyword in the blackhole callback + * + * @expectedException BadRequestException + */ + public function testBlackholeWithBrokenCallback() { + $request = new CakeRequest('posts/index', false); + $request->addParams(array( + 'controller' => 'posts', 'action' => 'index') + ); + $this->Controller = new BrokenCallbackController($request); + $this->Controller->Components->init($this->Controller); + $this->Controller->Security = $this->Controller->TestSecurity; + $this->Controller->Security->blackHoleCallback = '_fail'; + $this->Controller->Security->startup($this->Controller); + $this->Controller->Security->blackHole($this->Controller, 'csrf'); + } + +/** + * test that initialize can set properties. + * + * @return void + */ + public function testConstructorSettingProperties() { + $settings = array( + 'requirePost' => array('edit', 'update'), + 'requireSecure' => array('update_account'), + 'requireGet' => array('index'), + 'validatePost' => false, + ); + $Security = new SecurityComponent($this->Controller->Components, $settings); + $this->Controller->Security->initialize($this->Controller, $settings); + $this->assertEquals($Security->requirePost, $settings['requirePost']); + $this->assertEquals($Security->requireSecure, $settings['requireSecure']); + $this->assertEquals($Security->requireGet, $settings['requireGet']); + $this->assertEquals($Security->validatePost, $settings['validatePost']); + } + +/** + * testStartup method + * + * @return void + */ + public function testStartup() { + $this->Controller->Security->startup($this->Controller); + $result = $this->Controller->params['_Token']['key']; + $this->assertNotNull($result); + $this->assertTrue($this->Controller->Session->check('_Token')); + } + +/** + * testRequirePostFail method + * + * @return void + */ + public function testRequirePostFail() { + $_SERVER['REQUEST_METHOD'] = 'GET'; + $this->Controller->request['action'] = 'posted'; + $this->Controller->Security->requirePost(array('posted')); + $this->Controller->Security->startup($this->Controller); + $this->assertTrue($this->Controller->failed); + } + +/** + * testRequirePostSucceed method + * + * @return void + */ + public function testRequirePostSucceed() { + $_SERVER['REQUEST_METHOD'] = 'POST'; + $this->Controller->request['action'] = 'posted'; + $this->Controller->Security->requirePost('posted'); + $this->Security->startup($this->Controller); + $this->assertFalse($this->Controller->failed); + } + +/** + * testRequireSecureFail method + * + * @return void + */ + public function testRequireSecureFail() { + $_SERVER['HTTPS'] = 'off'; + $_SERVER['REQUEST_METHOD'] = 'POST'; + $this->Controller->request['action'] = 'posted'; + $this->Controller->Security->requireSecure(array('posted')); + $this->Controller->Security->startup($this->Controller); + $this->assertTrue($this->Controller->failed); + } + +/** + * testRequireSecureSucceed method + * + * @return void + */ + public function testRequireSecureSucceed() { + $_SERVER['REQUEST_METHOD'] = 'Secure'; + $this->Controller->request['action'] = 'posted'; + $_SERVER['HTTPS'] = 'on'; + $this->Controller->Security->requireSecure('posted'); + $this->Controller->Security->startup($this->Controller); + $this->assertFalse($this->Controller->failed); + } + +/** + * testRequireAuthFail method + * + * @return void + */ + public function testRequireAuthFail() { + $_SERVER['REQUEST_METHOD'] = 'AUTH'; + $this->Controller->request['action'] = 'posted'; + $this->Controller->request->data = array('username' => 'willy', 'password' => 'somePass'); + $this->Controller->Security->requireAuth(array('posted')); + $this->Controller->Security->startup($this->Controller); + $this->assertTrue($this->Controller->failed); + + $this->Controller->Session->write('_Token', array('allowedControllers' => array())); + $this->Controller->request->data = array('username' => 'willy', 'password' => 'somePass'); + $this->Controller->request['action'] = 'posted'; + $this->Controller->Security->requireAuth('posted'); + $this->Controller->Security->startup($this->Controller); + $this->assertTrue($this->Controller->failed); + + $this->Controller->Session->write('_Token', array( + 'allowedControllers' => array('SecurityTest'), 'allowedActions' => array('posted2') + )); + $this->Controller->request->data = array('username' => 'willy', 'password' => 'somePass'); + $this->Controller->request['action'] = 'posted'; + $this->Controller->Security->requireAuth('posted'); + $this->Controller->Security->startup($this->Controller); + $this->assertTrue($this->Controller->failed); + } + +/** + * testRequireAuthSucceed method + * + * @return void + */ + public function testRequireAuthSucceed() { + $_SERVER['REQUEST_METHOD'] = 'AUTH'; + $this->Controller->request['action'] = 'posted'; + $this->Controller->Security->requireAuth('posted'); + $this->Controller->Security->startup($this->Controller); + $this->assertFalse($this->Controller->failed); + + $this->Controller->Security->Session->write('_Token', array( + 'allowedControllers' => array('SecurityTest'), 'allowedActions' => array('posted') + )); + $this->Controller->request['controller'] = 'SecurityTest'; + $this->Controller->request['action'] = 'posted'; + + $this->Controller->request->data = array( + 'username' => 'willy', 'password' => 'somePass', '_Token' => '' + ); + $this->Controller->action = 'posted'; + $this->Controller->Security->requireAuth('posted'); + $this->Controller->Security->startup($this->Controller); + $this->assertFalse($this->Controller->failed); + } + +/** + * testRequirePostSucceedWrongMethod method + * + * @return void + */ + public function testRequirePostSucceedWrongMethod() { + $_SERVER['REQUEST_METHOD'] = 'GET'; + $this->Controller->request['action'] = 'getted'; + $this->Controller->Security->requirePost('posted'); + $this->Controller->Security->startup($this->Controller); + $this->assertFalse($this->Controller->failed); + } + +/** + * testRequireGetFail method + * + * @return void + */ + public function testRequireGetFail() { + $_SERVER['REQUEST_METHOD'] = 'POST'; + $this->Controller->request['action'] = 'getted'; + $this->Controller->Security->requireGet(array('getted')); + $this->Controller->Security->startup($this->Controller); + $this->assertTrue($this->Controller->failed); + } + +/** + * testRequireGetSucceed method + * + * @return void + */ + public function testRequireGetSucceed() { + $_SERVER['REQUEST_METHOD'] = 'GET'; + $this->Controller->request['action'] = 'getted'; + $this->Controller->Security->requireGet('getted'); + $this->Controller->Security->startup($this->Controller); + $this->assertFalse($this->Controller->failed); + } + +/** + * testRequireGetSucceedWrongMethod method + * + * @return void + */ + public function testRequireGetSucceedWrongMethod() { + $_SERVER['REQUEST_METHOD'] = 'POST'; + $this->Controller->request['action'] = 'posted'; + $this->Security->requireGet('getted'); + $this->Security->startup($this->Controller); + $this->assertFalse($this->Controller->failed); + } + +/** + * testRequirePutFail method + * + * @return void + */ + public function testRequirePutFail() { + $_SERVER['REQUEST_METHOD'] = 'POST'; + $this->Controller->request['action'] = 'putted'; + $this->Controller->Security->requirePut(array('putted')); + $this->Controller->Security->startup($this->Controller); + $this->assertTrue($this->Controller->failed); + } + +/** + * testRequirePutSucceed method + * + * @return void + */ + public function testRequirePutSucceed() { + $_SERVER['REQUEST_METHOD'] = 'PUT'; + $this->Controller->request['action'] = 'putted'; + $this->Controller->Security->requirePut('putted'); + $this->Controller->Security->startup($this->Controller); + $this->assertFalse($this->Controller->failed); + } + +/** + * testRequirePutSucceedWrongMethod method + * + * @return void + */ + public function testRequirePutSucceedWrongMethod() { + $_SERVER['REQUEST_METHOD'] = 'POST'; + $this->Controller->request['action'] = 'posted'; + $this->Controller->Security->requirePut('putted'); + $this->Controller->Security->startup($this->Controller); + $this->assertFalse($this->Controller->failed); + } + +/** + * testRequireDeleteFail method + * + * @return void + */ + public function testRequireDeleteFail() { + $_SERVER['REQUEST_METHOD'] = 'POST'; + $this->Controller->request['action'] = 'deleted'; + $this->Controller->Security->requireDelete(array('deleted', 'other_method')); + $this->Controller->Security->startup($this->Controller); + $this->assertTrue($this->Controller->failed); + } + +/** + * testRequireDeleteSucceed method + * + * @return void + */ + public function testRequireDeleteSucceed() { + $_SERVER['REQUEST_METHOD'] = 'DELETE'; + $this->Controller->request['action'] = 'deleted'; + $this->Controller->Security->requireDelete('deleted'); + $this->Controller->Security->startup($this->Controller); + $this->assertFalse($this->Controller->failed); + } + +/** + * testRequireDeleteSucceedWrongMethod method + * + * @return void + */ + public function testRequireDeleteSucceedWrongMethod() { + $_SERVER['REQUEST_METHOD'] = 'POST'; + $this->Controller->request['action'] = 'posted'; + $this->Controller->Security->requireDelete('deleted'); + $this->Controller->Security->startup($this->Controller); + $this->assertFalse($this->Controller->failed); + } + +/** + * Simple hash validation test + * + * @return void + */ + public function testValidatePost() { + $this->Controller->Security->startup($this->Controller); + + $key = $this->Controller->request->params['_Token']['key']; + $fields = 'a5475372b40f6e3ccbf9f8af191f20e1642fd877%3AModel.valid'; + $unlocked = ''; + + $this->Controller->request->data = array( + 'Model' => array('username' => 'nate', 'password' => 'foo', 'valid' => '0'), + '_Token' => compact('key', 'fields', 'unlocked') + ); + $this->assertTrue($this->Controller->Security->validatePost($this->Controller)); + } + +/** + * Test that validatePost fails if you are missing the session information. + * + * @return void + */ + public function testValidatePostNoSession() { + $this->Controller->Security->startup($this->Controller); + $this->Controller->Session->delete('_Token'); + + $key = $this->Controller->params['_Token']['key']; + $fields = 'a5475372b40f6e3ccbf9f8af191f20e1642fd877%3AModel.valid'; + + $this->Controller->data = array( + 'Model' => array('username' => 'nate', 'password' => 'foo', 'valid' => '0'), + '_Token' => compact('key', 'fields') + ); + $this->assertFalse($this->Controller->Security->validatePost($this->Controller)); + } + +/** + * test that validatePost fails if any of its required fields are missing. + * + * @return void + */ + public function testValidatePostFormHacking() { + $this->Controller->Security->startup($this->Controller); + $key = $this->Controller->params['_Token']['key']; + $unlocked = ''; + + $this->Controller->request->data = array( + 'Model' => array('username' => 'nate', 'password' => 'foo', 'valid' => '0'), + '_Token' => compact('key', 'unlocked') + ); + $result = $this->Controller->Security->validatePost($this->Controller); + $this->assertFalse($result, 'validatePost passed when fields were missing. %s'); + } + +/** + * Test that objects can't be passed into the serialized string. This was a vector for RFI and LFI + * attacks. Thanks to Felix Wilhelm + * + * @return void + */ + public function testValidatePostObjectDeserialize() { + $this->Controller->Security->startup($this->Controller); + $key = $this->Controller->request->params['_Token']['key']; + $fields = 'a5475372b40f6e3ccbf9f8af191f20e1642fd877'; + $unlocked = ''; + + // a corrupted serialized object, so we can see if it ever gets to deserialize + $attack = 'O:3:"App":1:{s:5:"__map";a:1:{s:3:"foo";s:7:"Hacked!";s:1:"fail"}}'; + $fields .= urlencode(':' . str_rot13($attack)); + + $this->Controller->request->data = array( + 'Model' => array('username' => 'mark', 'password' => 'foo', 'valid' => '0'), + '_Token' => compact('key', 'fields', 'unlocked') + ); + $result = $this->Controller->Security->validatePost($this->Controller); + $this->assertFalse($result, 'validatePost passed when key was missing. %s'); + } + +/** + * Tests validation of checkbox arrays + * + * @return void + */ + public function testValidatePostArray() { + $this->Controller->Security->startup($this->Controller); + + $key = $this->Controller->request->params['_Token']['key']; + $fields = 'f7d573650a295b94e0938d32b323fde775e5f32b%3A'; + $unlocked = ''; + + $this->Controller->request->data = array( + 'Model' => array('multi_field' => array('1', '3')), + '_Token' => compact('key', 'fields', 'unlocked') + ); + $this->assertTrue($this->Controller->Security->validatePost($this->Controller)); + } + +/** + * testValidatePostNoModel method + * + * @return void + */ + public function testValidatePostNoModel() { + $this->Controller->Security->startup($this->Controller); + + $key = $this->Controller->request->params['_Token']['key']; + $fields = '540ac9c60d323c22bafe997b72c0790f39a8bdef%3A'; + $unlocked = ''; + + $this->Controller->request->data = array( + 'anything' => 'some_data', + '_Token' => compact('key', 'fields', 'unlocked') + ); + + $result = $this->Controller->Security->validatePost($this->Controller); + $this->assertTrue($result); + } + +/** + * testValidatePostSimple method + * + * @return void + */ + public function testValidatePostSimple() { + $this->Controller->Security->startup($this->Controller); + + $key = $this->Controller->request->params['_Token']['key']; + $fields = '69f493434187b867ea14b901fdf58b55d27c935d%3A'; + $unlocked = ''; + + $this->Controller->request->data = $data = array( + 'Model' => array('username' => '', 'password' => ''), + '_Token' => compact('key', 'fields', 'unlocked') + ); + + $result = $this->Controller->Security->validatePost($this->Controller); + $this->assertTrue($result); + } + +/** + * Tests hash validation for multiple records, including locked fields + * + * @return void + */ + public function testValidatePostComplex() { + $this->Controller->Security->startup($this->Controller); + + $key = $this->Controller->request->params['_Token']['key']; + $fields = 'c9118120e680a7201b543f562e5301006ccfcbe2%3AAddresses.0.id%7CAddresses.1.id'; + $unlocked = ''; + + $this->Controller->request->data = array( + 'Addresses' => array( + '0' => array( + 'id' => '123456', 'title' => '', 'first_name' => '', 'last_name' => '', + 'address' => '', 'city' => '', 'phone' => '', 'primary' => '' + ), + '1' => array( + 'id' => '654321', 'title' => '', 'first_name' => '', 'last_name' => '', + 'address' => '', 'city' => '', 'phone' => '', 'primary' => '' + ) + ), + '_Token' => compact('key', 'fields', 'unlocked') + ); + $result = $this->Controller->Security->validatePost($this->Controller); + $this->assertTrue($result); + } + +/** + * test ValidatePost with multiple select elements. + * + * @return void + */ + public function testValidatePostMultipleSelect() { + $this->Controller->Security->startup($this->Controller); + + $key = $this->Controller->request->params['_Token']['key']; + $fields = '422cde416475abc171568be690a98cad20e66079%3A'; + $unlocked = ''; + + $this->Controller->request->data = array( + 'Tag' => array('Tag' => array(1, 2)), + '_Token' => compact('key', 'fields', 'unlocked'), + ); + $result = $this->Controller->Security->validatePost($this->Controller); + $this->assertTrue($result); + + $this->Controller->request->data = array( + 'Tag' => array('Tag' => array(1, 2, 3)), + '_Token' => compact('key', 'fields', 'unlocked'), + ); + $result = $this->Controller->Security->validatePost($this->Controller); + $this->assertTrue($result); + + $this->Controller->request->data = array( + 'Tag' => array('Tag' => array(1, 2, 3, 4)), + '_Token' => compact('key', 'fields', 'unlocked'), + ); + $result = $this->Controller->Security->validatePost($this->Controller); + $this->assertTrue($result); + + $fields = '19464422eafe977ee729c59222af07f983010c5f%3A'; + $this->Controller->request->data = array( + 'User.password' => 'bar', 'User.name' => 'foo', 'User.is_valid' => '1', + 'Tag' => array('Tag' => array(1)), + '_Token' => compact('key', 'fields', 'unlocked'), + ); + $result = $this->Controller->Security->validatePost($this->Controller); + $this->assertTrue($result); + } + +/** + * testValidatePostCheckbox method + * + * First block tests un-checked checkbox + * Second block tests checked checkbox + * + * @return void + */ + public function testValidatePostCheckbox() { + $this->Controller->Security->startup($this->Controller); + $key = $this->Controller->request->params['_Token']['key']; + $fields = 'a5475372b40f6e3ccbf9f8af191f20e1642fd877%3AModel.valid'; + $unlocked = ''; + + $this->Controller->request->data = array( + 'Model' => array('username' => '', 'password' => '', 'valid' => '0'), + '_Token' => compact('key', 'fields', 'unlocked') + ); + + $result = $this->Controller->Security->validatePost($this->Controller); + $this->assertTrue($result); + + $fields = '874439ca69f89b4c4a5f50fb9c36ff56a28f5d42%3A'; + + $this->Controller->request->data = array( + 'Model' => array('username' => '', 'password' => '', 'valid' => '0'), + '_Token' => compact('key', 'fields', 'unlocked') + ); + + $result = $this->Controller->Security->validatePost($this->Controller); + $this->assertTrue($result); + + $this->Controller->request->data = array(); + $this->Controller->Security->startup($this->Controller); + $key = $this->Controller->request->params['_Token']['key']; + + $this->Controller->request->data = $data = array( + 'Model' => array('username' => '', 'password' => '', 'valid' => '0'), + '_Token' => compact('key', 'fields', 'unlocked') + ); + + $result = $this->Controller->Security->validatePost($this->Controller); + $this->assertTrue($result); + } + +/** + * testValidatePostHidden method + * + * @return void + */ + public function testValidatePostHidden() { + $this->Controller->Security->startup($this->Controller); + $key = $this->Controller->request->params['_Token']['key']; + $fields = '51ccd8cb0997c7b3d4523ecde5a109318405ef8c%3AModel.hidden%7CModel.other_hidden'; + $unlocked = ''; + + $this->Controller->request->data = array( + 'Model' => array( + 'username' => '', 'password' => '', 'hidden' => '0', + 'other_hidden' => 'some hidden value' + ), + '_Token' => compact('key', 'fields', 'unlocked') + ); + $result = $this->Controller->Security->validatePost($this->Controller); + $this->assertTrue($result); + } + +/** + * testValidatePostWithDisabledFields method + * + * @return void + */ + public function testValidatePostWithDisabledFields() { + $this->Controller->Security->disabledFields = array('Model.username', 'Model.password'); + $this->Controller->Security->startup($this->Controller); + $key = $this->Controller->request->params['_Token']['key']; + $fields = 'ef1082968c449397bcd849f963636864383278b1%3AModel.hidden'; + $unlocked = ''; + + $this->Controller->request->data = array( + 'Model' => array( + 'username' => '', 'password' => '', 'hidden' => '0' + ), + '_Token' => compact('fields', 'key', 'unlocked') + ); + + $result = $this->Controller->Security->validatePost($this->Controller); + $this->assertTrue($result); + } + +/** + * test validating post data with posted unlocked fields. + * + * @return void + */ + public function testValidatePostDisabledFieldsInData() { + $this->Controller->Security->startup($this->Controller); + $key = $this->Controller->request->params['_Token']['key']; + $unlocked = 'Model.username'; + $fields = array('Model.hidden', 'Model.password'); + $fields = urlencode(Security::hash(serialize($fields) . $unlocked . Configure::read('Security.salt'))); + + $this->Controller->request->data = array( + 'Model' => array( + 'username' => 'mark', + 'password' => 'sekret', + 'hidden' => '0' + ), + '_Token' => compact('fields', 'key', 'unlocked') + ); + + $result = $this->Controller->Security->validatePost($this->Controller); + $this->assertTrue($result); + } + +/** + * test that missing 'unlocked' input causes failure + * + * @return void + */ + public function testValidatePostFailNoDisabled() { + $this->Controller->Security->startup($this->Controller); + $key = $this->Controller->request->params['_Token']['key']; + $fields = array('Model.hidden', 'Model.password', 'Model.username'); + $fields = urlencode(Security::hash(serialize($fields) . Configure::read('Security.salt'))); + + $this->Controller->request->data = array( + 'Model' => array( + 'username' => 'mark', + 'password' => 'sekret', + 'hidden' => '0' + ), + '_Token' => compact('fields', 'key') + ); + + $result = $this->Controller->Security->validatePost($this->Controller); + $this->assertFalse($result); + } + +/** + * Test that validatePost fails when unlocked fields are changed. + * + * @return + */ + public function testValidatePostFailDisabledFieldTampering() { + $this->Controller->Security->startup($this->Controller); + $key = $this->Controller->request->params['_Token']['key']; + $unlocked = 'Model.username'; + $fields = array('Model.hidden', 'Model.password'); + $fields = urlencode(Security::hash(serialize($fields) . $unlocked . Configure::read('Security.salt'))); + + // Tamper the values. + $unlocked = 'Model.username|Model.password'; + + $this->Controller->request->data = array( + 'Model' => array( + 'username' => 'mark', + 'password' => 'sekret', + 'hidden' => '0' + ), + '_Token' => compact('fields', 'key', 'unlocked') + ); + + $result = $this->Controller->Security->validatePost($this->Controller); + $this->assertFalse($result); + } + +/** + * testValidateHiddenMultipleModel method + * + * @return void + */ + public function testValidateHiddenMultipleModel() { + $this->Controller->Security->startup($this->Controller); + $key = $this->Controller->request->params['_Token']['key']; + $fields = 'a2d01072dc4660eea9d15007025f35a7a5b58e18%3AModel.valid%7CModel2.valid%7CModel3.valid'; + $unlocked = ''; + + $this->Controller->request->data = array( + 'Model' => array('username' => '', 'password' => '', 'valid' => '0'), + 'Model2' => array('valid' => '0'), + 'Model3' => array('valid' => '0'), + '_Token' => compact('key', 'fields', 'unlocked') + ); + $result = $this->Controller->Security->validatePost($this->Controller); + $this->assertTrue($result); + } + +/** + * testValidateHasManyModel method + * + * @return void + */ + public function testValidateHasManyModel() { + $this->Controller->Security->startup($this->Controller); + $key = $this->Controller->request->params['_Token']['key']; + $fields = '51e3b55a6edd82020b3f29c9ae200e14bbeb7ee5%3AModel.0.hidden%7CModel.0.valid'; + $fields .= '%7CModel.1.hidden%7CModel.1.valid'; + $unlocked = ''; + + $this->Controller->request->data = array( + 'Model' => array( + array( + 'username' => 'username', 'password' => 'password', + 'hidden' => 'value', 'valid' => '0' + ), + array( + 'username' => 'username', 'password' => 'password', + 'hidden' => 'value', 'valid' => '0' + ) + ), + '_Token' => compact('key', 'fields', 'unlocked') + ); + + $result = $this->Controller->Security->validatePost($this->Controller); + $this->assertTrue($result); + } + +/** + * testValidateHasManyRecordsPass method + * + * @return void + */ + public function testValidateHasManyRecordsPass() { + $this->Controller->Security->startup($this->Controller); + $key = $this->Controller->request->params['_Token']['key']; + $fields = '7a203edb3d345bbf38fe0dccae960da8842e11d7%3AAddress.0.id%7CAddress.0.primary%7C'; + $fields .= 'Address.1.id%7CAddress.1.primary'; + $unlocked = ''; + + $this->Controller->request->data = array( + 'Address' => array( + 0 => array( + 'id' => '123', + 'title' => 'home', + 'first_name' => 'Bilbo', + 'last_name' => 'Baggins', + 'address' => '23 Bag end way', + 'city' => 'the shire', + 'phone' => 'N/A', + 'primary' => '1', + ), + 1 => array( + 'id' => '124', + 'title' => 'home', + 'first_name' => 'Frodo', + 'last_name' => 'Baggins', + 'address' => '50 Bag end way', + 'city' => 'the shire', + 'phone' => 'N/A', + 'primary' => '1' + ) + ), + '_Token' => compact('key', 'fields', 'unlocked') + ); + + $result = $this->Controller->Security->validatePost($this->Controller); + $this->assertTrue($result); + } + +/** + * Test that values like Foo.0.1 + * + * @return void + */ + public function testValidateNestedNumericSets() { + $this->Controller->Security->startup($this->Controller); + $key = $this->Controller->request->params['_Token']['key']; + $unlocked = ''; + $hashFields = array('TaxonomyData'); + $fields = urlencode(Security::hash(serialize($hashFields) . $unlocked . Configure::read('Security.salt'))); + + $this->Controller->request->data = array( + 'TaxonomyData' => array( + 1 => array(array(2)), + 2 => array(array(3)) + ), + '_Token' => compact('key', 'fields', 'unlocked') + ); + $result = $this->Controller->Security->validatePost($this->Controller); + $this->assertTrue($result); + } + +/** + * testValidateHasManyRecords method + * + * validatePost should fail, hidden fields have been changed. + * + * @return void + */ + public function testValidateHasManyRecordsFail() { + $this->Controller->Security->startup($this->Controller); + $key = $this->Controller->request->params['_Token']['key']; + $fields = '7a203edb3d345bbf38fe0dccae960da8842e11d7%3AAddress.0.id%7CAddress.0.primary%7C'; + $fields .= 'Address.1.id%7CAddress.1.primary'; + $unlocked = ''; + + $this->Controller->request->data = array( + 'Address' => array( + 0 => array( + 'id' => '123', + 'title' => 'home', + 'first_name' => 'Bilbo', + 'last_name' => 'Baggins', + 'address' => '23 Bag end way', + 'city' => 'the shire', + 'phone' => 'N/A', + 'primary' => '5', + ), + 1 => array( + 'id' => '124', + 'title' => 'home', + 'first_name' => 'Frodo', + 'last_name' => 'Baggins', + 'address' => '50 Bag end way', + 'city' => 'the shire', + 'phone' => 'N/A', + 'primary' => '1' + ) + ), + '_Token' => compact('key', 'fields', 'unlocked') + ); + + $result = $this->Controller->Security->validatePost($this->Controller); + $this->assertFalse($result); + } + +/** + * testFormDisabledFields method + * + * @return void + */ + public function testFormDisabledFields() { + $this->Controller->Security->startup($this->Controller); + $key = $this->Controller->request->params['_Token']['key']; + $fields = '11842060341b9d0fc3808b90ba29fdea7054d6ad%3An%3A0%3A%7B%7D'; + $unlocked = ''; + + $this->Controller->request->data = array( + 'MyModel' => array('name' => 'some data'), + '_Token' => compact('key', 'fields', 'unlocked') + ); + $result = $this->Controller->Security->validatePost($this->Controller); + $this->assertFalse($result); + + $this->Controller->Security->startup($this->Controller); + $this->Controller->Security->disabledFields = array('MyModel.name'); + $key = $this->Controller->request->params['_Token']['key']; + + $this->Controller->request->data = array( + 'MyModel' => array('name' => 'some data'), + '_Token' => compact('key', 'fields', 'unlocked') + ); + + $result = $this->Controller->Security->validatePost($this->Controller); + $this->assertTrue($result); + } + +/** + * testRadio method + * + * @return void + */ + public function testRadio() { + $this->Controller->Security->startup($this->Controller); + $key = $this->Controller->request->params['_Token']['key']; + $fields = '575ef54ca4fc8cab468d6d898e9acd3a9671c17e%3An%3A0%3A%7B%7D'; + $unlocked = ''; + + $this->Controller->request->data = array( + '_Token' => compact('key', 'fields', 'unlocked') + ); + $result = $this->Controller->Security->validatePost($this->Controller); + $this->assertFalse($result); + + $this->Controller->request->data = array( + '_Token' => compact('key', 'fields', 'unlocked'), + 'Test' => array('test' => '') + ); + $result = $this->Controller->Security->validatePost($this->Controller); + $this->assertTrue($result); + + $this->Controller->request->data = array( + '_Token' => compact('key', 'fields', 'unlocked'), + 'Test' => array('test' => '1') + ); + $result = $this->Controller->Security->validatePost($this->Controller); + $this->assertTrue($result); + + $this->Controller->request->data = array( + '_Token' => compact('key', 'fields', 'unlocked'), + 'Test' => array('test' => '2') + ); + $result = $this->Controller->Security->validatePost($this->Controller); + $this->assertTrue($result); + } + +/** + * test that a requestAction's controller will have the _Token appended to + * the params. + * + * @return void + * @see http://cakephp.lighthouseapp.com/projects/42648/tickets/68 + */ + public function testSettingTokenForRequestAction() { + $this->Controller->Security->startup($this->Controller); + $key = $this->Controller->request->params['_Token']['key']; + + $this->Controller->params['requested'] = 1; + unset($this->Controller->request->params['_Token']); + + $this->Controller->Security->startup($this->Controller); + $this->assertEquals($this->Controller->request->params['_Token']['key'], $key); + } + +/** + * test that blackhole doesn't delete the _Token session key so repeat data submissions + * stay blackholed. + * + * @link http://cakephp.lighthouseapp.com/projects/42648/tickets/214 + * @return void + */ + public function testBlackHoleNotDeletingSessionInformation() { + $this->Controller->Security->startup($this->Controller); + + $this->Controller->Security->blackHole($this->Controller, 'auth'); + $this->assertTrue($this->Controller->Security->Session->check('_Token'), '_Token was deleted by blackHole %s'); + } + +/** + * test that csrf checks are skipped for request action. + * + * @return void + */ + public function testCsrfSkipRequestAction() { + $_SERVER['REQUEST_METHOD'] = 'POST'; + + $this->Security->validatePost = false; + $this->Security->csrfCheck = true; + $this->Security->csrfExpires = '+10 minutes'; + $this->Controller->request->params['requested'] = 1; + $this->Security->startup($this->Controller); + + $this->assertFalse($this->Controller->failed, 'fail() was called.'); + } + +/** + * test setting + * + * @return void + */ + public function testCsrfSettings() { + $this->Security->validatePost = false; + $this->Security->csrfCheck = true; + $this->Security->csrfExpires = '+10 minutes'; + $this->Security->startup($this->Controller); + + $token = $this->Security->Session->read('_Token'); + $this->assertEquals(1, count($token['csrfTokens']), 'Missing the csrf token.'); + $this->assertEquals(strtotime('+10 minutes'), current($token['csrfTokens']), 'Token expiry does not match'); + $this->assertEquals(array('key', 'unlockedFields'), array_keys($this->Controller->request->params['_Token']), 'Keys don not match'); + } + +/** + * Test setting multiple nonces, when startup() is called more than once, (ie more than one request.) + * + * @return void + */ + public function testCsrfSettingMultipleNonces() { + $this->Security->validatePost = false; + $this->Security->csrfCheck = true; + $this->Security->csrfExpires = '+10 minutes'; + $csrfExpires = strtotime('+10 minutes'); + $this->Security->startup($this->Controller); + $this->Security->startup($this->Controller); + + $token = $this->Security->Session->read('_Token'); + $this->assertEquals(2, count($token['csrfTokens']), 'Missing the csrf token.'); + foreach ($token['csrfTokens'] as $key => $expires) { + $diff = $csrfExpires - $expires; + $this->assertTrue($diff === 0 || $diff === 1, 'Token expiry does not match'); + } + } + +/** + * test that nonces are consumed by form submits. + * + * @return void + */ + public function testCsrfNonceConsumption() { + $this->Security->validatePost = false; + $this->Security->csrfCheck = true; + $this->Security->csrfExpires = '+10 minutes'; + + $this->Security->Session->write('_Token.csrfTokens', array('nonce1' => strtotime('+10 minutes'))); + + $this->Controller->request = $this->getMock('CakeRequest', array('is')); + $this->Controller->request->expects($this->once())->method('is') + ->with('post') + ->will($this->returnValue(true)); + + $this->Controller->request->params['action'] = 'index'; + $this->Controller->request->data = array( + '_Token' => array( + 'key' => 'nonce1' + ), + 'Post' => array( + 'title' => 'Woot' + ) + ); + $this->Security->startup($this->Controller); + $token = $this->Security->Session->read('_Token'); + $this->assertFalse(isset($token['csrfTokens']['nonce1']), 'Token was not consumed'); + } + +/** + * test that expired values in the csrfTokens are cleaned up. + * + * @return void + */ + public function testCsrfNonceVacuum() { + $this->Security->validatePost = false; + $this->Security->csrfCheck = true; + $this->Security->csrfExpires = '+10 minutes'; + + $this->Security->Session->write('_Token.csrfTokens', array( + 'valid' => strtotime('+30 minutes'), + 'poof' => strtotime('-11 minutes'), + 'dust' => strtotime('-20 minutes') + )); + $this->Security->startup($this->Controller); + $tokens = $this->Security->Session->read('_Token.csrfTokens'); + $this->assertEquals(2, count($tokens), 'Too many tokens left behind'); + $this->assertNotEmpty('valid', $tokens, 'Valid token was removed.'); + } + +/** + * test that when the key is missing the request is blackHoled + * + * @return void + */ + public function testCsrfBlackHoleOnKeyMismatch() { + $this->Security->validatePost = false; + $this->Security->csrfCheck = true; + $this->Security->csrfExpires = '+10 minutes'; + + $this->Security->Session->write('_Token.csrfTokens', array('nonce1' => strtotime('+10 minutes'))); + + $this->Controller->request = $this->getMock('CakeRequest', array('is')); + $this->Controller->request->expects($this->once())->method('is') + ->with('post') + ->will($this->returnValue(true)); + + $this->Controller->request->params['action'] = 'index'; + $this->Controller->request->data = array( + '_Token' => array( + 'key' => 'not the right value' + ), + 'Post' => array( + 'title' => 'Woot' + ) + ); + $this->Security->startup($this->Controller); + $this->assertTrue($this->Controller->failed, 'fail() was not called.'); + } + +/** + * test that when the key is missing the request is blackHoled + * + * @return void + */ + public function testCsrfBlackHoleOnExpiredKey() { + $this->Security->validatePost = false; + $this->Security->csrfCheck = true; + $this->Security->csrfExpires = '+10 minutes'; + + $this->Security->Session->write('_Token.csrfTokens', array('nonce1' => strtotime('-5 minutes'))); + + $this->Controller->request = $this->getMock('CakeRequest', array('is')); + $this->Controller->request->expects($this->once())->method('is') + ->with('post') + ->will($this->returnValue(true)); + + $this->Controller->request->params['action'] = 'index'; + $this->Controller->request->data = array( + '_Token' => array( + 'key' => 'nonce1' + ), + 'Post' => array( + 'title' => 'Woot' + ) + ); + $this->Security->startup($this->Controller); + $this->assertTrue($this->Controller->failed, 'fail() was not called.'); + } + +/** + * test that csrfUseOnce = false works. + * + * @return void + */ + public function testCsrfNotUseOnce() { + $this->Security->validatePost = false; + $this->Security->csrfCheck = true; + $this->Security->csrfUseOnce = false; + $this->Security->csrfExpires = '+10 minutes'; + + // Generate one token + $this->Security->startup($this->Controller); + $token = $this->Security->Session->read('_Token.csrfTokens'); + $this->assertEquals(1, count($token), 'Should only be one token.'); + + $this->Security->startup($this->Controller); + $tokenTwo = $this->Security->Session->read('_Token.csrfTokens'); + $this->assertEquals(1, count($tokenTwo), 'Should only be one token.'); + $this->assertEquals($token, $tokenTwo, 'Tokens should not be different.'); + + $key = $this->Controller->request->params['_Token']['key']; + $this->assertEquals(array($key), array_keys($token), '_Token.key and csrfToken do not match request will blackhole.'); + } + +/** + * ensure that longer session tokens are not consumed + * + * @return void + */ + public function testCsrfNotUseOnceValidationLeavingToken() { + $this->Security->validatePost = false; + $this->Security->csrfCheck = true; + $this->Security->csrfUseOnce = false; + $this->Security->csrfExpires = '+10 minutes'; + + $this->Security->Session->write('_Token.csrfTokens', array('nonce1' => strtotime('+10 minutes'))); + + $this->Controller->request = $this->getMock('CakeRequest', array('is')); + $this->Controller->request->expects($this->once())->method('is') + ->with('post') + ->will($this->returnValue(true)); + + $this->Controller->request->params['action'] = 'index'; + $this->Controller->request->data = array( + '_Token' => array( + 'key' => 'nonce1' + ), + 'Post' => array( + 'title' => 'Woot' + ) + ); + $this->Security->startup($this->Controller); + $token = $this->Security->Session->read('_Token'); + $this->assertTrue(isset($token['csrfTokens']['nonce1']), 'Token was consumed'); + } + +/** + * Test generateToken() + * + * @return void + */ + public function testGenerateToken() { + $request = $this->Controller->request; + $this->Security->generateToken($request); + + $this->assertNotEmpty($request->params['_Token']); + $this->assertTrue(isset($request->params['_Token']['unlockedFields'])); + $this->assertTrue(isset($request->params['_Token']['key'])); + } + +/** + * Test the limiting of CSRF tokens. + * + * @return void + */ + public function testCsrfLimit() { + $this->Security->csrfLimit = 3; + $time = strtotime('+10 minutes'); + $tokens = array( + '1' => $time, + '2' => $time, + '3' => $time, + '4' => $time, + '5' => $time, + ); + $this->Security->Session->write('_Token', array('csrfTokens' => $tokens)); + $this->Security->generateToken($this->Controller->request); + $result = $this->Security->Session->read('_Token.csrfTokens'); + + $this->assertFalse(isset($result['1'])); + $this->assertFalse(isset($result['2'])); + $this->assertFalse(isset($result['3'])); + $this->assertTrue(isset($result['4'])); + $this->assertTrue(isset($result['5'])); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/SessionComponentTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/SessionComponentTest.php new file mode 100644 index 0000000..0920186 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/Component/SessionComponentTest.php @@ -0,0 +1,294 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Controller.Component + * @since CakePHP(tm) v 1.2.0.5436 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ +App::uses('Controller', 'Controller'); +App::uses('SessionComponent', 'Controller/Component'); + +/** + * SessionTestController class + * + * @package Cake.Test.Case.Controller.Component + */ +class SessionTestController extends Controller { + +/** + * uses property + * + * @var array + */ + public $uses = array(); + +/** + * sessionId method + * + * @return string + */ + public function sessionId() { + return $this->Session->id(); + } + +} + +/** + * OrangeSessionTestController class + * + * @package Cake.Test.Case.Controller.Component + */ +class OrangeSessionTestController extends Controller { + +/** + * uses property + * + * @var array + */ + public $uses = array(); + +/** + * sessionId method + * + * @return string + */ + public function sessionId() { + return $this->Session->id(); + } + +} + +/** + * SessionComponentTest class + * + * @package Cake.Test.Case.Controller.Component + */ +class SessionComponentTest extends CakeTestCase { + + protected static $_sessionBackup; + +/** + * fixtures + * + * @var string + */ + public $fixtures = array('core.session'); + +/** + * test case startup + * + * @return void + */ + public static function setupBeforeClass() { + self::$_sessionBackup = Configure::read('Session'); + Configure::write('Session', array( + 'defaults' => 'php', + 'timeout' => 100, + 'cookie' => 'test' + )); + } + +/** + * cleanup after test case. + * + * @return void + */ + public static function teardownAfterClass() { + Configure::write('Session', self::$_sessionBackup); + } + +/** + * setUp method + * + * @return void + */ + public function setUp() { + parent::setUp(); + $_SESSION = null; + $this->ComponentCollection = new ComponentCollection(); + } + +/** + * tearDown method + * + * @return void + */ + public function tearDown() { + parent::tearDown(); + CakeSession::destroy(); + } + +/** + * ensure that session ids don't change when request action is called. + * + * @return void + */ + public function testSessionIdConsistentAcrossRequestAction() { + $Session = new SessionComponent($this->ComponentCollection); + $Session->check('Test'); + $this->assertTrue(isset($_SESSION)); + + $Object = new Object(); + $Session = new SessionComponent($this->ComponentCollection); + $expected = $Session->id(); + + $result = $Object->requestAction('/session_test/sessionId'); + $this->assertEquals($expected, $result); + + $result = $Object->requestAction('/orange_session_test/sessionId'); + $this->assertEquals($expected, $result); + } + +/** + * testSessionValid method + * + * @return void + */ + public function testSessionValid() { + $Session = new SessionComponent($this->ComponentCollection); + + $this->assertTrue($Session->valid()); + + Configure::write('Session.checkAgent', true); + $Session->userAgent('rweerw'); + $this->assertFalse($Session->valid()); + + $Session = new SessionComponent($this->ComponentCollection); + $Session->time = $Session->read('Config.time') + 1; + $this->assertFalse($Session->valid()); + } + +/** + * testSessionError method + * + * @return void + */ + public function testSessionError() { + $Session = new SessionComponent($this->ComponentCollection); + $this->assertFalse($Session->error()); + } + +/** + * testSessionReadWrite method + * + * @return void + */ + public function testSessionReadWrite() { + $Session = new SessionComponent($this->ComponentCollection); + + $this->assertNull($Session->read('Test')); + + $this->assertTrue($Session->write('Test', 'some value')); + $this->assertEquals('some value', $Session->read('Test')); + $Session->delete('Test'); + + $this->assertTrue($Session->write('Test.key.path', 'some value')); + $this->assertEquals('some value', $Session->read('Test.key.path')); + $this->assertEquals(array('path' => 'some value'), $Session->read('Test.key')); + $this->assertTrue($Session->write('Test.key.path2', 'another value')); + $this->assertEquals(array('path' => 'some value', 'path2' => 'another value'), $Session->read('Test.key')); + $Session->delete('Test'); + + $array = array('key1' => 'val1', 'key2' => 'val2', 'key3' => 'val3'); + $this->assertTrue($Session->write('Test', $array)); + $this->assertEquals($Session->read('Test'), $array); + $Session->delete('Test'); + + $this->assertFalse($Session->write(array('Test'), 'some value')); + $this->assertTrue($Session->write(array('Test' => 'some value'))); + $this->assertEquals('some value', $Session->read('Test')); + $Session->delete('Test'); + } + +/** + * testSessionDelete method + * + * @return void + */ + public function testSessionDelete() { + $Session = new SessionComponent($this->ComponentCollection); + + $this->assertFalse($Session->delete('Test')); + + $Session->write('Test', 'some value'); + $this->assertTrue($Session->delete('Test')); + } + +/** + * testSessionCheck method + * + * @return void + */ + public function testSessionCheck() { + $Session = new SessionComponent($this->ComponentCollection); + + $this->assertFalse($Session->check('Test')); + + $Session->write('Test', 'some value'); + $this->assertTrue($Session->check('Test')); + $Session->delete('Test'); + } + +/** + * testSessionFlash method + * + * @return void + */ + public function testSessionFlash() { + $Session = new SessionComponent($this->ComponentCollection); + + $this->assertNull($Session->read('Message.flash')); + + $Session->setFlash('This is a test message'); + $this->assertEquals(array('message' => 'This is a test message', 'element' => 'default', 'params' => array()), $Session->read('Message.flash')); + + $Session->setFlash('This is a test message', 'test', array('name' => 'Joel Moss')); + $this->assertEquals(array('message' => 'This is a test message', 'element' => 'test', 'params' => array('name' => 'Joel Moss')), $Session->read('Message.flash')); + + $Session->setFlash('This is a test message', 'default', array(), 'myFlash'); + $this->assertEquals(array('message' => 'This is a test message', 'element' => 'default', 'params' => array()), $Session->read('Message.myFlash')); + + $Session->setFlash('This is a test message', 'non_existing_layout'); + $this->assertEquals(array('message' => 'This is a test message', 'element' => 'default', 'params' => array()), $Session->read('Message.myFlash')); + + $Session->delete('Message'); + } + +/** + * testSessionId method + * + * @return void + */ + public function testSessionId() { + unset($_SESSION); + $Session = new SessionComponent($this->ComponentCollection); + $Session->check('test'); + $this->assertEquals(session_id(), $Session->id()); + } + +/** + * testSessionDestroy method + * + * @return void + */ + public function testSessionDestroy() { + $Session = new SessionComponent($this->ComponentCollection); + + $Session->write('Test', 'some value'); + $this->assertEquals('some value', $Session->read('Test')); + $Session->destroy('Test'); + $this->assertNull($Session->read('Test')); + } + +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/ComponentCollectionTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/ComponentCollectionTest.php new file mode 100644 index 0000000..11f5e6a --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/ComponentCollectionTest.php @@ -0,0 +1,178 @@ +Components = new ComponentCollection(); + } + +/** + * tearDown + * + * @return void + */ + public function tearDown() { + parent::tearDown(); + unset($this->Components); + } + +/** + * test triggering callbacks on loaded helpers + * + * @return void + */ + public function testLoad() { + $result = $this->Components->load('Cookie'); + $this->assertInstanceOf('CookieComponent', $result); + $this->assertInstanceOf('CookieComponent', $this->Components->Cookie); + + $result = $this->Components->attached(); + $this->assertEquals(array('Cookie'), $result, 'attached() results are wrong.'); + + $this->assertTrue($this->Components->enabled('Cookie')); + + $result = $this->Components->load('Cookie'); + $this->assertSame($result, $this->Components->Cookie); + } + +/** + * Tests loading as an alias + * + * @return void + */ + public function testLoadWithAlias() { + $result = $this->Components->load('Cookie', array('className' => 'CookieAlias', 'somesetting' => true)); + $this->assertInstanceOf('CookieAliasComponent', $result); + $this->assertInstanceOf('CookieAliasComponent', $this->Components->Cookie); + $this->assertTrue($this->Components->Cookie->settings['somesetting']); + + $result = $this->Components->attached(); + $this->assertEquals(array('Cookie'), $result, 'attached() results are wrong.'); + + $this->assertTrue($this->Components->enabled('Cookie')); + + $result = $this->Components->load('Cookie'); + $this->assertInstanceOf('CookieAliasComponent', $result); + + App::build(array('Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS))); + CakePlugin::load('TestPlugin'); + $result = $this->Components->load('SomeOther', array('className' => 'TestPlugin.Other')); + $this->assertInstanceOf('OtherComponent', $result); + $this->assertInstanceOf('OtherComponent', $this->Components->SomeOther); + + $result = $this->Components->attached(); + $this->assertEquals(array('Cookie', 'SomeOther'), $result, 'attached() results are wrong.'); + App::build(); + CakePlugin::unload(); + } + +/** + * test load and enable = false + * + * @return void + */ + public function testLoadWithEnableFalse() { + $result = $this->Components->load('Cookie', array('enabled' => false)); + $this->assertInstanceOf('CookieComponent', $result); + $this->assertInstanceOf('CookieComponent', $this->Components->Cookie); + + $this->assertFalse($this->Components->enabled('Cookie'), 'Cookie should be disabled'); + } + +/** + * test missingcomponent exception + * + * @expectedException MissingComponentException + * @return void + */ + public function testLoadMissingComponent() { + $this->Components->load('ThisComponentShouldAlwaysBeMissing'); + } + +/** + * test loading a plugin component. + * + * @return void + */ + public function testLoadPluginComponent() { + App::build(array( + 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS), + )); + CakePlugin::load('TestPlugin'); + $result = $this->Components->load('TestPlugin.Other'); + $this->assertInstanceOf('OtherComponent', $result, 'Component class is wrong.'); + $this->assertInstanceOf('OtherComponent', $this->Components->Other, 'Class is wrong'); + App::build(); + CakePlugin::unload(); + } + +/** + * test unload() + * + * @return void + */ + public function testUnload() { + $this->Components->load('Cookie'); + $this->Components->load('Security'); + + $result = $this->Components->attached(); + $this->assertEquals(array('Cookie', 'Security'), $result, 'loaded components is wrong'); + + $this->Components->unload('Cookie'); + $this->assertFalse(isset($this->Components->Cookie)); + $this->assertTrue(isset($this->Components->Security)); + + $result = $this->Components->attached(); + $this->assertEquals(array('Security'), $result, 'loaded components is wrong'); + + $result = $this->Components->enabled(); + $this->assertEquals(array('Security'), $result, 'enabled components is wrong'); + } + +/** + * test getting the controller out of the collection + * + * @return void + */ + public function testGetController() { + $controller = $this->getMock('Controller'); + $controller->components = array('Security'); + $this->Components->init($controller); + $result = $this->Components->getController(); + + $this->assertSame($controller, $result); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/ComponentTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/ComponentTest.php new file mode 100644 index 0000000..6085407 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/ComponentTest.php @@ -0,0 +1,305 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Controller + * @since CakePHP(tm) v 1.2.0.5436 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ + +App::uses('Controller', 'Controller'); +App::uses('Component', 'Controller'); + +/** + * ParamTestComponent + * + * @package Cake.Test.Case.Controller + */ +class ParamTestComponent extends Component { + +/** + * name property + * + * @var string 'ParamTest' + */ + public $name = 'ParamTest'; + +/** + * components property + * + * @var array + */ + public $components = array('Banana' => array('config' => 'value')); +} + +/** + * ComponentTestController class + * + * @package Cake.Test.Case.Controller + */ +class ComponentTestController extends Controller { + +/** + * name property + * + * @var string 'ComponentTest' + */ + public $name = 'ComponentTest'; + +/** + * uses property + * + * @var array + */ + public $uses = array(); + +} + +/** + * AppleComponent class + * + * @package Cake.Test.Case.Controller + */ +class AppleComponent extends Component { + +/** + * components property + * + * @var array + */ + public $components = array('Orange'); + +/** + * testName property + * + * @var mixed null + */ + public $testName = null; + +/** + * startup method + * + * @param Controller $controller + * @return void + */ + public function startup(Controller $controller) { + $this->testName = $controller->name; + } + +} + +/** + * OrangeComponent class + * + * @package Cake.Test.Case.Controller + */ +class OrangeComponent extends Component { + +/** + * components property + * + * @var array + */ + public $components = array('Banana'); + +/** + * initialize method + * + * @param Controller $controller + * @return void + */ + public function initialize(Controller $controller) { + $this->Controller = $controller; + $this->Banana->testField = 'OrangeField'; + } + +/** + * startup method + * + * @param Controller $controller + * @return string + */ + public function startup(Controller $controller) { + $controller->foo = 'pass'; + } + +} + +/** + * BananaComponent class + * + * @package Cake.Test.Case.Controller + */ +class BananaComponent extends Component { + +/** + * testField property + * + * @var string 'BananaField' + */ + public $testField = 'BananaField'; + +/** + * startup method + * + * @param Controller $controller + * @return string + */ + public function startup(Controller $controller) { + $controller->bar = 'fail'; + } + +} + +/** + * MutuallyReferencingOneComponent class + * + * @package Cake.Test.Case.Controller + */ +class MutuallyReferencingOneComponent extends Component { + +/** + * components property + * + * @var array + */ + public $components = array('MutuallyReferencingTwo'); +} + +/** + * MutuallyReferencingTwoComponent class + * + * @package Cake.Test.Case.Controller + */ +class MutuallyReferencingTwoComponent extends Component { + +/** + * components property + * + * @var array + */ + public $components = array('MutuallyReferencingOne'); +} + +/** + * SomethingWithEmailComponent class + * + * @package Cake.Test.Case.Controller + */ +class SomethingWithEmailComponent extends Component { + +/** + * components property + * + * @var array + */ + public $components = array('Email'); +} + + +/** + * ComponentTest class + * + * @package Cake.Test.Case.Controller + */ +class ComponentTest extends CakeTestCase { + +/** + * setUp method + * + * @return void + */ + public function setUp() { + parent::setUp(); + $this->_pluginPaths = App::path('plugins'); + App::build(array( + 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS) + )); + } + +/** + * test accessing inner components. + * + * @return void + */ + public function testInnerComponentConstruction() { + $Collection = new ComponentCollection(); + $Component = new AppleComponent($Collection); + + $this->assertInstanceOf('OrangeComponent', $Component->Orange, 'class is wrong'); + } + +/** + * test component loading + * + * @return void + */ + public function testNestedComponentLoading() { + $Collection = new ComponentCollection(); + $Apple = new AppleComponent($Collection); + + $this->assertInstanceOf('OrangeComponent', $Apple->Orange, 'class is wrong'); + $this->assertInstanceOf('BananaComponent', $Apple->Orange->Banana, 'class is wrong'); + $this->assertTrue(empty($Apple->Session)); + $this->assertTrue(empty($Apple->Orange->Session)); + } + +/** + * test that component components are not enabled in the collection. + * + * @return void + */ + public function testInnerComponentsAreNotEnabled() { + $Collection = new ComponentCollection(); + $Apple = $Collection->load('Apple'); + + $this->assertInstanceOf('OrangeComponent', $Apple->Orange, 'class is wrong'); + $result = $Collection->enabled(); + $this->assertEquals(array('Apple'), $result, 'Too many components enabled.'); + } + +/** + * test a component being used more than once. + * + * @return void + */ + public function testMultipleComponentInitialize() { + $Collection = new ComponentCollection(); + $Banana = $Collection->load('Banana'); + $Orange = $Collection->load('Orange'); + + $this->assertSame($Banana, $Orange->Banana, 'Should be references'); + $Banana->testField = 'OrangeField'; + + $this->assertSame($Banana->testField, $Orange->Banana->testField, 'References are broken'); + } + +/** + * Test mutually referencing components. + * + * @return void + */ + public function testSomethingReferencingEmailComponent() { + $Controller = new ComponentTestController(); + $Controller->components = array('SomethingWithEmail'); + $Controller->uses = false; + $Controller->constructClasses(); + $Controller->Components->trigger('initialize', array(&$Controller)); + $Controller->beforeFilter(); + $Controller->Components->trigger('startup', array(&$Controller)); + + $this->assertInstanceOf('SomethingWithEmailComponent', $Controller->SomethingWithEmail); + $this->assertInstanceOf('EmailComponent', $Controller->SomethingWithEmail->Email); + } + +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/ControllerMergeVarsTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/ControllerMergeVarsTest.php new file mode 100644 index 0000000..93a5cec --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/ControllerMergeVarsTest.php @@ -0,0 +1,252 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Controller + * @since CakePHP(tm) v 1.2.3 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ +App::uses('Controller', 'Controller'); + +/** + * Test case AppController + * + * @package Cake.Test.Case.Controller + * @package Cake.Test.Case.Controller + */ +class MergeVarsAppController extends Controller { + +/** + * components + * + * @var array + */ + public $components = array('MergeVar' => array('flag', 'otherFlag', 'redirect' => false)); + +/** + * helpers + * + * @var array + */ + public $helpers = array('MergeVar' => array('format' => 'html', 'terse')); +} + +/** + * MergeVar Component + * + * @package Cake.Test.Case.Controller + */ +class MergeVarComponent extends Object { + +} + +/** + * Additional controller for testing + * + * @package Cake.Test.Case.Controller + */ +class MergeVariablesController extends MergeVarsAppController { + +/** + * name + * + * @var string + */ + public $name = 'MergeVariables'; + +/** + * uses + * + * @var arrays + */ + public $uses = array(); + +/** + * parent for mergeVars + * + * @var string + */ + protected $_mergeParent = 'MergeVarsAppController'; +} + +/** + * MergeVarPlugin App Controller + * + * @package Cake.Test.Case.Controller + */ +class MergeVarPluginAppController extends MergeVarsAppController { + +/** + * components + * + * @var array + */ + public $components = array('Auth' => array('setting' => 'val', 'otherVal')); + +/** + * helpers + * + * @var array + */ + public $helpers = array('Javascript'); + +/** + * parent for mergeVars + * + * @var string + */ + protected $_mergeParent = 'MergeVarsAppController'; +} + +/** + * MergePostsController + * + * @package Cake.Test.Case.Controller + */ +class MergePostsController extends MergeVarPluginAppController { + +/** + * name + * + * @var string + */ + public $name = 'MergePosts'; + +/** + * uses + * + * @var array + */ + public $uses = array(); +} + + +/** + * Test Case for Controller Merging of Vars. + * + * @package Cake.Test.Case.Controller + */ +class ControllerMergeVarsTest extends CakeTestCase { + +/** + * test that component settings are not duplicated when merging component settings + * + * @return void + */ + public function testComponentParamMergingNoDuplication() { + $Controller = new MergeVariablesController(); + $Controller->constructClasses(); + + $expected = array('MergeVar' => array('flag', 'otherFlag', 'redirect' => false)); + $this->assertEquals($expected, $Controller->components, 'Duplication of settings occurred. %s'); + } + +/** + * test component merges with redeclared components + * + * @return void + */ + public function testComponentMergingWithRedeclarations() { + $Controller = new MergeVariablesController(); + $Controller->components['MergeVar'] = array('remote', 'redirect' => true); + $Controller->constructClasses(); + + $expected = array('MergeVar' => array('flag', 'otherFlag', 'redirect' => true, 'remote')); + $this->assertEquals($expected, $Controller->components, 'Merging of settings is wrong. %s'); + } + +/** + * test merging of helpers array, ensure no duplication occurs + * + * @return void + */ + public function testHelperSettingMergingNoDuplication() { + $Controller = new MergeVariablesController(); + $Controller->constructClasses(); + + $expected = array('MergeVar' => array('format' => 'html', 'terse')); + $this->assertEquals($expected, $Controller->helpers, 'Duplication of settings occurred. %s'); + } + +/** + * Test that helpers declared in appcontroller come before those in the subclass + * orderwise + * + * @return void + */ + public function testHelperOrderPrecedence() { + $Controller = new MergeVariablesController(); + $Controller->helpers = array('Custom', 'Foo' => array('something')); + $Controller->constructClasses(); + + $expected = array( + 'MergeVar' => array('format' => 'html', 'terse'), + 'Custom' => null, + 'Foo' => array('something') + ); + $this->assertSame($expected, $Controller->helpers, 'Order is incorrect.'); + } + +/** + * test merging of vars with plugin + * + * @return void + */ + public function testMergeVarsWithPlugin() { + $Controller = new MergePostsController(); + $Controller->components = array('Email' => array('ports' => 'open')); + $Controller->plugin = 'MergeVarPlugin'; + $Controller->constructClasses(); + + $expected = array( + 'MergeVar' => array('flag', 'otherFlag', 'redirect' => false), + 'Auth' => array('setting' => 'val', 'otherVal'), + 'Email' => array('ports' => 'open') + ); + $this->assertEquals($expected, $Controller->components, 'Components are unexpected.'); + + $expected = array( + 'MergeVar' => array('format' => 'html', 'terse'), + 'Javascript' => null + ); + $this->assertEquals($expected, $Controller->helpers, 'Helpers are unexpected.'); + + $Controller = new MergePostsController(); + $Controller->components = array(); + $Controller->plugin = 'MergeVarPlugin'; + $Controller->constructClasses(); + + $expected = array( + 'MergeVar' => array('flag', 'otherFlag', 'redirect' => false), + 'Auth' => array('setting' => 'val', 'otherVal'), + ); + $this->assertEquals($expected, $Controller->components, 'Components are unexpected.'); + } + +/** + * Ensure that _mergeControllerVars is not being greedy and merging with + * AppController when you make an instance of Controller + * + * @return void + */ + public function testMergeVarsNotGreedy() { + $Controller = new Controller(); + $Controller->components = array(); + $Controller->uses = array(); + $Controller->constructClasses(); + + $this->assertFalse(isset($Controller->Session)); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/ControllerTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/ControllerTest.php new file mode 100644 index 0000000..36116ad --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/ControllerTest.php @@ -0,0 +1,1441 @@ + 'error_msg'); + +/** + * lastQuery property + * + * @var mixed null + */ + public $lastQuery = null; + +/** + * beforeFind method + * + * @param mixed $query + * @return void + */ + public function beforeFind($query) { + $this->lastQuery = $query; + } + +/** + * find method + * + * @param string $type + * @param array $options + * @return void + */ + public function find($type = 'first', $options = array()) { + if ($type == 'popular') { + $conditions = array($this->name . '.' . $this->primaryKey . ' > ' => '1'); + $options = Hash::merge($options, compact('conditions')); + return parent::find('all', $options); + } + return parent::find($type, $options); + } + +} + +/** + * ControllerPostsController class + * + * @package Cake.Test.Case.Controller + */ +class ControllerCommentsController extends ControllerTestAppController { + +/** + * name property + * + * @var string 'ControllerPost' + */ + public $name = 'ControllerComments'; + + protected $_mergeParent = 'ControllerTestAppController'; +} + +/** + * ControllerComment class + * + * @package Cake.Test.Case.Controller + */ +class ControllerComment extends CakeTestModel { + +/** + * name property + * + * @var string 'ControllerComment' + */ + public $name = 'Comment'; + +/** + * useTable property + * + * @var string 'comments' + */ + public $useTable = 'comments'; + +/** + * data property + * + * @var array + */ + public $data = array('name' => 'Some Name'); + +/** + * alias property + * + * @var string 'ControllerComment' + */ + public $alias = 'ControllerComment'; +} + +/** + * ControllerAlias class + * + * @package Cake.Test.Case.Controller + */ +class ControllerAlias extends CakeTestModel { + +/** + * name property + * + * @var string 'ControllerAlias' + */ + public $name = 'ControllerAlias'; + +/** + * alias property + * + * @var string 'ControllerSomeAlias' + */ + public $alias = 'ControllerSomeAlias'; + +/** + * useTable property + * + * @var string 'posts' + */ + public $useTable = 'posts'; +} + +/** + * NameTest class + * + * @package Cake.Test.Case.Controller + */ +class NameTest extends CakeTestModel { + +/** + * name property + * @var string 'Name' + */ + public $name = 'Name'; + +/** + * useTable property + * @var string 'names' + */ + public $useTable = 'comments'; + +/** + * alias property + * + * @var string 'ControllerComment' + */ + public $alias = 'Name'; +} + +/** + * TestController class + * + * @package Cake.Test.Case.Controller + */ +class TestController extends ControllerTestAppController { + +/** + * name property + * @var string 'Name' + */ + public $name = 'Test'; + +/** + * helpers property + * + * @var array + */ + public $helpers = array('Session'); + +/** + * components property + * + * @var array + */ + public $components = array('Security'); + +/** + * uses property + * + * @var array + */ + public $uses = array('ControllerComment', 'ControllerAlias'); + + protected $_mergeParent = 'ControllerTestAppController'; + +/** + * index method + * + * @param mixed $testId + * @param mixed $test2Id + * @return void + */ + public function index($testId, $testTwoId) { + $this->data = array( + 'testId' => $testId, + 'test2Id' => $testTwoId + ); + } + +/** + * view method + * + * @param mixed $testId + * @param mixed $test2Id + * @return void + */ + public function view($testId, $testTwoId) { + $this->data = array( + 'testId' => $testId, + 'test2Id' => $testTwoId + ); + } + + public function returner() { + return 'I am from the controller.'; + } + + //@codingStandardsIgnoreStart + protected function protected_m() { + } + + private function private_m() { + } + + public function _hidden() { + } + //@codingStandardsIgnoreEnd + + public function admin_add() { + } + +} + +/** + * TestComponent class + * + * @package Cake.Test.Case.Controller + */ +class TestComponent extends Object { + +/** + * beforeRedirect method + * + * @return void + */ + public function beforeRedirect() { + } + +/** + * initialize method + * + * @return void + */ + public function initialize(Controller $controller) { + } + +/** + * startup method + * + * @return void + */ + public function startup(Controller $controller) { + } + +/** + * shutdown method + * + * @return void + */ + public function shutdown(Controller $controller) { + } + +/** + * beforeRender callback + * + * @return void + */ + public function beforeRender(Controller $controller) { + if ($this->viewclass) { + $controller->viewClass = $this->viewclass; + } + } + +} + +class Test2Component extends TestComponent { + + public function beforeRender(Controller $controller) { + return false; + } + +} + +/** + * AnotherTestController class + * + * @package Cake.Test.Case.Controller + */ +class AnotherTestController extends ControllerTestAppController { + +/** + * name property + * @var string 'Name' + */ + public $name = 'AnotherTest'; + +/** + * uses property + * + * @var array + */ + public $uses = false; + +/** + * merge parent + * + * @var string + */ + protected $_mergeParent = 'ControllerTestAppController'; +} + +/** + * ControllerTest class + * + * @package Cake.Test.Case.Controller + */ +class ControllerTest extends CakeTestCase { + +/** + * fixtures property + * + * @var array + */ + public $fixtures = array( + 'core.post', + 'core.comment' + ); + +/** + * reset environment. + * + * @return void + */ + public function setUp() { + parent::setUp(); + App::objects('plugin', null, false); + App::build(); + Router::reload(); + } + +/** + * tearDown + * + * @return void + */ + public function tearDown() { + parent::tearDown(); + CakePlugin::unload(); + } + +/** + * testLoadModel method + * + * @return void + */ + public function testLoadModel() { + $request = new CakeRequest('controller_posts/index'); + $response = $this->getMock('CakeResponse'); + $Controller = new Controller($request, $response); + + $this->assertFalse(isset($Controller->ControllerPost)); + + $result = $Controller->loadModel('ControllerPost'); + $this->assertTrue($result); + $this->assertTrue(is_a($Controller->ControllerPost, 'ControllerPost')); + $this->assertTrue(in_array('ControllerPost', $Controller->uses)); + + ClassRegistry::flush(); + unset($Controller); + } + +/** + * testLoadModel method from a plugin controller + * + * @return void + */ + public function testLoadModelInPlugins() { + App::build(array( + 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS), + 'Controller' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Controller' . DS), + 'Model' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Model' . DS) + )); + CakePlugin::load('TestPlugin'); + App::uses('TestPluginAppController', 'TestPlugin.Controller'); + App::uses('TestPluginController', 'TestPlugin.Controller'); + + $Controller = new TestPluginController(); + $Controller->plugin = 'TestPlugin'; + $Controller->uses = false; + + $this->assertFalse(isset($Controller->Comment)); + + $result = $Controller->loadModel('Comment'); + $this->assertTrue($result); + $this->assertInstanceOf('Comment', $Controller->Comment); + $this->assertTrue(in_array('Comment', $Controller->uses)); + + ClassRegistry::flush(); + unset($Controller); + } + +/** + * testConstructClasses method + * + * @return void + */ + public function testConstructClasses() { + $request = new CakeRequest('controller_posts/index'); + + $Controller = new Controller($request); + $Controller->uses = array('ControllerPost', 'ControllerComment'); + $Controller->constructClasses(); + $this->assertTrue(is_a($Controller->ControllerPost, 'ControllerPost')); + $this->assertTrue(is_a($Controller->ControllerComment, 'ControllerComment')); + + $this->assertEquals('Comment', $Controller->ControllerComment->name); + + unset($Controller); + + App::build(array('Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS))); + CakePlugin::load('TestPlugin'); + + $Controller = new Controller($request); + $Controller->uses = array('TestPlugin.TestPluginPost'); + $Controller->constructClasses(); + + $this->assertTrue(isset($Controller->TestPluginPost)); + $this->assertTrue(is_a($Controller->TestPluginPost, 'TestPluginPost')); + } + +/** + * testAliasName method + * + * @return void + */ + public function testAliasName() { + $request = new CakeRequest('controller_posts/index'); + $Controller = new Controller($request); + $Controller->uses = array('NameTest'); + $Controller->constructClasses(); + + $this->assertEquals('Name', $Controller->NameTest->name); + $this->assertEquals('Name', $Controller->NameTest->alias); + + unset($Controller); + } + +/** + * testFlash method + * + * @return void + */ + public function testFlash() { + $request = new CakeRequest('controller_posts/index'); + $request->webroot = '/'; + $request->base = '/'; + + $Controller = new Controller($request, $this->getMock('CakeResponse', array('_sendHeader'))); + $Controller->flash('this should work', '/flash'); + $result = $Controller->response->body(); + + $expected = ' + + + + this should work + + + +

this should work

+ + '; + $result = str_replace(array("\t", "\r\n", "\n"), "", $result); + $expected = str_replace(array("\t", "\r\n", "\n"), "", $expected); + $this->assertEquals($expected, $result); + + App::build(array( + 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS) + )); + $Controller = new Controller($request); + $Controller->response = $this->getMock('CakeResponse', array('_sendHeader')); + $Controller->flash('this should work', '/flash', 1, 'ajax2'); + $result = $Controller->response->body(); + $this->assertRegExp('/Ajax!/', $result); + App::build(); + } + +/** + * testControllerSet method + * + * @return void + */ + public function testControllerSet() { + $request = new CakeRequest('controller_posts/index'); + $Controller = new Controller($request); + + $Controller->set('variable_with_underscores', null); + $this->assertTrue(array_key_exists('variable_with_underscores', $Controller->viewVars)); + + $Controller->viewVars = array(); + $viewVars = array('ModelName' => array('id' => 1, 'name' => 'value')); + $Controller->set($viewVars); + $this->assertTrue(array_key_exists('ModelName', $Controller->viewVars)); + + $Controller->viewVars = array(); + $Controller->set('variable_with_underscores', 'value'); + $this->assertTrue(array_key_exists('variable_with_underscores', $Controller->viewVars)); + + $Controller->viewVars = array(); + $viewVars = array('ModelName' => 'name'); + $Controller->set($viewVars); + $this->assertTrue(array_key_exists('ModelName', $Controller->viewVars)); + + $Controller->set('title', 'someTitle'); + $this->assertSame($Controller->viewVars['title'], 'someTitle'); + $this->assertTrue(empty($Controller->pageTitle)); + + $Controller->viewVars = array(); + $expected = array('ModelName' => 'name', 'ModelName2' => 'name2'); + $Controller->set(array('ModelName', 'ModelName2'), array('name', 'name2')); + $this->assertSame($expected, $Controller->viewVars); + + $Controller->viewVars = array(); + $Controller->set(array(3 => 'three', 4 => 'four')); + $Controller->set(array(1 => 'one', 2 => 'two')); + $expected = array(3 => 'three', 4 => 'four', 1 => 'one', 2 => 'two'); + $this->assertEquals($expected, $Controller->viewVars); + } + +/** + * testRender method + * + * @return void + */ + public function testRender() { + App::build(array( + 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS) + ), App::RESET); + ClassRegistry::flush(); + $request = new CakeRequest('controller_posts/index'); + $request->params['action'] = 'index'; + + $Controller = new Controller($request, new CakeResponse()); + $Controller->viewPath = 'Posts'; + + $result = $Controller->render('index'); + $this->assertRegExp('/posts index/', (string)$result); + + $Controller->view = 'index'; + $result = $Controller->render(); + $this->assertRegExp('/posts index/', (string)$result); + + $result = $Controller->render('/Elements/test_element'); + $this->assertRegExp('/this is the test element/', (string)$result); + $Controller->view = null; + + $Controller = new TestController($request, new CakeResponse()); + $Controller->uses = array('ControllerAlias', 'TestPlugin.ControllerComment', 'ControllerPost'); + $Controller->helpers = array('Html'); + $Controller->constructClasses(); + $Controller->ControllerComment->validationErrors = array('title' => 'tooShort'); + $expected = $Controller->ControllerComment->validationErrors; + + $Controller->viewPath = 'Posts'; + $result = $Controller->render('index'); + $View = $Controller->View; + $this->assertTrue(isset($View->validationErrors['ControllerComment'])); + $this->assertEquals($expected, $View->validationErrors['ControllerComment']); + + $expectedModels = array( + 'ControllerAlias' => array('plugin' => null, 'className' => 'ControllerAlias'), + 'ControllerComment' => array('plugin' => 'TestPlugin', 'className' => 'ControllerComment'), + 'ControllerPost' => array('plugin' => null, 'className' => 'ControllerPost') + ); + $this->assertEquals($expectedModels, $Controller->request->params['models']); + + ClassRegistry::flush(); + App::build(); + } + +/** + * test that a component beforeRender can change the controller view class. + * + * @return void + */ + public function testComponentBeforeRenderChangingViewClass() { + App::build(array( + 'View' => array( + CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS + ) + ), true); + $Controller = new Controller($this->getMock('CakeRequest'), new CakeResponse()); + $Controller->uses = array(); + $Controller->components = array('Test'); + $Controller->constructClasses(); + $Controller->Test->viewclass = 'Theme'; + $Controller->viewPath = 'Posts'; + $Controller->theme = 'TestTheme'; + $result = $Controller->render('index'); + $this->assertRegExp('/default test_theme layout/', (string)$result); + App::build(); + } + +/** + * test that a component beforeRender can change the controller view class. + * + * @return void + */ + public function testComponentCancelRender() { + $Controller = new Controller($this->getMock('CakeRequest'), new CakeResponse()); + $Controller->uses = array(); + $Controller->components = array('Test2'); + $Controller->constructClasses(); + $result = $Controller->render('index'); + $this->assertInstanceOf('CakeResponse', $result); + } + +/** + * testToBeInheritedGuardmethods method + * + * @return void + */ + public function testToBeInheritedGuardmethods() { + $request = new CakeRequest('controller_posts/index'); + + $Controller = new Controller($request, $this->getMock('CakeResponse')); + $this->assertTrue($Controller->beforeScaffold('')); + $this->assertTrue($Controller->afterScaffoldSave('')); + $this->assertTrue($Controller->afterScaffoldSaveError('')); + $this->assertFalse($Controller->scaffoldError('')); + } + +/** + * Generates status codes for redirect test. + * + * @return void + */ + public static function statusCodeProvider() { + return array( + array(300, "Multiple Choices"), + array(301, "Moved Permanently"), + array(302, "Found"), + array(303, "See Other"), + array(304, "Not Modified"), + array(305, "Use Proxy"), + array(307, "Temporary Redirect"), + array(403, "Forbidden"), + ); + } + +/** + * testRedirect method + * + * @dataProvider statusCodeProvider + * @return void + */ + public function testRedirectByCode($code, $msg) { + $Controller = new Controller(null); + $Controller->response = $this->getMock('CakeResponse', array('header', 'statusCode')); + + $Controller->Components = $this->getMock('ComponentCollection', array('trigger')); + + $Controller->response->expects($this->once())->method('statusCode') + ->with($code); + $Controller->response->expects($this->once())->method('header') + ->with('Location', 'http://cakephp.org'); + + $Controller->redirect('http://cakephp.org', (int)$code, false); + $this->assertFalse($Controller->autoRender); + } + +/** + * test redirecting by message + * + * @dataProvider statusCodeProvider + * @return void + */ + public function testRedirectByMessage($code, $msg) { + $Controller = new Controller(null); + $Controller->response = $this->getMock('CakeResponse', array('header', 'statusCode')); + + $Controller->Components = $this->getMock('ComponentCollection', array('trigger')); + + $Controller->response->expects($this->once())->method('statusCode') + ->with($code); + + $Controller->response->expects($this->once())->method('header') + ->with('Location', 'http://cakephp.org'); + + $Controller->redirect('http://cakephp.org', $msg, false); + $this->assertFalse($Controller->autoRender); + } + +/** + * test that redirect triggers methods on the components. + * + * @return void + */ + public function testRedirectTriggeringComponentsReturnNull() { + $Controller = new Controller(null); + $Controller->response = $this->getMock('CakeResponse', array('header', 'statusCode')); + $Controller->Components = $this->getMock('ComponentCollection', array('trigger')); + + $Controller->Components->expects($this->once())->method('trigger') + ->will($this->returnValue(null)); + + $Controller->response->expects($this->once())->method('statusCode') + ->with(301); + + $Controller->response->expects($this->once())->method('header') + ->with('Location', 'http://cakephp.org'); + + $Controller->redirect('http://cakephp.org', 301, false); + } + +/** + * test that beforeRedirect callback returning null doesn't affect things. + * + * @return void + */ + public function testRedirectBeforeRedirectModifyingParams() { + $Controller = new Controller(null); + $Controller->response = $this->getMock('CakeResponse', array('header', 'statusCode')); + $Controller->Components = $this->getMock('ComponentCollection', array('trigger')); + + $Controller->Components->expects($this->once())->method('trigger') + ->will($this->returnValue(array('http://book.cakephp.org'))); + + $Controller->response->expects($this->once())->method('statusCode') + ->with(301); + + $Controller->response->expects($this->once())->method('header') + ->with('Location', 'http://book.cakephp.org'); + + $Controller->redirect('http://cakephp.org', 301, false); + } + +/** + * test that beforeRedirect callback returning null doesn't affect things. + * + * @return void + */ + public function testRedirectBeforeRedirectModifyingParamsArrayReturn() { + $Controller = $this->getMock('Controller', array('header', '_stop')); + $Controller->response = $this->getMock('CakeResponse'); + $Controller->Components = $this->getMock('ComponentCollection', array('trigger')); + + $return = array( + array( + 'url' => 'http://example.com/test/1', + 'exit' => false, + 'status' => 302 + ), + array( + 'url' => 'http://example.com/test/2', + ), + ); + $Controller->Components->expects($this->once())->method('trigger') + ->will($this->returnValue($return)); + + $Controller->response->expects($this->once())->method('header') + ->with('Location', 'http://example.com/test/2'); + + $Controller->response->expects($this->at(1))->method('statusCode') + ->with(302); + + $Controller->expects($this->never())->method('_stop'); + $Controller->redirect('http://cakephp.org', 301); + } + +/** + * test that beforeRedirect callback returning false in controller + * + * @return void + */ + public function testRedirectBeforeRedirectInController() { + $Controller = $this->getMock('Controller', array('_stop', 'beforeRedirect')); + $Controller->response = $this->getMock('CakeResponse', array('header')); + $Controller->Components = $this->getMock('ComponentCollection', array('trigger')); + + $Controller->expects($this->once())->method('beforeRedirect') + ->with('http://cakephp.org') + ->will($this->returnValue(false)); + $Controller->response->expects($this->never())->method('header'); + $Controller->expects($this->never())->method('_stop'); + $Controller->redirect('http://cakephp.org'); + } + +/** + * Test that beforeRedirect works with returning an array from the controller method. + * + * @return void + */ + public function testRedirectBeforeRedirectInControllerWithArray() { + $Controller = $this->getMock('Controller', array('_stop', 'beforeRedirect')); + $Controller->response = $this->getMock('CakeResponse', array('header')); + $Controller->Components = $this->getMock('ComponentCollection', array('trigger')); + + $Controller->expects($this->once()) + ->method('beforeRedirect') + ->with('http://cakephp.org', null, true) + ->will($this->returnValue(array( + 'url' => 'http://example.org', + 'status' => 302, + 'exit' => true + ))); + + $Controller->response->expects($this->at(0)) + ->method('header') + ->with('Location', 'http://example.org'); + + $Controller->expects($this->once())->method('_stop'); + $Controller->redirect('http://cakephp.org'); + } + +/** + * testMergeVars method + * + * @return void + */ + public function testMergeVars() { + $request = new CakeRequest('controller_posts/index'); + + $TestController = new TestController($request); + $TestController->constructClasses(); + + $testVars = get_class_vars('TestController'); + $appVars = get_class_vars('ControllerTestAppController'); + + $components = is_array($appVars['components']) + ? array_merge($appVars['components'], $testVars['components']) + : $testVars['components']; + if (!in_array('Session', $components)) { + $components[] = 'Session'; + } + $helpers = is_array($appVars['helpers']) + ? array_merge($appVars['helpers'], $testVars['helpers']) + : $testVars['helpers']; + $uses = is_array($appVars['uses']) + ? array_merge($appVars['uses'], $testVars['uses']) + : $testVars['uses']; + + $this->assertEquals(0, count(array_diff_key($TestController->helpers, array_flip($helpers)))); + $this->assertEquals(0, count(array_diff($TestController->uses, $uses))); + $this->assertEquals(count(array_diff_assoc(Hash::normalize($TestController->components), Hash::normalize($components))), 0); + + $expected = array('ControllerComment', 'ControllerAlias', 'ControllerPost'); + $this->assertEquals($expected, $TestController->uses, '$uses was merged incorrectly, ControllerTestAppController models should be last.'); + + $TestController = new AnotherTestController($request); + $TestController->constructClasses(); + + $appVars = get_class_vars('ControllerTestAppController'); + $testVars = get_class_vars('AnotherTestController'); + + $this->assertTrue(in_array('ControllerPost', $appVars['uses'])); + $this->assertFalse($testVars['uses']); + + $this->assertFalse(property_exists($TestController, 'ControllerPost')); + + $TestController = new ControllerCommentsController($request); + $TestController->constructClasses(); + + $appVars = get_class_vars('ControllerTestAppController'); + $testVars = get_class_vars('ControllerCommentsController'); + + $this->assertTrue(in_array('ControllerPost', $appVars['uses'])); + $this->assertEquals(array('ControllerPost'), $testVars['uses']); + + $this->assertTrue(isset($TestController->ControllerPost)); + $this->assertTrue(isset($TestController->ControllerComment)); + } + +/** + * test that options from child classes replace those in the parent classes. + * + * @return void + */ + public function testChildComponentOptionsSupercedeParents() { + $request = new CakeRequest('controller_posts/index'); + + $TestController = new TestController($request); + + $expected = array('foo'); + $TestController->components = array('Cookie' => $expected); + $TestController->constructClasses(); + $this->assertEquals($expected, $TestController->components['Cookie']); + } + +/** + * Ensure that _mergeControllerVars is not being greedy and merging with + * ControllerTestAppController when you make an instance of Controller + * + * @return void + */ + public function testMergeVarsNotGreedy() { + $request = new CakeRequest('controller_posts/index'); + + $Controller = new Controller($request); + $Controller->components = array(); + $Controller->uses = array(); + $Controller->constructClasses(); + + $this->assertFalse(isset($Controller->Session)); + } + +/** + * testReferer method + * + * @return void + */ + public function testReferer() { + $request = $this->getMock('CakeRequest'); + + $request->expects($this->any())->method('referer') + ->with(true) + ->will($this->returnValue('/posts/index')); + + $Controller = new Controller($request); + $result = $Controller->referer(null, true); + $this->assertEquals('/posts/index', $result); + + $Controller = new Controller($request); + $request->setReturnValue('referer', '/', array(true)); + $result = $Controller->referer(array('controller' => 'posts', 'action' => 'index'), true); + $this->assertEquals('/posts/index', $result); + + $request = $this->getMock('CakeRequest'); + + $request->expects($this->any())->method('referer') + ->with(false) + ->will($this->returnValue('http://localhost/posts/index')); + + $Controller = new Controller($request); + $result = $Controller->referer(); + $this->assertEquals('http://localhost/posts/index', $result); + + $Controller = new Controller(null); + $result = $Controller->referer(); + $this->assertEquals('/', $result); + } + +/** + * testSetAction method + * + * @return void + */ + public function testSetAction() { + $request = new CakeRequest('controller_posts/index'); + + $TestController = new TestController($request); + $TestController->setAction('view', 1, 2); + $expected = array('testId' => 1, 'test2Id' => 2); + $this->assertSame($expected, $TestController->request->data); + $this->assertSame('view', $TestController->request->params['action']); + $this->assertSame('view', $TestController->view); + } + +/** + * testValidateErrors method + * + * @return void + */ + public function testValidateErrors() { + ClassRegistry::flush(); + $request = new CakeRequest('controller_posts/index'); + + $TestController = new TestController($request); + $TestController->constructClasses(); + $this->assertFalse($TestController->validateErrors()); + $this->assertEquals(0, $TestController->validate()); + + $TestController->ControllerComment->invalidate('some_field', 'error_message'); + $TestController->ControllerComment->invalidate('some_field2', 'error_message2'); + + $comment = new ControllerComment($request); + $comment->set('someVar', 'data'); + $result = $TestController->validateErrors($comment); + $expected = array('some_field' => array('error_message'), 'some_field2' => array('error_message2')); + $this->assertSame($expected, $result); + $this->assertEquals(2, $TestController->validate($comment)); + } + +/** + * test that validateErrors works with any old model. + * + * @return void + */ + public function testValidateErrorsOnArbitraryModels() { + $TestController = new TestController(); + + $Post = new ControllerPost(); + $Post->validate = array('title' => 'notEmpty'); + $Post->set('title', ''); + $result = $TestController->validateErrors($Post); + + $expected = array('title' => array('This field cannot be left blank')); + $this->assertEquals($expected, $result); + } + +/** + * testPostConditions method + * + * @return void + */ + public function testPostConditions() { + $request = new CakeRequest('controller_posts/index'); + + $Controller = new Controller($request); + + $data = array( + 'Model1' => array('field1' => '23'), + 'Model2' => array('field2' => 'string'), + 'Model3' => array('field3' => '23'), + ); + $expected = array( + 'Model1.field1' => '23', + 'Model2.field2' => 'string', + 'Model3.field3' => '23', + ); + $result = $Controller->postConditions($data); + $this->assertSame($expected, $result); + + $data = array(); + $Controller->data = array( + 'Model1' => array('field1' => '23'), + 'Model2' => array('field2' => 'string'), + 'Model3' => array('field3' => '23'), + ); + $expected = array( + 'Model1.field1' => '23', + 'Model2.field2' => 'string', + 'Model3.field3' => '23', + ); + $result = $Controller->postConditions($data); + $this->assertSame($expected, $result); + + $data = array(); + $Controller->data = array(); + $result = $Controller->postConditions($data); + $this->assertNull($result); + + $data = array(); + $Controller->data = array( + 'Model1' => array('field1' => '23'), + 'Model2' => array('field2' => 'string'), + 'Model3' => array('field3' => '23'), + ); + $ops = array( + 'Model1.field1' => '>', + 'Model2.field2' => 'LIKE', + 'Model3.field3' => '<=', + ); + $expected = array( + 'Model1.field1 >' => '23', + 'Model2.field2 LIKE' => "%string%", + 'Model3.field3 <=' => '23', + ); + $result = $Controller->postConditions($data, $ops); + $this->assertSame($expected, $result); + } + +/** + * testControllerHttpCodes method + * + * @return void + */ + public function testControllerHttpCodes() { + $response = $this->getMock('CakeResponse', array('httpCodes')); + $Controller = new Controller(null, $response); + $Controller->response->expects($this->at(0))->method('httpCodes')->with(null); + $Controller->response->expects($this->at(1))->method('httpCodes')->with(100); + $Controller->httpCodes(); + $Controller->httpCodes(100); + } + +/** + * Tests that the startup process calls the correct functions + * + * @return void + */ + public function testStartupProcess() { + $Controller = $this->getMock('Controller', array('getEventManager')); + + $eventManager = $this->getMock('CakeEventManager'); + $eventManager->expects($this->at(0))->method('dispatch') + ->with( + $this->logicalAnd( + $this->isInstanceOf('CakeEvent'), + $this->attributeEqualTo('_name', 'Controller.initialize'), + $this->attributeEqualTo('_subject', $Controller) + ) + ); + $eventManager->expects($this->at(1))->method('dispatch') + ->with( + $this->logicalAnd( + $this->isInstanceOf('CakeEvent'), + $this->attributeEqualTo('_name', 'Controller.startup'), + $this->attributeEqualTo('_subject', $Controller) + ) + ); + $Controller->expects($this->exactly(2))->method('getEventManager') + ->will($this->returnValue($eventManager)); + $Controller->startupProcess(); + } + +/** + * Tests that the shutdown process calls the correct functions + * + * @return void + */ + public function testStartupProcessIndirect() { + $Controller = $this->getMock('Controller', array('beforeFilter')); + + $Controller->components = array('MockShutdown'); + $Controller->Components = $this->getMock('ComponentCollection', array('trigger')); + + $Controller->expects($this->once())->method('beforeFilter'); + $Controller->Components->expects($this->exactly(2))->method('trigger')->with($this->isInstanceOf('CakeEvent')); + + $Controller->startupProcess(); + } + +/** + * Tests that the shutdown process calls the correct functions + * + * @return void + */ + public function testShutdownProcess() { + $Controller = $this->getMock('Controller', array('getEventManager')); + + $eventManager = $this->getMock('CakeEventManager'); + $eventManager->expects($this->once())->method('dispatch') + ->with( + $this->logicalAnd( + $this->isInstanceOf('CakeEvent'), + $this->attributeEqualTo('_name', 'Controller.shutdown'), + $this->attributeEqualTo('_subject', $Controller) + ) + ); + $Controller->expects($this->once())->method('getEventManager') + ->will($this->returnValue($eventManager)); + $Controller->shutdownProcess(); + } + +/** + * Tests that the shutdown process calls the correct functions + * + * @return void + */ + public function testShutdownProcessIndirect() { + $Controller = $this->getMock('Controller', array('afterFilter')); + + $Controller->components = array('MockShutdown'); + $Controller->Components = $this->getMock('ComponentCollection', array('trigger')); + + $Controller->expects($this->once())->method('afterFilter'); + $Controller->Components->expects($this->exactly(1))->method('trigger')->with($this->isInstanceOf('CakeEvent')); + + $Controller->shutdownProcess(); + } + +/** + * test that BC works for attributes on the request object. + * + * @return void + */ + public function testPropertyBackwardsCompatibility() { + $request = new CakeRequest('posts/index', null); + $request->addParams(array('controller' => 'posts', 'action' => 'index')); + $request->data = array('Post' => array('id' => 1)); + $request->here = '/posts/index'; + $request->webroot = '/'; + + $Controller = new TestController($request); + $this->assertEquals($request->data, $Controller->data); + $this->assertEquals($request->webroot, $Controller->webroot); + $this->assertEquals($request->here, $Controller->here); + $this->assertEquals($request->action, $Controller->action); + + $this->assertFalse(empty($Controller->data)); + $this->assertTrue(isset($Controller->data)); + $this->assertTrue(empty($Controller->something)); + $this->assertFalse(isset($Controller->something)); + + $this->assertEquals($request, $Controller->params); + $this->assertEquals($request->params['controller'], $Controller->params['controller']); + } + +/** + * test that the BC wrapper doesn't interfere with models and components. + * + * @return void + */ + public function testPropertyCompatibilityAndModelsComponents() { + $request = new CakeRequest('controller_posts/index'); + + $Controller = new TestController($request); + $Controller->constructClasses(); + $this->assertInstanceOf('SecurityComponent', $Controller->Security); + $this->assertInstanceOf('ControllerComment', $Controller->ControllerComment); + } + +/** + * test that using Controller::paginate() falls back to PaginatorComponent + * + * @return void + */ + public function testPaginateBackwardsCompatibility() { + $request = new CakeRequest('controller_posts/index'); + $request->params['pass'] = $request->params['named'] = array(); + $response = $this->getMock('CakeResponse', array('httpCodes')); + + $Controller = new Controller($request, $response); + $Controller->uses = array('ControllerPost', 'ControllerComment'); + $Controller->passedArgs[] = '1'; + $Controller->params['url'] = array(); + $Controller->constructClasses(); + $expected = array('page' => 1, 'limit' => 20, 'maxLimit' => 100, 'paramType' => 'named'); + $this->assertEquals($expected, $Controller->paginate); + + $results = Hash::extract($Controller->paginate('ControllerPost'), '{n}.ControllerPost.id'); + $this->assertEquals(array(1, 2, 3), $results); + + $Controller->passedArgs = array(); + $Controller->paginate = array('limit' => '-1'); + $this->assertEquals(array('limit' => '-1'), $Controller->paginate); + $Controller->paginate('ControllerPost'); + $this->assertSame($Controller->params['paging']['ControllerPost']['page'], 1); + $this->assertSame($Controller->params['paging']['ControllerPost']['pageCount'], 3); + $this->assertSame($Controller->params['paging']['ControllerPost']['prevPage'], false); + $this->assertSame($Controller->params['paging']['ControllerPost']['nextPage'], true); + } + +/** + * testMissingAction method + * + * @expectedException MissingActionException + * @expectedExceptionMessage Action TestController::missing() could not be found. + * @return void + */ + public function testInvokeActionMissingAction() { + $url = new CakeRequest('test/missing'); + $url->addParams(array('controller' => 'test_controller', 'action' => 'missing')); + $response = $this->getMock('CakeResponse'); + + $Controller = new TestController($url, $response); + $Controller->invokeAction($url); + } + +/** + * test invoking private methods. + * + * @expectedException PrivateActionException + * @expectedExceptionMessage Private Action TestController::private_m() is not directly accessible. + * @return void + */ + public function testInvokeActionPrivate() { + $url = new CakeRequest('test/private_m/'); + $url->addParams(array('controller' => 'test_controller', 'action' => 'private_m')); + $response = $this->getMock('CakeResponse'); + + $Controller = new TestController($url, $response); + $Controller->invokeAction($url); + } + +/** + * test invoking protected methods. + * + * @expectedException PrivateActionException + * @expectedExceptionMessage Private Action TestController::protected_m() is not directly accessible. + * @return void + */ + public function testInvokeActionProtected() { + $url = new CakeRequest('test/protected_m/'); + $url->addParams(array('controller' => 'test_controller', 'action' => 'protected_m')); + $response = $this->getMock('CakeResponse'); + + $Controller = new TestController($url, $response); + $Controller->invokeAction($url); + } + +/** + * test invoking hidden methods. + * + * @expectedException PrivateActionException + * @expectedExceptionMessage Private Action TestController::_hidden() is not directly accessible. + * @return void + */ + public function testInvokeActionHidden() { + $url = new CakeRequest('test/_hidden/'); + $url->addParams(array('controller' => 'test_controller', 'action' => '_hidden')); + $response = $this->getMock('CakeResponse'); + + $Controller = new TestController($url, $response); + $Controller->invokeAction($url); + } + +/** + * test invoking controller methods. + * + * @expectedException PrivateActionException + * @expectedExceptionMessage Private Action TestController::redirect() is not directly accessible. + * @return void + */ + public function testInvokeActionBaseMethods() { + $url = new CakeRequest('test/redirect/'); + $url->addParams(array('controller' => 'test_controller', 'action' => 'redirect')); + $response = $this->getMock('CakeResponse'); + + $Controller = new TestController($url, $response); + $Controller->invokeAction($url); + } + +/** + * test invoking controller methods. + * + * @expectedException PrivateActionException + * @expectedExceptionMessage Private Action TestController::admin_add() is not directly accessible. + * @return void + */ + public function testInvokeActionPrefixProtection() { + Router::reload(); + Router::connect('/admin/:controller/:action/*', array('prefix' => 'admin')); + + $url = new CakeRequest('test/admin_add/'); + $url->addParams(array('controller' => 'test_controller', 'action' => 'admin_add')); + $response = $this->getMock('CakeResponse'); + + $Controller = new TestController($url, $response); + $Controller->invokeAction($url); + } + +/** + * test invoking controller methods. + * + * @return void + */ + public function testInvokeActionReturnValue() { + $url = new CakeRequest('test/returner/'); + $url->addParams(array( + 'controller' => 'test_controller', + 'action' => 'returner', + 'pass' => array() + )); + $response = $this->getMock('CakeResponse'); + + $Controller = new TestController($url, $response); + $result = $Controller->invokeAction($url); + $this->assertEquals('I am from the controller.', $result); + } + +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/PagesControllerTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/PagesControllerTest.php new file mode 100644 index 0000000..614edea --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/PagesControllerTest.php @@ -0,0 +1,53 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Controller + * @since CakePHP(tm) v 1.2.0.5436 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ + +App::uses('PagesController', 'Controller'); + +/** + * PagesControllerTest class + * + * @package Cake.Test.Case.Controller + */ +class PagesControllerTest extends CakeTestCase { + +/** + * testDisplay method + * + * @return void + */ + public function testDisplay() { + App::build(array( + 'View' => array( + CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS + ) + )); + $Pages = new PagesController(new CakeRequest(null, false), new CakeResponse()); + + $Pages->viewPath = 'Posts'; + $Pages->display('index'); + $this->assertRegExp('/posts index/', $Pages->response->body()); + $this->assertEquals('index', $Pages->viewVars['page']); + + $Pages->viewPath = 'Themed'; + $Pages->display('TestTheme', 'Posts', 'index'); + $this->assertRegExp('/posts index themed view/', $Pages->response->body()); + $this->assertEquals('TestTheme', $Pages->viewVars['page']); + $this->assertEquals('Posts', $Pages->viewVars['subpage']); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/ScaffoldTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/ScaffoldTest.php new file mode 100644 index 0000000..14fe182 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Controller/ScaffoldTest.php @@ -0,0 +1,350 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Controller + * @since CakePHP(tm) v 1.2.0.5436 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ +App::uses('Router', 'Routing'); +App::uses('Controller', 'Controller'); +App::uses('Scaffold', 'Controller'); +App::uses('ScaffoldView', 'View'); +App::uses('AppModel', 'Model'); + +require_once dirname(dirname(__FILE__)) . DS . 'Model' . DS . 'models.php'; + +/** + * ScaffoldMockController class + * + * @package Cake.Test.Case.Controller + */ +class ScaffoldMockController extends Controller { + +/** + * name property + * + * @var string 'ScaffoldMock' + */ + public $name = 'ScaffoldMock'; + +/** + * scaffold property + * + * @var mixed + */ + public $scaffold; +} + +/** + * ScaffoldMockControllerWithFields class + * + * @package Cake.Test.Case.Controller + */ +class ScaffoldMockControllerWithFields extends Controller { + +/** + * name property + * + * @var string 'ScaffoldMock' + */ + public $name = 'ScaffoldMock'; + +/** + * scaffold property + * + * @var mixed + */ + public $scaffold; + +/** + * function beforeScaffold + * + * @param string method + */ + public function beforeScaffold($method) { + $this->set('scaffoldFields', array('title')); + return true; + } + +} + +/** + * TestScaffoldMock class + * + * @package Cake.Test.Case.Controller + */ +class TestScaffoldMock extends Scaffold { + +/** + * Overload _scaffold + * + * @param unknown_type $params + */ + protected function _scaffold(CakeRequest $request) { + $this->_params = $request; + } + +/** + * Get Params from the Controller. + * + * @return unknown + */ + public function getParams() { + return $this->_params; + } + +} + +/** + * Scaffold Test class + * + * @package Cake.Test.Case.Controller + */ +class ScaffoldTest extends CakeTestCase { + +/** + * Controller property + * + * @var SecurityTestController + */ + public $Controller; + +/** + * fixtures property + * + * @var array + */ + public $fixtures = array('core.article', 'core.user', 'core.comment', 'core.join_thing', 'core.tag'); + +/** + * setUp method + * + * @return void + */ + public function setUp() { + parent::setUp(); + $request = new CakeRequest(null, false); + $this->Controller = new ScaffoldMockController($request); + $this->Controller->response = $this->getMock('CakeResponse', array('_sendHeader')); + } + +/** + * tearDown method + * + * @return void + */ + public function tearDown() { + parent::tearDown(); + unset($this->Controller); + } + +/** + * Test the correct Generation of Scaffold Params. + * This ensures that the correct action and view will be generated + * + * @return void + */ + public function testScaffoldParams() { + $params = array( + 'plugin' => null, + 'pass' => array(), + 'form' => array(), + 'named' => array(), + 'url' => array('url' => 'admin/scaffold_mock/edit'), + 'controller' => 'scaffold_mock', + 'action' => 'admin_edit', + 'admin' => true, + ); + $this->Controller->request->base = ''; + $this->Controller->request->webroot = '/'; + $this->Controller->request->here = '/admin/scaffold_mock/edit'; + $this->Controller->request->addParams($params); + + //set router. + Router::setRequestInfo($this->Controller->request); + + $this->Controller->constructClasses(); + $Scaffold = new TestScaffoldMock($this->Controller, $this->Controller->request); + $result = $Scaffold->getParams(); + $this->assertEquals('admin_edit', $result['action']); + } + +/** + * test that the proper names and variable values are set by Scaffold + * + * @return void + */ + public function testScaffoldVariableSetting() { + $params = array( + 'plugin' => null, + 'pass' => array(), + 'form' => array(), + 'named' => array(), + 'url' => array('url' => 'admin/scaffold_mock/edit'), + 'controller' => 'scaffold_mock', + 'action' => 'admin_edit', + 'admin' => true, + ); + $this->Controller->request->base = ''; + $this->Controller->request->webroot = '/'; + $this->Controller->request->here = '/admin/scaffold_mock/edit'; + $this->Controller->request->addParams($params); + + //set router. + Router::setRequestInfo($this->Controller->request); + + $this->Controller->constructClasses(); + $Scaffold = new TestScaffoldMock($this->Controller, $this->Controller->request); + $result = $Scaffold->controller->viewVars; + + $this->assertEquals('Scaffold :: Admin Edit :: Scaffold Mock', $result['title_for_layout']); + $this->assertEquals('Scaffold Mock', $result['singularHumanName']); + $this->assertEquals('Scaffold Mock', $result['pluralHumanName']); + $this->assertEquals('ScaffoldMock', $result['modelClass']); + $this->assertEquals('id', $result['primaryKey']); + $this->assertEquals('title', $result['displayField']); + $this->assertEquals('scaffoldMock', $result['singularVar']); + $this->assertEquals('scaffoldMock', $result['pluralVar']); + $this->assertEquals(array('id', 'user_id', 'title', 'body', 'published', 'created', 'updated'), $result['scaffoldFields']); + } + +/** + * test that Scaffold overrides the view property even if its set to 'Theme' + * + * @return void + */ + public function testScaffoldChangingViewProperty() { + $this->Controller->action = 'edit'; + $this->Controller->theme = 'TestTheme'; + $this->Controller->viewClass = 'Theme'; + $this->Controller->constructClasses(); + $Scaffold = new TestScaffoldMock($this->Controller, $this->Controller->request); + + $this->assertEquals('Scaffold', $this->Controller->viewClass); + } + +/** + * test that scaffold outputs flash messages when sessions are unset. + * + * @return void + */ + public function testScaffoldFlashMessages() { + $params = array( + 'plugin' => null, + 'pass' => array(1), + 'form' => array(), + 'named' => array(), + 'url' => array('url' => 'scaffold_mock'), + 'controller' => 'scaffold_mock', + 'action' => 'edit', + ); + $this->Controller->request->base = ''; + $this->Controller->request->webroot = '/'; + $this->Controller->request->here = '/scaffold_mock/edit'; + $this->Controller->request->addParams($params); + + //set router. + Router::reload(); + Router::setRequestInfo($this->Controller->request); + $this->Controller->request->data = array( + 'ScaffoldMock' => array( + 'id' => 1, + 'title' => 'New title', + 'body' => 'new body' + ) + ); + $this->Controller->constructClasses(); + unset($this->Controller->Session); + + ob_start(); + new Scaffold($this->Controller, $this->Controller->request); + $this->Controller->response->send(); + $result = ob_get_clean(); + $this->assertRegExp('/Scaffold Mock has been updated/', $result); + } + +/** + * test that habtm relationship keys get added to scaffoldFields. + * + * @return void + */ + public function testHabtmFieldAdditionWithScaffoldForm() { + CakePlugin::unload(); + $params = array( + 'plugin' => null, + 'pass' => array(1), + 'form' => array(), + 'named' => array(), + 'url' => array('url' => 'scaffold_mock'), + 'controller' => 'scaffold_mock', + 'action' => 'edit', + ); + $this->Controller->request->base = ''; + $this->Controller->request->webroot = '/'; + $this->Controller->request->here = '/scaffold_mock/edit'; + $this->Controller->request->addParams($params); + + //set router. + Router::reload(); + Router::setRequestInfo($this->Controller->request); + + $this->Controller->constructClasses(); + ob_start(); + $Scaffold = new Scaffold($this->Controller, $this->Controller->request); + $this->Controller->response->send(); + $result = ob_get_clean(); + $this->assertRegExp('/name="data\[ScaffoldTag\]\[ScaffoldTag\]"/', $result); + + $result = $Scaffold->controller->viewVars; + $this->assertEquals(array('id', 'user_id', 'title', 'body', 'published', 'created', 'updated', 'ScaffoldTag'), $result['scaffoldFields']); + } + +/** + * test that the proper names and variable values are set by Scaffold + * + * @return void + */ + public function testEditScaffoldWithScaffoldFields() { + $request = new CakeRequest(null, false); + $this->Controller = new ScaffoldMockControllerWithFields($request); + $this->Controller->response = $this->getMock('CakeResponse', array('_sendHeader')); + + $params = array( + 'plugin' => null, + 'pass' => array(1), + 'form' => array(), + 'named' => array(), + 'url' => array('url' => 'scaffold_mock/edit'), + 'controller' => 'scaffold_mock', + 'action' => 'edit', + ); + $this->Controller->request->base = ''; + $this->Controller->request->webroot = '/'; + $this->Controller->request->here = '/scaffold_mock/edit'; + $this->Controller->request->addParams($params); + + //set router. + Router::reload(); + Router::setRequestInfo($this->Controller->request); + + $this->Controller->constructClasses(); + ob_start(); + new Scaffold($this->Controller, $this->Controller->request); + $this->Controller->response->send(); + $result = ob_get_clean(); + + $this->assertNotRegExp('/textarea name="data\[ScaffoldMock\]\[body\]" cols="30" rows="6" id="ScaffoldMockBody"/', $result); + } + +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Core/AppTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Core/AppTest.php new file mode 100644 index 0000000..3b6cef5 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Core/AppTest.php @@ -0,0 +1,851 @@ +assertEquals($expected, $old); + + App::build(array('Model' => array('/path/to/models/'))); + $new = App::path('Model'); + $expected = array( + '/path/to/models/', + APP . 'Model' . DS + ); + $this->assertEquals($expected, $new); + + App::build(); + App::build(array('Model' => array('/path/to/models/')), App::PREPEND); + $new = App::path('Model'); + $expected = array( + '/path/to/models/', + APP . 'Model' . DS + ); + $this->assertEquals($expected, $new); + + App::build(); + App::build(array('Model' => array('/path/to/models/')), App::APPEND); + $new = App::path('Model'); + $expected = array( + APP . 'Model' . DS, + '/path/to/models/' + ); + $this->assertEquals($expected, $new); + + App::build(); + App::build(array( + 'Model' => array('/path/to/models/'), + 'Controller' => array('/path/to/controllers/'), + ), App::APPEND); + $new = App::path('Model'); + $expected = array( + APP . 'Model' . DS, + '/path/to/models/' + ); + $this->assertEquals($expected, $new); + $new = App::path('Controller'); + $expected = array( + APP . 'Controller' . DS, + '/path/to/controllers/' + ); + $this->assertEquals($expected, $new); + + App::build(); //reset defaults + $defaults = App::path('Model'); + $this->assertEquals($old, $defaults); + } + +/** + * tests that it is possible to set up paths using the cake 1.3 notation for them (models, behaviors, controllers...) + * + * @return void + */ + public function testCompatibleBuild() { + $old = App::path('models'); + $expected = array( + APP . 'Model' . DS + ); + $this->assertEquals($expected, $old); + + App::build(array('models' => array('/path/to/models/'))); + + $new = App::path('models'); + + $expected = array( + '/path/to/models/', + APP . 'Model' . DS + ); + $this->assertEquals($expected, $new); + $this->assertEquals($expected, App::path('Model')); + + App::build(array('datasources' => array('/path/to/datasources/'))); + $expected = array( + '/path/to/datasources/', + APP . 'Model' . DS . 'Datasource' . DS + ); + $result = App::path('datasources'); + $this->assertEquals($expected, $result); + $this->assertEquals($expected, App::path('Model/Datasource')); + + App::build(array('behaviors' => array('/path/to/behaviors/'))); + $expected = array( + '/path/to/behaviors/', + APP . 'Model' . DS . 'Behavior' . DS + ); + $result = App::path('behaviors'); + $this->assertEquals($expected, $result); + $this->assertEquals($expected, App::path('Model/Behavior')); + + App::build(array('controllers' => array('/path/to/controllers/'))); + $expected = array( + '/path/to/controllers/', + APP . 'Controller' . DS + ); + $result = App::path('controllers'); + $this->assertEquals($expected, $result); + $this->assertEquals($expected, App::path('Controller')); + + App::build(array('components' => array('/path/to/components/'))); + $expected = array( + '/path/to/components/', + APP . 'Controller' . DS . 'Component' . DS + ); + $result = App::path('components'); + $this->assertEquals($expected, $result); + $this->assertEquals($expected, App::path('Controller/Component')); + + App::build(array('views' => array('/path/to/views/'))); + $expected = array( + '/path/to/views/', + APP . 'View' . DS + ); + $result = App::path('views'); + $this->assertEquals($expected, $result); + $this->assertEquals($expected, App::path('View')); + + App::build(array('helpers' => array('/path/to/helpers/'))); + $expected = array( + '/path/to/helpers/', + APP . 'View' . DS . 'Helper' . DS + ); + $result = App::path('helpers'); + $this->assertEquals($expected, $result); + $this->assertEquals($expected, App::path('View/Helper')); + + App::build(array('shells' => array('/path/to/shells/'))); + $expected = array( + '/path/to/shells/', + APP . 'Console' . DS . 'Command' . DS + ); + $result = App::path('shells'); + $this->assertEquals($expected, $result); + $this->assertEquals($expected, App::path('Console/Command')); + + App::build(); //reset defaults + $defaults = App::path('Model'); + $this->assertEquals($old, $defaults); + } + +/** + * test package build() with App::REGISTER. + * + * @return void + */ + public function testBuildPackage() { + $pluginPaths = array( + '/foo/bar', + APP . 'Plugin' . DS, + dirname(dirname(CAKE)) . DS . 'plugins' . DS + ); + App::build(array( + 'Plugin' => array( + '/foo/bar' + ) + )); + $result = App::path('Plugin'); + $this->assertEquals($pluginPaths, $result); + + $paths = App::path('Service'); + $this->assertEquals(array(), $paths); + + App::build(array( + 'Service' => array( + '%s' . 'Service' . DS, + ), + ), App::REGISTER); + + $expected = array( + APP . 'Service' . DS, + ); + $result = App::path('Service'); + $this->assertEquals($expected, $result); + + //Ensure new paths registered for other packages are not affected + $result = App::path('Plugin'); + $this->assertEquals($pluginPaths, $result); + + App::build(); + $paths = App::path('Service'); + $this->assertEquals(array(), $paths); + } + +/** + * test path() with a plugin. + * + * @return void + */ + public function testPathWithPlugins() { + $basepath = CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS; + App::build(array( + 'Plugin' => array($basepath), + )); + CakePlugin::load('TestPlugin'); + + $result = App::path('Vendor', 'TestPlugin'); + $this->assertEquals($basepath . 'TestPlugin' . DS . 'Vendor' . DS, $result[0]); + } + +/** + * testBuildWithReset method + * + * @return void + */ + public function testBuildWithReset() { + $old = App::path('Model'); + $expected = array( + APP . 'Model' . DS + ); + $this->assertEquals($expected, $old); + + App::build(array('Model' => array('/path/to/models/')), App::RESET); + + $new = App::path('Model'); + + $expected = array( + '/path/to/models/' + ); + $this->assertEquals($expected, $new); + + App::build(); //reset defaults + $defaults = App::path('Model'); + $this->assertEquals($old, $defaults); + } + +/** + * testCore method + * + * @return void + */ + public function testCore() { + $model = App::core('Model'); + $this->assertEquals(array(CAKE . 'Model' . DS), $model); + + $view = App::core('View'); + $this->assertEquals(array(CAKE . 'View' . DS), $view); + + $controller = App::core('Controller'); + $this->assertEquals(array(CAKE . 'Controller' . DS), $controller); + + $component = App::core('Controller/Component'); + $this->assertEquals(array(CAKE . 'Controller' . DS . 'Component' . DS), str_replace('/', DS, $component)); + + $auth = App::core('Controller/Component/Auth'); + $this->assertEquals(array(CAKE . 'Controller' . DS . 'Component' . DS . 'Auth' . DS), str_replace('/', DS, $auth)); + + $datasource = App::core('Model/Datasource'); + $this->assertEquals(array(CAKE . 'Model' . DS . 'Datasource' . DS), str_replace('/', DS, $datasource)); + } + +/** + * testListObjects method + * + * @return void + */ + public function testListObjects() { + $result = App::objects('class', CAKE . 'Routing', false); + $this->assertTrue(in_array('Dispatcher', $result)); + $this->assertTrue(in_array('Router', $result)); + + App::build(array( + 'Model/Behavior' => App::core('Model/Behavior'), + 'Controller' => App::core('Controller'), + 'Controller/Component' => App::core('Controller/Component'), + 'View' => App::core('View'), + 'Model' => App::core('Model'), + 'View/Helper' => App::core('View/Helper'), + ), App::RESET); + $result = App::objects('behavior', null, false); + $this->assertTrue(in_array('TreeBehavior', $result)); + $result = App::objects('Model/Behavior', null, false); + $this->assertTrue(in_array('TreeBehavior', $result)); + + $result = App::objects('component', null, false); + $this->assertTrue(in_array('AuthComponent', $result)); + $result = App::objects('Controller/Component', null, false); + $this->assertTrue(in_array('AuthComponent', $result)); + + $result = App::objects('view', null, false); + $this->assertTrue(in_array('MediaView', $result)); + $result = App::objects('View', null, false); + $this->assertTrue(in_array('MediaView', $result)); + + $result = App::objects('helper', null, false); + $this->assertTrue(in_array('HtmlHelper', $result)); + $result = App::objects('View/Helper', null, false); + $this->assertTrue(in_array('HtmlHelper', $result)); + + $result = App::objects('model', null, false); + $this->assertTrue(in_array('AcoAction', $result)); + $result = App::objects('Model', null, false); + $this->assertTrue(in_array('AcoAction', $result)); + + $result = App::objects('file'); + $this->assertFalse($result); + + $result = App::objects('file', 'non_existing_configure'); + $expected = array(); + $this->assertEquals($expected, $result); + + $result = App::objects('NonExistingType'); + $this->assertEquals(array(), $result); + + App::build(array( + 'plugins' => array( + CAKE . 'Test' . DS . 'test_app' . DS . 'Lib' . DS + ) + )); + $result = App::objects('plugin', null, false); + $this->assertTrue(in_array('Cache', $result)); + $this->assertTrue(in_array('Log', $result)); + + App::build(); + } + +/** + * Make sure that .svn and friends are excluded from App::objects('plugin') + */ + public function testListObjectsIgnoreDotDirectories() { + $path = CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS; + + $this->skipIf(!is_writable($path), $path . ' is not writable.'); + + App::build(array( + 'plugins' => array($path) + ), App::RESET); + mkdir($path . '.svn'); + $result = App::objects('plugin', null, false); + rmdir($path . '.svn'); + + $this->assertNotContains('.svn', $result); + } + +/** + * Tests listing objects within a plugin + * + * @return void + */ + public function testListObjectsInPlugin() { + App::build(array( + 'Model' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Model' . DS), + 'plugins' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS) + ), App::RESET); + CakePlugin::load(array('TestPlugin', 'TestPluginTwo')); + + $result = App::objects('TestPlugin.model'); + $this->assertTrue(in_array('TestPluginPost', $result)); + $result = App::objects('TestPlugin.Model'); + $this->assertTrue(in_array('TestPluginPost', $result)); + + $result = App::objects('TestPlugin.behavior'); + $this->assertTrue(in_array('TestPluginPersisterOneBehavior', $result)); + $result = App::objects('TestPlugin.Model/Behavior'); + $this->assertTrue(in_array('TestPluginPersisterOneBehavior', $result)); + + $result = App::objects('TestPlugin.helper'); + $expected = array('OtherHelperHelper', 'PluggedHelperHelper', 'TestPluginAppHelper'); + $this->assertEquals($expected, $result); + $result = App::objects('TestPlugin.View/Helper'); + $expected = array('OtherHelperHelper', 'PluggedHelperHelper', 'TestPluginAppHelper'); + $this->assertEquals($expected, $result); + + $result = App::objects('TestPlugin.component'); + $this->assertTrue(in_array('OtherComponent', $result)); + $result = App::objects('TestPlugin.Controller/Component'); + $this->assertTrue(in_array('OtherComponent', $result)); + + $result = App::objects('TestPluginTwo.behavior'); + $this->assertEquals(array(), $result); + $result = App::objects('TestPluginTwo.Model/Behavior'); + $this->assertEquals(array(), $result); + + $result = App::objects('model', null, false); + $this->assertTrue(in_array('Comment', $result)); + $this->assertTrue(in_array('Post', $result)); + + $result = App::objects('Model', null, false); + $this->assertTrue(in_array('Comment', $result)); + $this->assertTrue(in_array('Post', $result)); + + App::build(); + } + +/** + * test that pluginPath can find paths for plugins. + * + * @return void + */ + public function testPluginPath() { + App::build(array( + 'plugins' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS) + )); + CakePlugin::load(array('TestPlugin', 'TestPluginTwo')); + + $path = App::pluginPath('TestPlugin'); + $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS . 'TestPlugin' . DS; + $this->assertEquals($expected, $path); + + $path = App::pluginPath('TestPluginTwo'); + $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS . 'TestPluginTwo' . DS; + $this->assertEquals($expected, $path); + App::build(); + } + +/** + * test that themePath can find paths for themes. + * + * @return void + */ + public function testThemePath() { + App::build(array( + 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS) + )); + $path = App::themePath('test_theme'); + $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS . 'Themed' . DS . 'TestTheme' . DS; + $this->assertEquals($expected, $path); + + $path = App::themePath('TestTheme'); + $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS . 'Themed' . DS . 'TestTheme' . DS; + $this->assertEquals($expected, $path); + + App::build(); + } + +/** + * testClassLoading method + * + * @return void + */ + public function testClassLoading() { + $file = App::import('Model', 'Model', false); + $this->assertTrue($file); + $this->assertTrue(class_exists('Model')); + + $file = App::import('Controller', 'Controller', false); + $this->assertTrue($file); + $this->assertTrue(class_exists('Controller')); + + $file = App::import('Component', 'Auth', false); + $this->assertTrue($file); + $this->assertTrue(class_exists('AuthComponent')); + + $file = App::import('Shell', 'Shell', false); + $this->assertTrue($file); + $this->assertTrue(class_exists('Shell')); + + $file = App::import('Configure', 'PhpReader'); + $this->assertTrue($file); + $this->assertTrue(class_exists('PhpReader')); + + $file = App::import('Model', 'SomeRandomModelThatDoesNotExist', false); + $this->assertFalse($file); + + $file = App::import('Model', 'AppModel', false); + $this->assertTrue($file); + $this->assertTrue(class_exists('AppModel')); + + $file = App::import('WrongType', null, true, array(), ''); + $this->assertFalse($file); + + $file = App::import('Model', 'NonExistingPlugin.NonExistingModel', false); + $this->assertFalse($file); + + $file = App::import('Model', array('NonExistingPlugin.NonExistingModel'), false); + $this->assertFalse($file); + + if (!class_exists('AppController', false)) { + $classes = array_flip(get_declared_classes()); + + $this->assertFalse(isset($classes['PagesController'])); + $this->assertFalse(isset($classes['AppController'])); + + $file = App::import('Controller', 'Pages'); + $this->assertTrue($file); + $this->assertTrue(class_exists('PagesController')); + + $classes = array_flip(get_declared_classes()); + + $this->assertTrue(isset($classes['PagesController'])); + $this->assertTrue(isset($classes['AppController'])); + + $file = App::import('Behavior', 'Containable'); + $this->assertTrue($file); + $this->assertTrue(class_exists('ContainableBehavior')); + + $file = App::import('Component', 'RequestHandler'); + $this->assertTrue($file); + $this->assertTrue(class_exists('RequestHandlerComponent')); + + $file = App::import('Helper', 'Form'); + $this->assertTrue($file); + $this->assertTrue(class_exists('FormHelper')); + + $file = App::import('Model', 'NonExistingModel'); + $this->assertFalse($file); + + $file = App::import('Datasource', 'DboSource'); + $this->assertTrue($file); + $this->assertTrue(class_exists('DboSource')); + } + App::build(); + } + +/** + * test import() with plugins + * + * @return void + */ + public function testPluginImporting() { + App::build(array( + 'Lib' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Lib' . DS), + 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS) + )); + CakePlugin::load(array('TestPlugin', 'TestPluginTwo')); + + $result = App::import('Controller', 'TestPlugin.Tests'); + $this->assertTrue($result); + $this->assertTrue(class_exists('TestPluginAppController')); + $this->assertTrue(class_exists('TestsController')); + + $result = App::import('Lib', 'TestPlugin.TestPluginLibrary'); + $this->assertTrue($result); + $this->assertTrue(class_exists('TestPluginLibrary')); + + $result = App::import('Lib', 'Library'); + $this->assertTrue($result); + $this->assertTrue(class_exists('Library')); + + $result = App::import('Helper', 'TestPlugin.OtherHelper'); + $this->assertTrue($result); + $this->assertTrue(class_exists('OtherHelperHelper')); + + $result = App::import('Helper', 'TestPlugin.TestPluginApp'); + $this->assertTrue($result); + $this->assertTrue(class_exists('TestPluginAppHelper')); + + $result = App::import('Datasource', 'TestPlugin.TestSource'); + $this->assertTrue($result); + $this->assertTrue(class_exists('TestSource')); + + App::uses('ExampleExample', 'TestPlugin.Vendor/Example'); + $this->assertTrue(class_exists('ExampleExample')); + + App::build(); + } + +/** + * test that building helper paths actually works. + * + * @return void + * @link http://cakephp.lighthouseapp.com/projects/42648/tickets/410 + */ + public function testImportingHelpersFromAlternatePaths() { + $this->assertFalse(class_exists('BananaHelper', false), 'BananaHelper exists, cannot test importing it.'); + App::build(array( + 'View/Helper' => array( + CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS . 'Helper' . DS + ) + )); + $this->assertFalse(class_exists('BananaHelper', false), 'BananaHelper exists, cannot test importing it.'); + App::import('Helper', 'Banana'); + $this->assertTrue(class_exists('BananaHelper', false), 'BananaHelper was not loaded.'); + + App::build(); + } + +/** + * testFileLoading method + * + * @return void + */ + public function testFileLoading() { + $file = App::import('File', 'RealFile', false, array(), CAKE . 'Config' . DS . 'config.php'); + $this->assertTrue($file); + + $file = App::import('File', 'NoFile', false, array(), CAKE . 'Config' . DS . 'cake' . DS . 'config.php'); + $this->assertFalse($file); + } + +/** + * testFileLoadingWithArray method + * + * @return void + */ + public function testFileLoadingWithArray() { + $type = array( + 'type' => 'File', + 'name' => 'SomeName', + 'parent' => false, + 'file' => CAKE . DS . 'Config' . DS . 'config.php' + ); + $file = App::import($type); + $this->assertTrue($file); + + $type = array( + 'type' => 'File', + 'name' => 'NoFile', + 'parent' => false, + 'file' => CAKE . 'Config' . DS . 'cake' . DS . 'config.php' + ); + $file = App::import($type); + $this->assertFalse($file); + } + +/** + * testFileLoadingReturnValue method + * + * @return void + */ + public function testFileLoadingReturnValue() { + $file = App::import('File', 'Name', false, array(), CAKE . 'Config' . DS . 'config.php', true); + $this->assertTrue(!empty($file)); + + $this->assertTrue(isset($file['Cake.version'])); + + $type = array( + 'type' => 'File', + 'name' => 'OtherName', + 'parent' => false, + 'file' => CAKE . 'Config' . DS . 'config.php', 'return' => true + ); + $file = App::import($type); + $this->assertTrue(!empty($file)); + + $this->assertTrue(isset($file['Cake.version'])); + } + +/** + * testLoadingWithSearch method + * + * @return void + */ + public function testLoadingWithSearch() { + $file = App::import('File', 'NewName', false, array(CAKE . 'Config' . DS), 'config.php'); + $this->assertTrue($file); + + $file = App::import('File', 'AnotherNewName', false, array(CAKE), 'config.php'); + $this->assertFalse($file); + } + +/** + * testLoadingWithSearchArray method + * + * @return void + */ + public function testLoadingWithSearchArray() { + $type = array( + 'type' => 'File', + 'name' => 'RandomName', + 'parent' => false, + 'file' => 'config.php', + 'search' => array(CAKE . 'Config' . DS) + ); + $file = App::import($type); + $this->assertTrue($file); + + $type = array( + 'type' => 'File', + 'name' => 'AnotherRandomName', + 'parent' => false, + 'file' => 'config.php', + 'search' => array(CAKE) + ); + $file = App::import($type); + $this->assertFalse($file); + } + +/** + * testMultipleLoading method + * + * @return void + */ + public function testMultipleLoading() { + if (class_exists('PersisterOne', false) || class_exists('PersisterTwo', false)) { + $this->markTestSkipped('Cannot test loading of classes that exist.'); + } + App::build(array( + 'Model' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Model' . DS) + )); + $toLoad = array('PersisterOne', 'PersisterTwo'); + $load = App::import('Model', $toLoad); + $this->assertTrue($load); + + $classes = array_flip(get_declared_classes()); + + $this->assertTrue(isset($classes['PersisterOne'])); + $this->assertTrue(isset($classes['PersisterTwo'])); + + $load = App::import('Model', array('PersisterOne', 'SomeNotFoundClass', 'PersisterTwo')); + $this->assertFalse($load); + } + + public function testLoadingVendor() { + App::build(array( + 'plugins' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS), + 'vendors' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Vendor' . DS), + ), App::RESET); + CakePlugin::load(array('TestPlugin', 'TestPluginTwo')); + + ob_start(); + $result = App::import('Vendor', 'css/TestAsset', array('ext' => 'css')); + $text = ob_get_clean(); + $this->assertTrue($result); + $this->assertEquals('this is the test asset css file', $text); + + $result = App::import('Vendor', 'TestPlugin.sample/SamplePlugin'); + $this->assertTrue($result); + $this->assertTrue(class_exists('SamplePluginClassTestName')); + + $result = App::import('Vendor', 'sample/ConfigureTestVendorSample'); + $this->assertTrue($result); + $this->assertTrue(class_exists('ConfigureTestVendorSample')); + + ob_start(); + $result = App::import('Vendor', 'SomeNameInSubfolder', array('file' => 'somename/some.name.php')); + $text = ob_get_clean(); + $this->assertTrue($result); + $this->assertEquals('This is a file with dot in file name', $text); + + ob_start(); + $result = App::import('Vendor', 'TestHello', array('file' => 'Test' . DS . 'hello.php')); + $text = ob_get_clean(); + $this->assertTrue($result); + $this->assertEquals('This is the hello.php file in Test directory', $text); + + ob_start(); + $result = App::import('Vendor', 'MyTest', array('file' => 'Test' . DS . 'MyTest.php')); + $text = ob_get_clean(); + $this->assertTrue($result); + $this->assertEquals('This is the MyTest.php file', $text); + + ob_start(); + $result = App::import('Vendor', 'Welcome'); + $text = ob_get_clean(); + $this->assertTrue($result); + $this->assertEquals('This is the welcome.php file in vendors directory', $text); + + ob_start(); + $result = App::import('Vendor', 'TestPlugin.Welcome'); + $text = ob_get_clean(); + $this->assertTrue($result); + $this->assertEquals('This is the welcome.php file in test_plugin/vendors directory', $text); + } + +/** + * Tests that the automatic class loader will also find in "libs" folder for both + * app and plugins if it does not find the class in other configured paths + * + */ + public function testLoadClassInLibs() { + App::build(array( + 'libs' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Lib' . DS), + 'plugins' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS) + ), App::RESET); + CakePlugin::load(array('TestPlugin', 'TestPluginTwo')); + + $this->assertFalse(class_exists('CustomLibClass', false)); + App::uses('CustomLibClass', 'TestPlugin.Custom/Package'); + $this->assertTrue(class_exists('CustomLibClass')); + + $this->assertFalse(class_exists('TestUtilityClass', false)); + App::uses('TestUtilityClass', 'Utility'); + $this->assertTrue(class_exists('CustomLibClass')); + } + +/** + * Tests that App::location() returns the defined path for a class + * + * @return void + */ + public function testClassLocation() { + App::uses('MyCustomClass', 'MyPackage/Name'); + $this->assertEquals('MyPackage/Name', App::location('MyCustomClass')); + } + +/** + * Test that paths() works. + * + * @return void + */ + public function testPaths() { + $result = App::paths(); + $this->assertArrayHasKey('Plugin', $result); + $this->assertArrayHasKey('Controller', $result); + $this->assertArrayHasKey('Controller/Component', $result); + } + +/** + * Proves that it is possible to load plugin libraries in top + * level Lib dir for plugins + * + * @return void + */ + public function testPluginLibClasses() { + App::build(array( + 'plugins' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS) + ), App::RESET); + CakePlugin::load(array('TestPlugin', 'TestPluginTwo')); + $this->assertFalse(class_exists('TestPluginOtherLibrary', false)); + App::uses('TestPluginOtherLibrary', 'TestPlugin.Lib'); + $this->assertTrue(class_exists('TestPluginOtherLibrary')); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Core/CakePluginTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Core/CakePluginTest.php new file mode 100644 index 0000000..893e671 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Core/CakePluginTest.php @@ -0,0 +1,268 @@ + array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS) + ), App::RESET); + App::objects('plugins', null, false); + } + +/** + * Reverts the changes done to the environment while testing + * + * @return void + */ + public function tearDown() { + parent::tearDown(); + CakePlugin::unload(); + } + +/** + * Tests loading a single plugin + * + * @return void + */ + public function testLoadSingle() { + CakePlugin::unload(); + CakePlugin::load('TestPlugin'); + $expected = array('TestPlugin'); + $this->assertEquals($expected, CakePlugin::loaded()); + } + +/** + * Tests unloading plugins + * + * @return void + */ + public function testUnload() { + CakePlugin::load('TestPlugin'); + $expected = array('TestPlugin'); + $this->assertEquals($expected, CakePlugin::loaded()); + + CakePlugin::unload('TestPlugin'); + $this->assertEquals(array(), CakePlugin::loaded()); + + CakePlugin::load('TestPlugin'); + $expected = array('TestPlugin'); + $this->assertEquals($expected, CakePlugin::loaded()); + + CakePlugin::unload('TestFakePlugin'); + $this->assertEquals($expected, CakePlugin::loaded()); + } + +/** + * Tests loading a plugin and its bootstrap file + * + * @return void + */ + public function testLoadSingleWithBootstrap() { + CakePlugin::load('TestPlugin', array('bootstrap' => true)); + $this->assertTrue(CakePlugin::loaded('TestPlugin')); + $this->assertEquals('loaded plugin bootstrap', Configure::read('CakePluginTest.test_plugin.bootstrap')); + } + +/** + * Tests loading a plugin with bootstrap file and routes file + * + * @return void + */ + public function testLoadSingleWithBootstrapAndRoutes() { + CakePlugin::load('TestPlugin', array('bootstrap' => true, 'routes' => true)); + $this->assertTrue(CakePlugin::loaded('TestPlugin')); + $this->assertEquals('loaded plugin bootstrap', Configure::read('CakePluginTest.test_plugin.bootstrap')); + + CakePlugin::routes(); + $this->assertEquals('loaded plugin routes', Configure::read('CakePluginTest.test_plugin.routes')); + } + +/** + * Tests loading multiple plugins at once + * + * @return void + */ + public function testLoadMultiple() { + CakePlugin::load(array('TestPlugin', 'TestPluginTwo')); + $expected = array('TestPlugin', 'TestPluginTwo'); + $this->assertEquals($expected, CakePlugin::loaded()); + } + +/** + * Tests loading multiple plugins and their bootstrap files + * + * @return void + */ + public function testLoadMultipleWithDefaults() { + CakePlugin::load(array('TestPlugin', 'TestPluginTwo'), array('bootstrap' => true, 'routes' => false)); + $expected = array('TestPlugin', 'TestPluginTwo'); + $this->assertEquals($expected, CakePlugin::loaded()); + $this->assertEquals('loaded plugin bootstrap', Configure::read('CakePluginTest.test_plugin.bootstrap')); + $this->assertEquals('loaded plugin two bootstrap', Configure::read('CakePluginTest.test_plugin_two.bootstrap')); + } + +/** + * Tests loading multiple plugins with default loading params and some overrides + * + * @return void + */ + public function testLoadMultipleWithDefaultsAndOverride() { + CakePlugin::load( + array('TestPlugin', 'TestPluginTwo' => array('routes' => false)), + array('bootstrap' => true, 'routes' => true) + ); + $expected = array('TestPlugin', 'TestPluginTwo'); + $this->assertEquals($expected, CakePlugin::loaded()); + $this->assertEquals('loaded plugin bootstrap', Configure::read('CakePluginTest.test_plugin.bootstrap')); + $this->assertEquals(null, Configure::read('CakePluginTest.test_plugin_two.bootstrap')); + } + +/** + * Tests that it is possible to load multiple bootstrap files at once + * + * @return void + */ + public function testMultipleBootstrapFiles() { + CakePlugin::load('TestPlugin', array('bootstrap' => array('bootstrap', 'custom_config'))); + $this->assertTrue(CakePlugin::loaded('TestPlugin')); + $this->assertEquals('loaded plugin bootstrap', Configure::read('CakePluginTest.test_plugin.bootstrap')); + } + +/** + * Tests that it is possible to load plugin bootstrap by calling a callback function + * + * @return void + */ + public function testCallbackBootstrap() { + CakePlugin::load('TestPlugin', array('bootstrap' => array($this, 'pluginBootstrap'))); + $this->assertTrue(CakePlugin::loaded('TestPlugin')); + $this->assertEquals('called plugin bootstrap callback', Configure::read('CakePluginTest.test_plugin.bootstrap')); + } + +/** + * Tests that loading a missing routes file throws a warning + * + * @return void + * @expectedException PHPUNIT_FRAMEWORK_ERROR_WARNING + */ + public function testLoadMultipleWithDefaultsMissingFile() { + CakePlugin::load(array('TestPlugin', 'TestPluginTwo'), array('bootstrap' => true, 'routes' => true)); + CakePlugin::routes(); + } + +/** + * Tests that CakePlugin::load() throws an exception on unknown plugin + * + * @return void + * @expectedException MissingPluginException + */ + public function testLoadNotFound() { + CakePlugin::load('MissingPlugin'); + } + +/** + * Tests that CakePlugin::path() returns the correct path for the loaded plugins + * + * @return void + */ + public function testPath() { + CakePlugin::load(array('TestPlugin', 'TestPluginTwo')); + $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS . 'TestPlugin' . DS; + $this->assertEquals(CakePlugin::path('TestPlugin'), $expected); + + $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS . 'TestPluginTwo' . DS; + $this->assertEquals(CakePlugin::path('TestPluginTwo'), $expected); + } + +/** + * Tests that CakePlugin::path() throws an exception on unknown plugin + * + * @return void + * @expectedException MissingPluginException + */ + public function testPathNotFound() { + CakePlugin::path('TestPlugin'); + } + +/** + * Tests that CakePlugin::loadAll() will load all plugins in the configured folder + * + * @return void + */ + public function testLoadAll() { + CakePlugin::loadAll(); + $expected = array('PluginJs', 'TestPlugin', 'TestPluginTwo'); + $this->assertEquals($expected, CakePlugin::loaded()); + } + +/** + * Tests that CakePlugin::loadAll() will load all plugins in the configured folder with bootstrap loading + * + * @return void + */ + public function testLoadAllWithDefaults() { + $defaults = array('bootstrap' => true); + CakePlugin::loadAll(array($defaults)); + $expected = array('PluginJs', 'TestPlugin', 'TestPluginTwo'); + $this->assertEquals($expected, CakePlugin::loaded()); + $this->assertEquals('loaded js plugin bootstrap', Configure::read('CakePluginTest.js_plugin.bootstrap')); + $this->assertEquals('loaded plugin bootstrap', Configure::read('CakePluginTest.test_plugin.bootstrap')); + $this->assertEquals('loaded plugin two bootstrap', Configure::read('CakePluginTest.test_plugin_two.bootstrap')); + } + +/** + * Tests that CakePlugin::loadAll() will load all plugins in the configured folder wit defaults + * and overrides for a plugin + * + * @return void + */ + public function testLoadAllWithDefaultsAndOverride() { + CakePlugin::loadAll(array(array('bootstrap' => true), 'TestPlugin' => array('routes' => true))); + CakePlugin::routes(); + + $expected = array('PluginJs', 'TestPlugin', 'TestPluginTwo'); + $this->assertEquals($expected, CakePlugin::loaded()); + $this->assertEquals('loaded js plugin bootstrap', Configure::read('CakePluginTest.js_plugin.bootstrap')); + $this->assertEquals('loaded plugin routes', Configure::read('CakePluginTest.test_plugin.routes')); + $this->assertEquals(null, Configure::read('CakePluginTest.test_plugin.bootstrap')); + $this->assertEquals('loaded plugin two bootstrap', Configure::read('CakePluginTest.test_plugin_two.bootstrap')); + } + +/** + * Auxiliary function to test plugin bootstrap callbacks + * + * @return void + */ + public function pluginBootstrap() { + Configure::write('CakePluginTest.test_plugin.bootstrap', 'called plugin bootstrap callback'); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Core/ConfigureTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Core/ConfigureTest.php new file mode 100644 index 0000000..7351f83 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Core/ConfigureTest.php @@ -0,0 +1,408 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Core + * @since CakePHP(tm) v 1.2.0.5432 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ +App::uses('PhpReader', 'Configure'); + +/** + * ConfigureTest + * + * @package Cake.Test.Case.Core + */ +class ConfigureTest extends CakeTestCase { + +/** + * setUp method + * + * @return void + */ + public function setUp() { + parent::setUp(); + Configure::write('Cache.disable', true); + App::build(); + App::objects('plugin', null, true); + } + +/** + * tearDown method + * + * @return void + */ + public function tearDown() { + parent::tearDown(); + if (file_exists(TMP . 'cache' . DS . 'persistent' . DS . 'cake_core_core_paths')) { + unlink(TMP . 'cache' . DS . 'persistent' . DS . 'cake_core_core_paths'); + } + if (file_exists(TMP . 'cache' . DS . 'persistent' . DS . 'cake_core_dir_map')) { + unlink(TMP . 'cache' . DS . 'persistent' . DS . 'cake_core_dir_map'); + } + if (file_exists(TMP . 'cache' . DS . 'persistent' . DS . 'cake_core_file_map')) { + unlink(TMP . 'cache' . DS . 'persistent' . DS . 'cake_core_file_map'); + } + if (file_exists(TMP . 'cache' . DS . 'persistent' . DS . 'cake_core_object_map')) { + unlink(TMP . 'cache' . DS . 'persistent' . DS . 'cake_core_object_map'); + } + if (file_exists(TMP . 'cache' . DS . 'persistent' . DS . 'test.config.php')) { + unlink(TMP . 'cache' . DS . 'persistent' . DS . 'test.config.php'); + } + if (file_exists(TMP . 'cache' . DS . 'persistent' . DS . 'test.php')) { + unlink(TMP . 'cache' . DS . 'persistent' . DS . 'test.php'); + } + Configure::drop('test'); + } + +/** + * testRead method + * + * @return void + */ + public function testRead() { + $expected = 'ok'; + Configure::write('level1.level2.level3_1', $expected); + Configure::write('level1.level2.level3_2', 'something_else'); + $result = Configure::read('level1.level2.level3_1'); + $this->assertEquals($expected, $result); + + $result = Configure::read('level1.level2.level3_2'); + $this->assertEquals('something_else', $result); + + $result = Configure::read('debug'); + $this->assertTrue($result >= 0); + + $result = Configure::read(); + $this->assertTrue(is_array($result)); + $this->assertTrue(isset($result['debug'])); + $this->assertTrue(isset($result['level1'])); + + $result = Configure::read('something_I_just_made_up_now'); + $this->assertEquals(null, $result, 'Missing key should return null.'); + } + +/** + * testWrite method + * + * @return void + */ + public function testWrite() { + $writeResult = Configure::write('SomeName.someKey', 'myvalue'); + $this->assertTrue($writeResult); + $result = Configure::read('SomeName.someKey'); + $this->assertEquals('myvalue', $result); + + $writeResult = Configure::write('SomeName.someKey', null); + $this->assertTrue($writeResult); + $result = Configure::read('SomeName.someKey'); + $this->assertEquals(null, $result); + + $expected = array('One' => array('Two' => array('Three' => array('Four' => array('Five' => 'cool'))))); + $writeResult = Configure::write('Key', $expected); + $this->assertTrue($writeResult); + + $result = Configure::read('Key'); + $this->assertEquals($expected, $result); + + $result = Configure::read('Key.One'); + $this->assertEquals($expected['One'], $result); + + $result = Configure::read('Key.One.Two'); + $this->assertEquals($expected['One']['Two'], $result); + + $result = Configure::read('Key.One.Two.Three.Four.Five'); + $this->assertEquals('cool', $result); + + Configure::write('one.two.three.four', '4'); + $result = Configure::read('one.two.three.four'); + $this->assertEquals('4', $result); + } + +/** + * test setting display_errors with debug. + * + * @return void + */ + public function testDebugSettingDisplayErrors() { + Configure::write('debug', 0); + $result = ini_get('display_errors'); + $this->assertEquals(0, $result); + + Configure::write('debug', 2); + $result = ini_get('display_errors'); + $this->assertEquals(1, $result); + } + +/** + * testDelete method + * + * @return void + */ + public function testDelete() { + Configure::write('SomeName.someKey', 'myvalue'); + $result = Configure::read('SomeName.someKey'); + $this->assertEquals('myvalue', $result); + + Configure::delete('SomeName.someKey'); + $result = Configure::read('SomeName.someKey'); + $this->assertTrue($result === null); + + Configure::write('SomeName', array('someKey' => 'myvalue', 'otherKey' => 'otherValue')); + + $result = Configure::read('SomeName.someKey'); + $this->assertEquals('myvalue', $result); + + $result = Configure::read('SomeName.otherKey'); + $this->assertEquals('otherValue', $result); + + Configure::delete('SomeName'); + + $result = Configure::read('SomeName.someKey'); + $this->assertTrue($result === null); + + $result = Configure::read('SomeName.otherKey'); + $this->assertTrue($result === null); + } + +/** + * testLoad method + * + * @expectedException RuntimeException + * @return void + */ + public function testLoadExceptionOnNonExistantFile() { + Configure::config('test', new PhpReader()); + $result = Configure::load('non_existing_configuration_file', 'test'); + } + +/** + * test load method for default config creation + * + * @return void + */ + public function testLoadDefaultConfig() { + try { + Configure::load('non_existing_configuration_file'); + } catch (Exception $e) { + $result = Configure::configured('default'); + $this->assertTrue($result); + } + } + +/** + * test load with merging + * + * @return void + */ + public function testLoadWithMerge() { + Configure::config('test', new PhpReader(CAKE . 'Test' . DS . 'test_app' . DS . 'Config' . DS)); + + $result = Configure::load('var_test', 'test'); + $this->assertTrue($result); + + $this->assertEquals('value', Configure::read('Read')); + + $result = Configure::load('var_test2', 'test', true); + $this->assertTrue($result); + + $this->assertEquals('value2', Configure::read('Read')); + $this->assertEquals('buried2', Configure::read('Deep.Second.SecondDeepest')); + $this->assertEquals('buried', Configure::read('Deep.Deeper.Deepest')); + $this->assertEquals('Overwrite', Configure::read('TestAcl.classname')); + $this->assertEquals('one', Configure::read('TestAcl.custom')); + } + +/** + * test loading with overwrite + * + * @return void + */ + public function testLoadNoMerge() { + Configure::config('test', new PhpReader(CAKE . 'Test' . DS . 'test_app' . DS . 'Config' . DS)); + + $result = Configure::load('var_test', 'test'); + $this->assertTrue($result); + + $this->assertEquals('value', Configure::read('Read')); + + $result = Configure::load('var_test2', 'test', false); + $this->assertTrue($result); + + $this->assertEquals('value2', Configure::read('Read')); + $this->assertEquals('buried2', Configure::read('Deep.Second.SecondDeepest')); + $this->assertNull(Configure::read('Deep.Deeper.Deepest')); + } + +/** + * testLoad method + * + * @return void + */ + public function testLoadPlugin() { + App::build(array( + 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS) + ), App::RESET); + Configure::config('test', new PhpReader()); + CakePlugin::load('TestPlugin'); + $result = Configure::load('TestPlugin.load', 'test'); + $this->assertTrue($result); + $expected = '/test_app/plugins/test_plugin/config/load.php'; + $config = Configure::read('plugin_load'); + $this->assertEquals($expected, $config); + + $result = Configure::load('TestPlugin.more.load', 'test'); + $this->assertTrue($result); + $expected = '/test_app/plugins/test_plugin/config/more.load.php'; + $config = Configure::read('plugin_more_load'); + $this->assertEquals($expected, $config); + CakePlugin::unload(); + } + +/** + * testStore method + * + * @return void + */ + public function testStoreAndRestore() { + Configure::write('Cache.disable', false); + + Configure::write('Testing', 'yummy'); + $this->assertTrue(Configure::store('store_test', 'default')); + + Configure::delete('Testing'); + $this->assertNull(Configure::read('Testing')); + + Configure::restore('store_test', 'default'); + $this->assertEquals('yummy', Configure::read('Testing')); + + Cache::delete('store_test', 'default'); + } + +/** + * test that store and restore only store/restore the provided data. + * + * @return void + */ + public function testStoreAndRestoreWithData() { + Configure::write('Cache.disable', false); + + Configure::write('testing', 'value'); + Configure::store('store_test', 'default', array('store_test' => 'one')); + Configure::delete('testing'); + $this->assertNull(Configure::read('store_test'), 'Calling store with data shouldn\'t modify runtime.'); + + Configure::restore('store_test', 'default'); + $this->assertEquals('one', Configure::read('store_test')); + $this->assertNull(Configure::read('testing'), 'Values that were not stored are not restored.'); + + Cache::delete('store_test', 'default'); + } + +/** + * testVersion method + * + * @return void + */ + public function testVersion() { + $result = Configure::version(); + $this->assertTrue(version_compare($result, '1.2', '>=')); + } + +/** + * test adding new readers. + * + * @return void + */ + public function testReaderSetup() { + $reader = new PhpReader(); + Configure::config('test', $reader); + $configured = Configure::configured(); + + $this->assertTrue(in_array('test', $configured)); + + $this->assertTrue(Configure::configured('test')); + $this->assertFalse(Configure::configured('fake_garbage')); + + $this->assertTrue(Configure::drop('test')); + $this->assertFalse(Configure::drop('test'), 'dropping things that do not exist should return false.'); + } + +/** + * test reader() throwing exceptions on missing interface. + * + * @expectedException PHPUnit_Framework_Error + * @return void + */ + public function testReaderExceptionOnIncorrectClass() { + $reader = new StdClass(); + Configure::config('test', $reader); + } + +/** + * Test that clear wipes all values. + * + * @return void + */ + public function testClear() { + Configure::write('test', 'value'); + $this->assertTrue(Configure::clear()); + $this->assertNull(Configure::read('debug')); + $this->assertNull(Configure::read('test')); + } + +/** + * @expectedException ConfigureException + */ + public function testDumpNoAdapter() { + Configure::dump(TMP . 'test.php', 'does_not_exist'); + } + +/** + * test dump integrated with the PhpReader. + * + * @return void + */ + public function testDump() { + Configure::config('test_reader', new PhpReader(TMP)); + + $result = Configure::dump('config_test.php', 'test_reader'); + $this->assertTrue($result > 0); + $result = file_get_contents(TMP . 'config_test.php'); + $this->assertContains('assertContains('$config = ', $result); + @unlink(TMP . 'config_test.php'); + } + +/** + * Test dumping only some of the data. + * + * @return + */ + public function testDumpPartial() { + Configure::config('test_reader', new PhpReader(TMP)); + + $result = Configure::dump('config_test.php', 'test_reader', array('Error')); + $this->assertTrue($result > 0); + $result = file_get_contents(TMP . 'config_test.php'); + $this->assertContains('assertContains('$config = ', $result); + $this->assertContains('Error', $result); + $this->assertNotContains('debug', $result); + + @unlink(TMP . 'config_test.php'); + } + +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Core/ObjectTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Core/ObjectTest.php new file mode 100644 index 0000000..222a231 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Core/ObjectTest.php @@ -0,0 +1,673 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Core + * @since CakePHP(tm) v 1.2.0.5432 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ + +App::uses('Object', 'Core'); +App::uses('Router', 'Routing'); +App::uses('Controller', 'Controller'); +App::uses('Model', 'Model'); + +/** + * RequestActionPost class + * + * @package Cake.Test.Case.Core + */ +class RequestActionPost extends CakeTestModel { + +/** + * name property + * + * @var string 'ControllerPost' + */ + public $name = 'RequestActionPost'; + +/** + * useTable property + * + * @var string 'posts' + */ + public $useTable = 'posts'; +} + +/** + * RequestActionController class + * + * @package Cake.Test.Case.Core + */ +class RequestActionController extends Controller { + +/** + * uses property + * + * @var array + * @access public + */ + public $uses = array('RequestActionPost'); + +/** + * test_request_action method + * + * @access public + * @return void + */ + public function test_request_action() { + return 'This is a test'; + } + +/** + * another_ra_test method + * + * @param mixed $id + * @param mixed $other + * @access public + * @return void + */ + public function another_ra_test($id, $other) { + return $id + $other; + } + +/** + * normal_request_action method + * + * @return void + */ + public function normal_request_action() { + return 'Hello World'; + } + +/** + * returns $this->here + * + * @return void + */ + public function return_here() { + return $this->here; + } + +/** + * paginate_request_action method + * + * @return void + */ + public function paginate_request_action() { + $data = $this->paginate(); + return true; + } + +/** + * post pass, testing post passing + * + * @return array + */ + public function post_pass() { + return $this->request->data; + } + +/** + * test param passing and parsing. + * + * @return array + */ + public function params_pass() { + return $this->request; + } + + public function param_check() { + $this->autoRender = false; + $content = ''; + if (isset($this->request->params[0])) { + $content = 'return found'; + } + $this->response->body($content); + } + +} + +/** + * TestObject class + * + * @package Cake.Test.Case.Core + */ +class TestObject extends Object { + +/** + * firstName property + * + * @var string 'Joel' + */ + public $firstName = 'Joel'; + +/** + * lastName property + * + * @var string 'Moss' + */ + public $lastName = 'Moss'; + +/** + * methodCalls property + * + * @var array + */ + public $methodCalls = array(); + +/** + * emptyMethod method + * + * @return void + */ + public function emptyMethod() { + $this->methodCalls[] = 'emptyMethod'; + } + +/** + * oneParamMethod method + * + * @param mixed $param + * @return void + */ + public function oneParamMethod($param) { + $this->methodCalls[] = array('oneParamMethod' => array($param)); + } + +/** + * twoParamMethod method + * + * @param mixed $param + * @param mixed $paramTwo + * @return void + */ + public function twoParamMethod($param, $paramTwo) { + $this->methodCalls[] = array('twoParamMethod' => array($param, $paramTwo)); + } + +/** + * threeParamMethod method + * + * @param mixed $param + * @param mixed $paramTwo + * @param mixed $paramThree + * @return void + */ + public function threeParamMethod($param, $paramTwo, $paramThree) { + $this->methodCalls[] = array('threeParamMethod' => array($param, $paramTwo, $paramThree)); + } + +/** + * fourParamMethod method + * + * @param mixed $param + * @param mixed $paramTwo + * @param mixed $paramThree + * @param mixed $paramFour + * @return void + */ + public function fourParamMethod($param, $paramTwo, $paramThree, $paramFour) { + $this->methodCalls[] = array('fourParamMethod' => array($param, $paramTwo, $paramThree, $paramFour)); + } + +/** + * fiveParamMethod method + * + * @param mixed $param + * @param mixed $paramTwo + * @param mixed $paramThree + * @param mixed $paramFour + * @param mixed $paramFive + * @return void + */ + public function fiveParamMethod($param, $paramTwo, $paramThree, $paramFour, $paramFive) { + $this->methodCalls[] = array('fiveParamMethod' => array($param, $paramTwo, $paramThree, $paramFour, $paramFive)); + } + +/** + * crazyMethod method + * + * @param mixed $param + * @param mixed $paramTwo + * @param mixed $paramThree + * @param mixed $paramFour + * @param mixed $paramFive + * @param mixed $paramSix + * @param mixed $paramSeven + * @return void + */ + public function crazyMethod($param, $paramTwo, $paramThree, $paramFour, $paramFive, $paramSix, $paramSeven = null) { + $this->methodCalls[] = array('crazyMethod' => array($param, $paramTwo, $paramThree, $paramFour, $paramFive, $paramSix, $paramSeven)); + } + +/** + * methodWithOptionalParam method + * + * @param mixed $param + * @return void + */ + public function methodWithOptionalParam($param = null) { + $this->methodCalls[] = array('methodWithOptionalParam' => array($param)); + } + +/** + * undocumented function + * + * @return void + */ + public function set($properties = array()) { + return parent::_set($properties); + } + +} + +/** + * ObjectTestModel class + * + * @package Cake.Test.Case.Core + */ +class ObjectTestModel extends CakeTestModel { + + public $useTable = false; + + public $name = 'ObjectTestModel'; + +} + +/** + * Object Test class + * + * @package Cake.Test.Case.Core + */ +class ObjectTest extends CakeTestCase { + +/** + * fixtures + * + * @var string + */ + public $fixtures = array('core.post', 'core.test_plugin_comment', 'core.comment'); + +/** + * setUp method + * + * @return void + */ + public function setUp() { + parent::setUp(); + $this->object = new TestObject(); + } + +/** + * tearDown method + * + * @return void + */ + public function tearDown() { + parent::tearDown(); + CakePlugin::unload(); + unset($this->object); + } + +/** + * testLog method + * + * @return void + */ + public function testLog() { + if (file_exists(LOGS . 'error.log')) { + unlink(LOGS . 'error.log'); + } + $this->assertTrue($this->object->log('Test warning 1')); + $this->assertTrue($this->object->log(array('Test' => 'warning 2'))); + $result = file(LOGS . 'error.log'); + $this->assertRegExp('/^2[0-9]{3}-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+ Error: Test warning 1$/', $result[0]); + $this->assertRegExp('/^2[0-9]{3}-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+ Error: Array$/', $result[1]); + $this->assertRegExp('/^\($/', $result[2]); + $this->assertRegExp('/\[Test\] => warning 2$/', $result[3]); + $this->assertRegExp('/^\)$/', $result[4]); + unlink(LOGS . 'error.log'); + + $this->assertTrue($this->object->log('Test warning 1', LOG_WARNING)); + $this->assertTrue($this->object->log(array('Test' => 'warning 2'), LOG_WARNING)); + $result = file(LOGS . 'error.log'); + $this->assertRegExp('/^2[0-9]{3}-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+ Warning: Test warning 1$/', $result[0]); + $this->assertRegExp('/^2[0-9]{3}-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+ Warning: Array$/', $result[1]); + $this->assertRegExp('/^\($/', $result[2]); + $this->assertRegExp('/\[Test\] => warning 2$/', $result[3]); + $this->assertRegExp('/^\)$/', $result[4]); + unlink(LOGS . 'error.log'); + } + +/** + * testSet method + * + * @return void + */ + public function testSet() { + $this->object->set('a string'); + $this->assertEquals('Joel', $this->object->firstName); + + $this->object->set(array('firstName')); + $this->assertEquals('Joel', $this->object->firstName); + + $this->object->set(array('firstName' => 'Ashley')); + $this->assertEquals('Ashley', $this->object->firstName); + + $this->object->set(array('firstName' => 'Joel', 'lastName' => 'Moose')); + $this->assertEquals('Joel', $this->object->firstName); + $this->assertEquals('Moose', $this->object->lastName); + } + +/** + * testToString method + * + * @return void + */ + public function testToString() { + $result = strtolower($this->object->toString()); + $this->assertEquals('testobject', $result); + } + +/** + * testMethodDispatching method + * + * @return void + */ + public function testMethodDispatching() { + $this->object->emptyMethod(); + $expected = array('emptyMethod'); + $this->assertSame($this->object->methodCalls, $expected); + + $this->object->oneParamMethod('Hello'); + $expected[] = array('oneParamMethod' => array('Hello')); + $this->assertSame($this->object->methodCalls, $expected); + + $this->object->twoParamMethod(true, false); + $expected[] = array('twoParamMethod' => array(true, false)); + $this->assertSame($this->object->methodCalls, $expected); + + $this->object->threeParamMethod(true, false, null); + $expected[] = array('threeParamMethod' => array(true, false, null)); + $this->assertSame($this->object->methodCalls, $expected); + + $this->object->crazyMethod(1, 2, 3, 4, 5, 6, 7); + $expected[] = array('crazyMethod' => array(1, 2, 3, 4, 5, 6, 7)); + $this->assertSame($this->object->methodCalls, $expected); + + $this->object = new TestObject(); + $this->assertSame($this->object->methodCalls, array()); + + $this->object->dispatchMethod('emptyMethod'); + $expected = array('emptyMethod'); + $this->assertSame($this->object->methodCalls, $expected); + + $this->object->dispatchMethod('oneParamMethod', array('Hello')); + $expected[] = array('oneParamMethod' => array('Hello')); + $this->assertSame($this->object->methodCalls, $expected); + + $this->object->dispatchMethod('twoParamMethod', array(true, false)); + $expected[] = array('twoParamMethod' => array(true, false)); + $this->assertSame($this->object->methodCalls, $expected); + + $this->object->dispatchMethod('threeParamMethod', array(true, false, null)); + $expected[] = array('threeParamMethod' => array(true, false, null)); + $this->assertSame($this->object->methodCalls, $expected); + + $this->object->dispatchMethod('fourParamMethod', array(1, 2, 3, 4)); + $expected[] = array('fourParamMethod' => array(1, 2, 3, 4)); + $this->assertSame($this->object->methodCalls, $expected); + + $this->object->dispatchMethod('fiveParamMethod', array(1, 2, 3, 4, 5)); + $expected[] = array('fiveParamMethod' => array(1, 2, 3, 4, 5)); + $this->assertSame($this->object->methodCalls, $expected); + + $this->object->dispatchMethod('crazyMethod', array(1, 2, 3, 4, 5, 6, 7)); + $expected[] = array('crazyMethod' => array(1, 2, 3, 4, 5, 6, 7)); + $this->assertSame($this->object->methodCalls, $expected); + + $this->object->dispatchMethod('methodWithOptionalParam', array('Hello')); + $expected[] = array('methodWithOptionalParam' => array("Hello")); + $this->assertSame($this->object->methodCalls, $expected); + + $this->object->dispatchMethod('methodWithOptionalParam'); + $expected[] = array('methodWithOptionalParam' => array(null)); + $this->assertSame($this->object->methodCalls, $expected); + } + +/** + * testRequestAction method + * + * @return void + */ + public function testRequestAction() { + App::build(array( + 'Model' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Model' . DS), + 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS), + 'Controller' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Controller' . DS) + ), App::RESET); + $this->assertNull(Router::getRequest(), 'request stack should be empty.'); + + $result = $this->object->requestAction(''); + $this->assertFalse($result); + + $result = $this->object->requestAction('/request_action/test_request_action'); + $expected = 'This is a test'; + $this->assertEquals($expected, $result); + + $result = $this->object->requestAction(FULL_BASE_URL . '/request_action/test_request_action'); + $expected = 'This is a test'; + $this->assertEquals($expected, $result); + + $result = $this->object->requestAction('/request_action/another_ra_test/2/5'); + $expected = 7; + $this->assertEquals($expected, $result); + + $result = $this->object->requestAction('/tests_apps/index', array('return')); + $expected = 'This is the TestsAppsController index view '; + $this->assertEquals($expected, $result); + + $result = $this->object->requestAction('/tests_apps/some_method'); + $expected = 5; + $this->assertEquals($expected, $result); + + $result = $this->object->requestAction('/request_action/paginate_request_action'); + $this->assertTrue($result); + + $result = $this->object->requestAction('/request_action/normal_request_action'); + $expected = 'Hello World'; + $this->assertEquals($expected, $result); + + $this->assertNull(Router::getRequest(), 'requests were not popped off the stack, this will break url generation'); + } + +/** + * test requestAction() and plugins. + * + * @return void + */ + public function testRequestActionPlugins() { + App::build(array( + 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS), + ), App::RESET); + CakePlugin::load('TestPlugin'); + Router::reload(); + + $result = $this->object->requestAction('/test_plugin/tests/index', array('return')); + $expected = 'test plugin index'; + $this->assertEquals($expected, $result); + + $result = $this->object->requestAction('/test_plugin/tests/index/some_param', array('return')); + $expected = 'test plugin index'; + $this->assertEquals($expected, $result); + + $result = $this->object->requestAction( + array('controller' => 'tests', 'action' => 'index', 'plugin' => 'test_plugin'), array('return') + ); + $expected = 'test plugin index'; + $this->assertEquals($expected, $result); + + $result = $this->object->requestAction('/test_plugin/tests/some_method'); + $expected = 25; + $this->assertEquals($expected, $result); + + $result = $this->object->requestAction( + array('controller' => 'tests', 'action' => 'some_method', 'plugin' => 'test_plugin') + ); + $expected = 25; + $this->assertEquals($expected, $result); + } + +/** + * test requestAction() with arrays. + * + * @return void + */ + public function testRequestActionArray() { + App::build(array( + 'Model' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Model' . DS), + 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS), + 'Controller' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Controller' . DS), + 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS) + ), App::RESET); + CakePlugin::load(array('TestPlugin')); + + $result = $this->object->requestAction( + array('controller' => 'request_action', 'action' => 'test_request_action') + ); + $expected = 'This is a test'; + $this->assertEquals($expected, $result); + + $result = $this->object->requestAction( + array('controller' => 'request_action', 'action' => 'another_ra_test'), + array('pass' => array('5', '7')) + ); + $expected = 12; + $this->assertEquals($expected, $result); + + $result = $this->object->requestAction( + array('controller' => 'tests_apps', 'action' => 'index'), array('return') + ); + $expected = 'This is the TestsAppsController index view '; + $this->assertEquals($expected, $result); + + $result = $this->object->requestAction(array('controller' => 'tests_apps', 'action' => 'some_method')); + $expected = 5; + $this->assertEquals($expected, $result); + + $result = $this->object->requestAction( + array('controller' => 'request_action', 'action' => 'normal_request_action') + ); + $expected = 'Hello World'; + $this->assertEquals($expected, $result); + + $result = $this->object->requestAction( + array('controller' => 'request_action', 'action' => 'paginate_request_action') + ); + $this->assertTrue($result); + + $result = $this->object->requestAction( + array('controller' => 'request_action', 'action' => 'paginate_request_action'), + array('pass' => array(5), 'named' => array('param' => 'value')) + ); + $this->assertTrue($result); + } + +/** + * Test that requestAction() does not forward the 0 => return value. + * + * @return void + */ + public function testRequestActionRemoveReturnParam() { + $result = $this->object->requestAction( + '/request_action/param_check', array('return') + ); + $this->assertEquals('', $result, 'Return key was found'); + } + +/** + * Test that requestAction() is populating $this->params properly + * + * @return void + */ + public function testRequestActionParamParseAndPass() { + $result = $this->object->requestAction('/request_action/params_pass'); + $this->assertEquals('request_action/params_pass', $result->url); + $this->assertEquals('request_action', $result['controller']); + $this->assertEquals('params_pass', $result['action']); + $this->assertEquals(null, $result['plugin']); + + $result = $this->object->requestAction('/request_action/params_pass/sort:desc/limit:5'); + $expected = array('sort' => 'desc', 'limit' => 5,); + $this->assertEquals($expected, $result['named']); + + $result = $this->object->requestAction( + array('controller' => 'request_action', 'action' => 'params_pass'), + array('named' => array('sort' => 'desc', 'limit' => 5)) + ); + $this->assertEquals($expected, $result['named']); + } + +/** + * test that requestAction does not fish data out of the POST + * superglobal. + * + * @return void + */ + public function testRequestActionNoPostPassing() { + $_tmp = $_POST; + + $_POST = array('data' => array( + 'item' => 'value' + )); + $result = $this->object->requestAction(array('controller' => 'request_action', 'action' => 'post_pass')); + $expected = null; + $this->assertEmpty($result); + + $result = $this->object->requestAction( + array('controller' => 'request_action', 'action' => 'post_pass'), + array('data' => $_POST['data']) + ); + $expected = $_POST['data']; + $this->assertEquals($expected, $result); + + $result = $this->object->requestAction('/request_action/post_pass'); + $expected = $_POST['data']; + $this->assertEquals($expected, $result); + + $_POST = $_tmp; + } + +/** + * Test requestAction with post data. + * + * @return void + */ + public function testRequestActionPostWithData() { + $data = array( + 'Post' => array('id' => 2) + ); + $result = $this->object->requestAction( + array('controller' => 'request_action', 'action' => 'post_pass'), + array('data' => $data) + ); + $this->assertEquals($data, $result); + + $result = $this->object->requestAction( + '/request_action/post_pass', + array('data' => $data) + ); + $this->assertEquals($data, $result); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Error/ErrorHandlerTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Error/ErrorHandlerTest.php new file mode 100644 index 0000000..e4bd579 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Error/ErrorHandlerTest.php @@ -0,0 +1,296 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Error + * @since CakePHP(tm) v 1.2.0.5432 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ + +App::uses('ErrorHandler', 'Error'); +App::uses('Controller', 'Controller'); +App::uses('Router', 'Routing'); + +/** + * ErrorHandlerTest class + * + * @package Cake.Test.Case.Error + */ +class ErrorHandlerTest extends CakeTestCase { + + protected $_restoreError = false; + +/** + * setup create a request object to get out of router later. + * + * @return void + */ + public function setUp() { + parent::setUp(); + App::build(array( + 'View' => array( + CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS + ) + ), App::RESET); + Router::reload(); + + $request = new CakeRequest(null, false); + $request->base = ''; + Router::setRequestInfo($request); + Configure::write('debug', 2); + + CakeLog::disable('stdout'); + CakeLog::disable('stderr'); + } + +/** + * tearDown + * + * @return void + */ + public function tearDown() { + parent::tearDown(); + if ($this->_restoreError) { + restore_error_handler(); + } + CakeLog::enable('stdout'); + CakeLog::enable('stderr'); + } + +/** + * test error handling when debug is on, an error should be printed from Debugger. + * + * @return void + */ + public function testHandleErrorDebugOn() { + set_error_handler('ErrorHandler::handleError'); + $this->_restoreError = true; + + ob_start(); + $wrong .= ''; + $result = ob_get_clean(); + + $this->assertRegExp('/
/', $result);
+		$this->assertRegExp('/Notice<\/b>/', $result);
+		$this->assertRegExp('/variable:\s+wrong/', $result);
+	}
+
+/**
+ * provides errors for mapping tests.
+ *
+ * @return void
+ */
+	public static function errorProvider() {
+		return array(
+			array(E_USER_NOTICE, 'Notice'),
+			array(E_USER_WARNING, 'Warning'),
+		);
+	}
+
+/**
+ * test error mappings
+ *
+ * @dataProvider errorProvider
+ * @return void
+ */
+	public function testErrorMapping($error, $expected) {
+		set_error_handler('ErrorHandler::handleError');
+		$this->_restoreError = true;
+
+		ob_start();
+		trigger_error('Test error', $error);
+
+		$result = ob_get_clean();
+		$this->assertRegExp('/' . $expected . '<\/b>/', $result);
+	}
+
+/**
+ * test error prepended by @
+ *
+ * @return void
+ */
+	public function testErrorSuppressed() {
+		set_error_handler('ErrorHandler::handleError');
+		$this->_restoreError = true;
+
+		ob_start();
+		@include 'invalid.file';
+		$result = ob_get_clean();
+		$this->assertTrue(empty($result));
+	}
+
+/**
+ * Test that errors go into CakeLog when debug = 0.
+ *
+ * @return void
+ */
+	public function testHandleErrorDebugOff() {
+		Configure::write('debug', 0);
+		Configure::write('Error.trace', false);
+		if (file_exists(LOGS . 'debug.log')) {
+			@unlink(LOGS . 'debug.log');
+		}
+
+		set_error_handler('ErrorHandler::handleError');
+		$this->_restoreError = true;
+
+		$out .= '';
+
+		$result = file(LOGS . 'debug.log');
+		$this->assertEquals(1, count($result));
+		$this->assertRegExp(
+			'/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} (Notice|Debug): Notice \(8\): Undefined variable:\s+out in \[.+ line \d+\]$/',
+			$result[0]
+		);
+		@unlink(LOGS . 'debug.log');
+	}
+
+/**
+ * Test that errors going into CakeLog include traces.
+ *
+ * @return void
+ */
+	public function testHandleErrorLoggingTrace() {
+		Configure::write('debug', 0);
+		Configure::write('Error.trace', true);
+		if (file_exists(LOGS . 'debug.log')) {
+			@unlink(LOGS . 'debug.log');
+		}
+
+		set_error_handler('ErrorHandler::handleError');
+		$this->_restoreError = true;
+
+		$out .= '';
+
+		$result = file(LOGS . 'debug.log');
+		$this->assertRegExp(
+			'/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} (Notice|Debug): Notice \(8\): Undefined variable:\s+out in \[.+ line \d+\]$/',
+			$result[0]
+		);
+		$this->assertRegExp('/^Trace:/', $result[1]);
+		$this->assertRegExp('/^ErrorHandlerTest\:\:testHandleErrorLoggingTrace\(\)/', $result[2]);
+		@unlink(LOGS . 'debug.log');
+	}
+
+/**
+ * test handleException generating a page.
+ *
+ * @return void
+ */
+	public function testHandleException() {
+		$this->skipIf(file_exists(APP . 'app_error.php'), 'App error exists cannot run.');
+
+		$error = new NotFoundException('Kaboom!');
+		ob_start();
+		ErrorHandler::handleException($error);
+		$result = ob_get_clean();
+		$this->assertRegExp('/Kaboom!/', $result, 'message missing.');
+	}
+
+/**
+ * test handleException generating log.
+ *
+ * @return void
+ */
+	public function testHandleExceptionLog() {
+		$this->skipIf(file_exists(APP . 'app_error.php'), 'App error exists cannot run.');
+
+		if (file_exists(LOGS . 'error.log')) {
+			unlink(LOGS . 'error.log');
+		}
+		Configure::write('Exception.log', true);
+		$error = new NotFoundException('Kaboom!');
+
+		ob_start();
+		ErrorHandler::handleException($error);
+		$result = ob_get_clean();
+		$this->assertRegExp('/Kaboom!/', $result, 'message missing.');
+
+		$log = file(LOGS . 'error.log');
+		$this->assertRegExp('/\[NotFoundException\] Kaboom!/', $log[0], 'message missing.');
+		$this->assertRegExp('/\#0.*ErrorHandlerTest->testHandleExceptionLog/', $log[1], 'Stack trace missing.');
+	}
+
+/**
+ * tests it is possible to load a plugin exception renderer
+ *
+ * @return void
+ */
+	public function testLoadPluginHandler() {
+		App::build(array(
+			'Plugin' => array(
+				CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS
+			)
+		), App::RESET);
+		CakePlugin::load('TestPlugin');
+		Configure::write('Exception.renderer', 'TestPlugin.TestPluginExceptionRenderer');
+		$error = new NotFoundException('Kaboom!');
+		ob_start();
+		ErrorHandler::handleException($error);
+		$result = ob_get_clean();
+		$this->assertEquals('Rendered by test plugin', $result);
+		CakePlugin::unload();
+	}
+
+/**
+ * test handleFatalError generating a page.
+ *
+ * @return void
+ */
+	public function testHandleFatalErrorPage() {
+		$this->skipIf(file_exists(APP . 'app_error.php'), 'App error exists cannot run.');
+
+		$originalDebugLevel = Configure::read('debug');
+		$line = __LINE__;
+
+		ob_start();
+		Configure::write('debug', 1);
+		ErrorHandler::handleFatalError(E_ERROR, 'Something wrong', __FILE__, $line);
+		$result = ob_get_clean();
+		$this->assertContains('Something wrong', $result, 'message missing.');
+		$this->assertContains(__FILE__, $result, 'filename missing.');
+		$this->assertContains((string)$line, $result, 'line missing.');
+
+		ob_start();
+		Configure::write('debug', 0);
+		ErrorHandler::handleFatalError(E_ERROR, 'Something wrong', __FILE__, $line);
+		$result = ob_get_clean();
+		$this->assertNotContains('Something wrong', $result, 'message must not appear.');
+		$this->assertNotContains(__FILE__, $result, 'filename must not appear.');
+		$this->assertContains('An Internal Error Has Occurred', $result);
+
+		Configure::write('debug', $originalDebugLevel);
+	}
+
+/**
+ * test handleException generating log.
+ *
+ * @return void
+ */
+	public function testHandleFatalErrorLog() {
+		$this->skipIf(file_exists(APP . 'app_error.php'), 'App error exists cannot run.');
+
+		if (file_exists(LOGS . 'error.log')) {
+			unlink(LOGS . 'error.log');
+		}
+
+		ob_start();
+		ErrorHandler::handleFatalError(E_ERROR, 'Something wrong', __FILE__, __LINE__);
+		ob_clean();
+
+		$log = file(LOGS . 'error.log');
+		$this->assertContains(__FILE__, $log[0], 'missing filename');
+		$this->assertContains('[FatalErrorException] Something wrong', $log[1], 'message missing.');
+	}
+
+}
diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Error/ExceptionRendererTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Error/ExceptionRendererTest.php
new file mode 100644
index 0000000..956acec
--- /dev/null
+++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Error/ExceptionRendererTest.php
@@ -0,0 +1,776 @@
+
+ * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
+ *
+ * Licensed under The MIT License
+ * Redistributions of files must retain the above copyright notice
+ *
+ * @copyright     Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
+ * @link          http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
+ * @package       Cake.Test.Case.Error
+ * @since         CakePHP(tm) v 2.0
+ * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
+ */
+
+App::uses('ExceptionRenderer', 'Error');
+App::uses('Controller', 'Controller');
+App::uses('AppController', 'Controller');
+App::uses('Component', 'Controller');
+App::uses('Router', 'Routing');
+
+/**
+ * Short description for class.
+ *
+ * @package       Cake.Test.Case.Error
+ */
+class AuthBlueberryUser extends CakeTestModel {
+
+/**
+ * name property
+ *
+ * @var string 'AuthBlueberryUser'
+ */
+	public $name = 'AuthBlueberryUser';
+
+/**
+ * useTable property
+ *
+ * @var string
+ */
+	public $useTable = false;
+}
+
+/**
+ * BlueberryComponent class
+ *
+ * @package       Cake.Test.Case.Error
+ */
+class BlueberryComponent extends Component {
+
+/**
+ * testName property
+ *
+ * @return void
+ */
+	public $testName = null;
+
+/**
+ * initialize method
+ *
+ * @return void
+ */
+	public function initialize(Controller $controller) {
+		$this->testName = 'BlueberryComponent';
+	}
+
+}
+
+/**
+ * TestErrorController class
+ *
+ * @package       Cake.Test.Case.Error
+ */
+class TestErrorController extends Controller {
+
+/**
+ * uses property
+ *
+ * @var array
+ */
+	public $uses = array();
+
+/**
+ * components property
+ *
+ * @return void
+ */
+	public $components = array('Blueberry');
+
+/**
+ * beforeRender method
+ *
+ * @return void
+ */
+	public function beforeRender() {
+		echo $this->Blueberry->testName;
+	}
+
+/**
+ * index method
+ *
+ * @return void
+ */
+	public function index() {
+		$this->autoRender = false;
+		return 'what up';
+	}
+
+}
+
+/**
+ * MyCustomExceptionRenderer class
+ *
+ * @package       Cake.Test.Case.Error
+ */
+class MyCustomExceptionRenderer extends ExceptionRenderer {
+
+/**
+ * custom error message type.
+ *
+ * @return void
+ */
+	public function missingWidgetThing() {
+		echo 'widget thing is missing';
+	}
+
+}
+
+/**
+ * Exception class for testing app error handlers and custom errors.
+ *
+ * @package       Cake.Test.Case.Error
+ */
+class MissingWidgetThingException extends NotFoundException {
+}
+
+
+/**
+ * ExceptionRendererTest class
+ *
+ * @package       Cake.Test.Case.Error
+ */
+class ExceptionRendererTest extends CakeTestCase {
+
+	protected $_restoreError = false;
+
+/**
+ * setup create a request object to get out of router later.
+ *
+ * @return void
+ */
+	public function setUp() {
+		parent::setUp();
+		App::build(array(
+			'View' => array(
+				CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS
+			)
+		), App::RESET);
+		Router::reload();
+
+		$request = new CakeRequest(null, false);
+		$request->base = '';
+		Router::setRequestInfo($request);
+		Configure::write('debug', 2);
+	}
+
+/**
+ * tearDown
+ *
+ * @return void
+ */
+	public function tearDown() {
+		parent::tearDown();
+		if ($this->_restoreError) {
+			restore_error_handler();
+		}
+	}
+
+/**
+ * Mocks out the response on the ExceptionRenderer object so headers aren't modified.
+ *
+ * @return void
+ */
+	protected function _mockResponse($error) {
+		$error->controller->response = $this->getMock('CakeResponse', array('_sendHeader'));
+		return $error;
+	}
+
+/**
+ * test that methods declared in an ExceptionRenderer subclass are not converted
+ * into error400 when debug > 0
+ *
+ * @return void
+ */
+	public function testSubclassMethodsNotBeingConvertedToError() {
+		Configure::write('debug', 2);
+
+		$exception = new MissingWidgetThingException('Widget not found');
+		$ExceptionRenderer = $this->_mockResponse(new MyCustomExceptionRenderer($exception));
+
+		ob_start();
+		$ExceptionRenderer->render();
+		$result = ob_get_clean();
+
+		$this->assertEquals('widget thing is missing', $result);
+	}
+
+/**
+ * test that subclass methods are not converted when debug = 0
+ *
+ * @return void
+ */
+	public function testSubclassMethodsNotBeingConvertedDebug0() {
+		Configure::write('debug', 0);
+		$exception = new MissingWidgetThingException('Widget not found');
+		$ExceptionRenderer = $this->_mockResponse(new MyCustomExceptionRenderer($exception));
+
+		$this->assertEquals('missingWidgetThing', $ExceptionRenderer->method);
+
+		ob_start();
+		$ExceptionRenderer->render();
+		$result = ob_get_clean();
+
+		$this->assertEquals('widget thing is missing', $result, 'Method declared in subclass converted to error400');
+	}
+
+/**
+ * test that ExceptionRenderer subclasses properly convert framework errors.
+ *
+ * @return void
+ */
+	public function testSubclassConvertingFrameworkErrors() {
+		Configure::write('debug', 0);
+
+		$exception = new MissingControllerException('PostsController');
+		$ExceptionRenderer = $this->_mockResponse(new MyCustomExceptionRenderer($exception));
+
+		$this->assertEquals('error400', $ExceptionRenderer->method);
+
+		ob_start();
+		$ExceptionRenderer->render();
+		$result = ob_get_clean();
+
+		$this->assertRegExp('/Not Found/', $result, 'Method declared in error handler not converted to error400. %s');
+	}
+
+/**
+ * test things in the constructor.
+ *
+ * @return void
+ */
+	public function testConstruction() {
+		$exception = new NotFoundException('Page not found');
+		$ExceptionRenderer = new ExceptionRenderer($exception);
+
+		$this->assertInstanceOf('CakeErrorController', $ExceptionRenderer->controller);
+		$this->assertEquals('error400', $ExceptionRenderer->method);
+		$this->assertEquals($exception, $ExceptionRenderer->error);
+	}
+
+/**
+ * test that method gets coerced when debug = 0
+ *
+ * @return void
+ */
+	public function testErrorMethodCoercion() {
+		Configure::write('debug', 0);
+		$exception = new MissingActionException('Page not found');
+		$ExceptionRenderer = new ExceptionRenderer($exception);
+
+		$this->assertInstanceOf('CakeErrorController', $ExceptionRenderer->controller);
+		$this->assertEquals('error400', $ExceptionRenderer->method);
+		$this->assertEquals($exception, $ExceptionRenderer->error);
+	}
+
+/**
+ * test that helpers in custom CakeErrorController are not lost
+ */
+	public function testCakeErrorHelpersNotLost() {
+		$testApp = CAKE . 'Test' . DS . 'test_app' . DS;
+		App::build(array(
+			'Controller' => array(
+				$testApp . 'Controller' . DS
+			),
+			'View/Helper' => array(
+				$testApp . 'View' . DS . 'Helper' . DS
+			),
+			'View/Layouts' => array(
+				$testApp . 'View' . DS . 'Layouts' . DS
+			),
+			'Error' => array(
+				$testApp . 'Error' . DS
+			),
+		), App::RESET);
+
+		App::uses('TestAppsExceptionRenderer', 'Error');
+		$exception = new SocketException('socket exception');
+		$renderer = new TestAppsExceptionRenderer($exception);
+
+		ob_start();
+		$renderer->render();
+		$result = ob_get_clean();
+		$this->assertContains('peeled', $result);
+	}
+
+/**
+ * test that unknown exception types with valid status codes are treated correctly.
+ *
+ * @return void
+ */
+	public function testUnknownExceptionTypeWithExceptionThatHasA400Code() {
+		$exception = new MissingWidgetThingException('coding fail.');
+		$ExceptionRenderer = new ExceptionRenderer($exception);
+		$ExceptionRenderer->controller->response = $this->getMock('CakeResponse', array('statusCode', '_sendHeader'));
+		$ExceptionRenderer->controller->response->expects($this->once())->method('statusCode')->with(404);
+
+		ob_start();
+		$ExceptionRenderer->render();
+		$result = ob_get_clean();
+
+		$this->assertFalse(method_exists($ExceptionRenderer, 'missingWidgetThing'), 'no method should exist.');
+		$this->assertEquals('error400', $ExceptionRenderer->method, 'incorrect method coercion.');
+		$this->assertContains('coding fail', $result, 'Text should show up.');
+	}
+
+/**
+ * test that unknown exception types with valid status codes are treated correctly.
+ *
+ * @return void
+ */
+	public function testUnknownExceptionTypeWithNoCodeIsA500() {
+		$exception = new OutOfBoundsException('foul ball.');
+		$ExceptionRenderer = new ExceptionRenderer($exception);
+		$ExceptionRenderer->controller->response = $this->getMock('CakeResponse', array('statusCode', '_sendHeader'));
+		$ExceptionRenderer->controller->response->expects($this->once())
+			->method('statusCode')
+			->with(500);
+
+		ob_start();
+		$ExceptionRenderer->render();
+		$result = ob_get_clean();
+
+		$this->assertEquals('error500', $ExceptionRenderer->method, 'incorrect method coercion.');
+		$this->assertContains('foul ball.', $result, 'Text should show up as its debug mode.');
+	}
+
+/**
+ * test that unknown exceptions have messages ignored.
+ *
+ * @return void
+ */
+	public function testUnknownExceptionInProduction() {
+		Configure::write('debug', 0);
+
+		$exception = new OutOfBoundsException('foul ball.');
+		$ExceptionRenderer = new ExceptionRenderer($exception);
+		$ExceptionRenderer->controller->response = $this->getMock('CakeResponse', array('statusCode', '_sendHeader'));
+		$ExceptionRenderer->controller->response->expects($this->once())
+			->method('statusCode')
+			->with(500);
+
+		ob_start();
+		$ExceptionRenderer->render();
+		$result = ob_get_clean();
+
+		$this->assertEquals('error500', $ExceptionRenderer->method, 'incorrect method coercion.');
+		$this->assertNotContains('foul ball.', $result, 'Text should no show up.');
+		$this->assertContains('Internal Error', $result, 'Generic message only.');
+	}
+
+/**
+ * test that unknown exception types with valid status codes are treated correctly.
+ *
+ * @return void
+ */
+	public function testUnknownExceptionTypeWithCodeHigherThan500() {
+		$exception = new OutOfBoundsException('foul ball.', 501);
+		$ExceptionRenderer = new ExceptionRenderer($exception);
+		$ExceptionRenderer->controller->response = $this->getMock('CakeResponse', array('statusCode', '_sendHeader'));
+		$ExceptionRenderer->controller->response->expects($this->once())->method('statusCode')->with(501);
+
+		ob_start();
+		$ExceptionRenderer->render();
+		$result = ob_get_clean();
+
+		$this->assertEquals('error500', $ExceptionRenderer->method, 'incorrect method coercion.');
+		$this->assertContains('foul ball.', $result, 'Text should show up as its debug mode.');
+	}
+
+/**
+ * testerror400 method
+ *
+ * @return void
+ */
+	public function testError400() {
+		Router::reload();
+
+		$request = new CakeRequest('posts/view/1000', false);
+		Router::setRequestInfo($request);
+
+		$exception = new NotFoundException('Custom message');
+		$ExceptionRenderer = new ExceptionRenderer($exception);
+		$ExceptionRenderer->controller->response = $this->getMock('CakeResponse', array('statusCode', '_sendHeader'));
+		$ExceptionRenderer->controller->response->expects($this->once())->method('statusCode')->with(404);
+
+		ob_start();
+		$ExceptionRenderer->render();
+		$result = ob_get_clean();
+
+		$this->assertRegExp('/

Custom message<\/h2>/', $result); + $this->assertRegExp("/'.*?\/posts\/view\/1000'<\/strong>/", $result); + } + +/** + * test that error400 only modifies the messages on CakeExceptions. + * + * @return void + */ + public function testerror400OnlyChangingCakeException() { + Configure::write('debug', 0); + + $exception = new NotFoundException('Custom message'); + $ExceptionRenderer = $this->_mockResponse(new ExceptionRenderer($exception)); + + ob_start(); + $ExceptionRenderer->render(); + $result = ob_get_clean(); + $this->assertContains('Custom message', $result); + + $exception = new MissingActionException(array('controller' => 'PostsController', 'action' => 'index')); + $ExceptionRenderer = $this->_mockResponse(new ExceptionRenderer($exception)); + + ob_start(); + $ExceptionRenderer->render(); + $result = ob_get_clean(); + $this->assertContains('Not Found', $result); + } + +/** + * test that error400 doesn't expose XSS + * + * @return void + */ + public function testError400NoInjection() { + Router::reload(); + + $request = new CakeRequest('pages/pink', false); + Router::setRequestInfo($request); + + $exception = new NotFoundException('Custom message'); + $ExceptionRenderer = $this->_mockResponse(new ExceptionRenderer($exception)); + + ob_start(); + $ExceptionRenderer->render(); + $result = ob_get_clean(); + + $this->assertNotRegExp('##', $result); + } + +/** + * testError500 method + * + * @return void + */ + public function testError500Message() { + $exception = new InternalErrorException('An Internal Error Has Occurred'); + $ExceptionRenderer = new ExceptionRenderer($exception); + $ExceptionRenderer->controller->response = $this->getMock('CakeResponse', array('statusCode', '_sendHeader')); + $ExceptionRenderer->controller->response->expects($this->once())->method('statusCode')->with(500); + + ob_start(); + $ExceptionRenderer->render(); + $result = ob_get_clean(); + + $this->assertRegExp('/

An Internal Error Has Occurred<\/h2>/', $result); + } + +/** + * testMissingController method + * + * @return void + */ + public function testMissingController() { + $exception = new MissingControllerException(array('class' => 'PostsController')); + $ExceptionRenderer = $this->_mockResponse(new ExceptionRenderer($exception)); + + ob_start(); + $ExceptionRenderer->render(); + $result = ob_get_clean(); + + $this->assertRegExp('/

Missing Controller<\/h2>/', $result); + $this->assertRegExp('/PostsController<\/em>/', $result); + } + +/** + * Returns an array of tests to run for the various CakeException classes. + * + * @return void + */ + public static function testProvider() { + return array( + array( + new MissingActionException(array('controller' => 'PostsController', 'action' => 'index')), + array( + '/

Missing Method in PostsController<\/h2>/', + '/PostsController::<\/em>index\(\)<\/em>/' + ), + 404 + ), + array( + new PrivateActionException(array('controller' => 'PostsController' , 'action' => '_secretSauce')), + array( + '/

Private Method in PostsController<\/h2>/', + '/PostsController::<\/em>_secretSauce\(\)<\/em>/' + ), + 404 + ), + array( + new MissingTableException(array('table' => 'articles', 'class' => 'Article', 'ds' => 'test')), + array( + '/

Missing Database Table<\/h2>/', + '/Table articles<\/em> for model Article<\/em> was not found in datasource test<\/em>/' + ), + 500 + ), + array( + new MissingDatabaseException(array('connection' => 'default')), + array( + '/

Missing Database Connection<\/h2>/', + '/Confirm you have created the file/' + ), + 500 + ), + array( + new MissingViewException(array('file' => '/posts/about.ctp')), + array( + "/posts\/about.ctp/" + ), + 500 + ), + array( + new MissingLayoutException(array('file' => 'layouts/my_layout.ctp')), + array( + "/Missing Layout/", + "/layouts\/my_layout.ctp/" + ), + 500 + ), + array( + new MissingConnectionException(array('class' => 'Article')), + array( + '/

Missing Database Connection<\/h2>/', + '/Article requires a database connection/' + ), + 500 + ), + array( + new MissingConnectionException(array('class' => 'Mysql', 'enabled' => false)), + array( + '/

Missing Database Connection<\/h2>/', + '/Mysql requires a database connection/', + '/Mysql driver is NOT enabled/' + ), + 500 + ), + array( + new MissingDatasourceConfigException(array('config' => 'default')), + array( + '/

Missing Datasource Configuration<\/h2>/', + '/The datasource configuration default<\/em> was not found in database.php/' + ), + 500 + ), + array( + new MissingDatasourceException(array('class' => 'MyDatasource', 'plugin' => 'MyPlugin')), + array( + '/

Missing Datasource<\/h2>/', + '/Datasource class MyPlugin.MyDatasource<\/em> could not be found/' + ), + 500 + ), + array( + new MissingHelperException(array('class' => 'MyCustomHelper')), + array( + '/

Missing Helper<\/h2>/', + '/MyCustomHelper<\/em> could not be found./', + '/Create the class MyCustomHelper<\/em> below in file:/', + '/(\/|\\\)MyCustomHelper.php/' + ), + 500 + ), + array( + new MissingBehaviorException(array('class' => 'MyCustomBehavior')), + array( + '/

Missing Behavior<\/h2>/', + '/Create the class MyCustomBehavior<\/em> below in file:/', + '/(\/|\\\)MyCustomBehavior.php/' + ), + 500 + ), + array( + new MissingComponentException(array('class' => 'SideboxComponent')), + array( + '/

Missing Component<\/h2>/', + '/Create the class SideboxComponent<\/em> below in file:/', + '/(\/|\\\)SideboxComponent.php/' + ), + 500 + ), + array( + new Exception('boom'), + array( + '/Internal Error/' + ), + 500 + ), + array( + new RuntimeException('another boom'), + array( + '/Internal Error/' + ), + 500 + ), + array( + new CakeException('base class'), + array('/Internal Error/'), + 500 + ), + array( + new ConfigureException('No file'), + array('/Internal Error/'), + 500 + ) + ); + } + +/** + * Test the various CakeException sub classes + * + * @dataProvider testProvider + * @return void + */ + public function testCakeExceptionHandling($exception, $patterns, $code) { + $ExceptionRenderer = new ExceptionRenderer($exception); + $ExceptionRenderer->controller->response = $this->getMock('CakeResponse', array('statusCode', '_sendHeader')); + $ExceptionRenderer->controller->response->expects($this->once()) + ->method('statusCode') + ->with($code); + + ob_start(); + $ExceptionRenderer->render(); + $result = ob_get_clean(); + + foreach ($patterns as $pattern) { + $this->assertRegExp($pattern, $result); + } + } + +/** + * Test exceptions being raised when helpers are missing. + * + * @return void + */ + public function testMissingRenderSafe() { + $exception = new MissingHelperException(array('class' => 'Fail')); + $ExceptionRenderer = new ExceptionRenderer($exception); + + $ExceptionRenderer->controller = $this->getMock('Controller'); + $ExceptionRenderer->controller->helpers = array('Fail', 'Boom'); + $ExceptionRenderer->controller->request = $this->getMock('CakeRequest'); + $ExceptionRenderer->controller->expects($this->at(2)) + ->method('render') + ->with('missingHelper') + ->will($this->throwException($exception)); + + $ExceptionRenderer->controller->expects($this->at(4)) + ->method('render') + ->with('error500') + ->will($this->returnValue(true)); + + $ExceptionRenderer->controller->response = $this->getMock('CakeResponse'); + $ExceptionRenderer->render(); + sort($ExceptionRenderer->controller->helpers); + $this->assertEquals(array('Form', 'Html', 'Session'), $ExceptionRenderer->controller->helpers); + } + +/** + * Test that missing subDir/layoutPath don't cause other fatal errors. + * + * @return void + */ + public function testMissingSubdirRenderSafe() { + $exception = new NotFoundException(); + $ExceptionRenderer = new ExceptionRenderer($exception); + + $ExceptionRenderer->controller = $this->getMock('Controller'); + $ExceptionRenderer->controller->helpers = array('Fail', 'Boom'); + $ExceptionRenderer->controller->layoutPath = 'json'; + $ExceptionRenderer->controller->subDir = 'json'; + $ExceptionRenderer->controller->viewClass = 'Json'; + $ExceptionRenderer->controller->request = $this->getMock('CakeRequest'); + + $ExceptionRenderer->controller->expects($this->at(1)) + ->method('render') + ->with('error400') + ->will($this->throwException($exception)); + + $ExceptionRenderer->controller->expects($this->at(3)) + ->method('render') + ->with('error500') + ->will($this->returnValue(true)); + + $ExceptionRenderer->controller->response = $this->getMock('CakeResponse'); + $ExceptionRenderer->controller->response->expects($this->once()) + ->method('type') + ->with('html'); + + $ExceptionRenderer->render(); + $this->assertEquals('', $ExceptionRenderer->controller->layoutPath); + $this->assertEquals('', $ExceptionRenderer->controller->subDir); + $this->assertEquals('View', $ExceptionRenderer->controller->viewClass); + $this->assertEquals('Errors/', $ExceptionRenderer->controller->viewPath); + } + +/** + * Test that exceptions can be rendered when an request hasn't been registered + * with Router + * + * @return void + */ + public function testRenderWithNoRequest() { + Router::reload(); + $this->assertNull(Router::getRequest(false)); + + $exception = new Exception('Terrible'); + $ExceptionRenderer = new ExceptionRenderer($exception); + $ExceptionRenderer->controller->response = $this->getMock('CakeResponse', array('statusCode', '_sendHeader')); + $ExceptionRenderer->controller->response->expects($this->once()) + ->method('statusCode') + ->with(500); + + ob_start(); + $ExceptionRenderer->render(); + $result = ob_get_clean(); + + $this->assertContains('Internal Error', $result); + } + +/** + * Tests the output of rendering a PDOException + * + * @return void + */ + public function testPDOException() { + $exception = new PDOException('There was an error in the SQL query'); + $exception->queryString = 'SELECT * from poo_query < 5 and :seven'; + $exception->params = array('seven' => 7); + $ExceptionRenderer = new ExceptionRenderer($exception); + $ExceptionRenderer->controller->response = $this->getMock('CakeResponse', array('statusCode', '_sendHeader')); + $ExceptionRenderer->controller->response->expects($this->once())->method('statusCode')->with(500); + + ob_start(); + $ExceptionRenderer->render(); + $result = ob_get_clean(); + + $this->assertContains('

Database Error

', $result); + $this->assertContains('There was an error in the SQL query', $result); + $this->assertContains('SELECT * from poo_query < 5 and :seven', $result); + $this->assertContains("'seven' => (int) 7", $result); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Event/CakeEventManagerTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Event/CakeEventManagerTest.php new file mode 100644 index 0000000..04a358a --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Event/CakeEventManagerTest.php @@ -0,0 +1,406 @@ +callStack[] = __FUNCTION__; + } + +/** + * Test function to be used in event dispatching + * + * @return void + */ + public function secondListenerFunction() { + $this->callStack[] = __FUNCTION__; + } + +/** + * Auxiliary function to help in stopPropagation testing + * + * @param CakeEvent $event + * @return void + */ + public function stopListener($event) { + $event->stopPropagation(); + } + +} + +/** + * Mock used for testing the subscriber objects + * + * @package Cake.Test.Case.Event + */ +class CustomTestEventListerner extends CakeEventTestListener implements CakeEventListener { + + public function implementedEvents() { + return array( + 'fake.event' => 'listenerFunction', + 'another.event' => array('callable' => 'secondListenerFunction', 'passParams' => true), + 'multiple.handlers' => array( + array('callable' => 'listenerFunction'), + array('callable' => 'thirdListenerFunction') + ) + ); + } + +/** + * Test function to be used in event dispatching + * + * @return void + */ + public function thirdListenerFunction() { + $this->callStack[] = __FUNCTION__; + } + +} + +/** + * Tests the CakeEventManager class functionality + * + */ +class CakeEventManagerTest extends CakeTestCase { + +/** + * Tests the attach() method for a single event key in multiple queues + * + * @return void + */ + public function testAttachListeners() { + $manager = new CakeEventManager; + $manager->attach('fakeFunction', 'fake.event'); + $expected = array( + array('callable' => 'fakeFunction', 'passParams' => false) + ); + $this->assertEquals($expected, $manager->listeners('fake.event')); + + $manager->attach('fakeFunction2', 'fake.event'); + $expected[] = array('callable' => 'fakeFunction2', 'passParams' => false); + $this->assertEquals($expected, $manager->listeners('fake.event')); + + $manager->attach('inQ5', 'fake.event', array('priority' => 5)); + $manager->attach('inQ1', 'fake.event', array('priority' => 1)); + $manager->attach('otherInQ5', 'fake.event', array('priority' => 5)); + + $expected = array_merge( + array( + array('callable' => 'inQ1', 'passParams' => false), + array('callable' => 'inQ5', 'passParams' => false), + array('callable' => 'otherInQ5', 'passParams' => false) + ), + $expected + ); + $this->assertEquals($expected, $manager->listeners('fake.event')); + } + +/** + * Tests the attach() method for multiple event key in multiple queues + * + * @return void + */ + public function testAttachMultipleEventKeys() { + $manager = new CakeEventManager; + $manager->attach('fakeFunction', 'fake.event'); + $manager->attach('fakeFunction2', 'another.event'); + $manager->attach('fakeFunction3', 'another.event', array('priority' => 1, 'passParams' => true)); + $expected = array( + array('callable' => 'fakeFunction', 'passParams' => false) + ); + $this->assertEquals($expected, $manager->listeners('fake.event')); + + $expected = array( + array('callable' => 'fakeFunction3', 'passParams' => true), + array('callable' => 'fakeFunction2', 'passParams' => false) + ); + $this->assertEquals($expected, $manager->listeners('another.event')); + } + +/** + * Tests detaching an event from a event key queue + * + * @return void + */ + public function testDetach() { + $manager = new CakeEventManager; + $manager->attach(array('AClass', 'aMethod'), 'fake.event'); + $manager->attach(array('AClass', 'anotherMethod'), 'another.event'); + $manager->attach('fakeFunction', 'another.event', array('priority' => 1)); + + $manager->detach(array('AClass', 'aMethod'), 'fake.event'); + $this->assertEquals(array(), $manager->listeners('fake.event')); + + $manager->detach(array('AClass', 'anotherMethod'), 'another.event'); + $expected = array( + array('callable' => 'fakeFunction', 'passParams' => false) + ); + $this->assertEquals($expected, $manager->listeners('another.event')); + + $manager->detach('fakeFunction', 'another.event'); + $this->assertEquals(array(), $manager->listeners('another.event')); + } + +/** + * Tests detaching an event from all event queues + * + * @return void + */ + public function testDetachFromAll() { + $manager = new CakeEventManager; + $manager->attach(array('AClass', 'aMethod'), 'fake.event'); + $manager->attach(array('AClass', 'aMethod'), 'another.event'); + $manager->attach('fakeFunction', 'another.event', array('priority' => 1)); + + $manager->detach(array('AClass', 'aMethod')); + $expected = array( + array('callable' => 'fakeFunction', 'passParams' => false) + ); + $this->assertEquals($expected, $manager->listeners('another.event')); + $this->assertEquals(array(), $manager->listeners('fake.event')); + } + +/** + * Tests event dispatching + * + * @return void + */ + public function testDispatch() { + $manager = new CakeEventManager; + $listener = $this->getMock('CakeEventTestListener'); + $anotherListener = $this->getMock('CakeEventTestListener'); + $manager->attach(array($listener, 'listenerFunction'), 'fake.event'); + $manager->attach(array($anotherListener, 'listenerFunction'), 'fake.event'); + $event = new CakeEvent('fake.event'); + + $listener->expects($this->once())->method('listenerFunction')->with($event); + $anotherListener->expects($this->once())->method('listenerFunction')->with($event); + $manager->dispatch($event); + } + +/** + * Tests event dispatching using event key name + * + * @return void + */ + public function testDispatchWithKeyName() { + $manager = new CakeEventManager; + $listener = new CakeEventTestListener; + $manager->attach(array($listener, 'listenerFunction'), 'fake.event'); + $event = 'fake.event'; + $manager->dispatch($event); + + $expected = array('listenerFunction'); + $this->assertEquals($expected, $listener->callStack); + } + +/** + * Tests event dispatching with a return value + * + * @return void + */ + public function testDispatchReturnValue() { + $manager = new CakeEventManager; + $listener = $this->getMock('CakeEventTestListener'); + $anotherListener = $this->getMock('CakeEventTestListener'); + $manager->attach(array($listener, 'listenerFunction'), 'fake.event'); + $manager->attach(array($anotherListener, 'listenerFunction'), 'fake.event'); + $event = new CakeEvent('fake.event'); + + $firstStep = clone $event; + $listener->expects($this->at(0))->method('listenerFunction') + ->with($firstStep) + ->will($this->returnValue('something special')); + $anotherListener->expects($this->at(0))->method('listenerFunction')->with($event); + $manager->dispatch($event); + $this->assertEquals('something special', $event->result); + } + +/** + * Tests that returning false in a callback stops the event + * + * @return void + */ + public function testDispatchFalseStopsEvent() { + $manager = new CakeEventManager; + $listener = $this->getMock('CakeEventTestListener'); + $anotherListener = $this->getMock('CakeEventTestListener'); + $manager->attach(array($listener, 'listenerFunction'), 'fake.event'); + $manager->attach(array($anotherListener, 'listenerFunction'), 'fake.event'); + $event = new CakeEvent('fake.event'); + + $originalEvent = clone $event; + $listener->expects($this->at(0))->method('listenerFunction') + ->with($originalEvent) + ->will($this->returnValue(false)); + $anotherListener->expects($this->never())->method('listenerFunction'); + $manager->dispatch($event); + $this->assertTrue($event->isStopped()); + } + +/** + * Tests event dispatching using priorities + * + * @return void + */ + public function testDispatchPrioritized() { + $manager = new CakeEventManager; + $listener = new CakeEventTestListener; + $manager->attach(array($listener, 'listenerFunction'), 'fake.event'); + $manager->attach(array($listener, 'secondListenerFunction'), 'fake.event', array('priority' => 5)); + $event = new CakeEvent('fake.event'); + $manager->dispatch($event); + + $expected = array('secondListenerFunction', 'listenerFunction'); + $this->assertEquals($expected, $listener->callStack); + } + +/** + * Tests event dispatching with passed params + * + * @return void + */ + public function testDispatchPassingParams() { + $manager = new CakeEventManager; + $listener = $this->getMock('CakeEventTestListener'); + $anotherListener = $this->getMock('CakeEventTestListener'); + $manager->attach(array($listener, 'listenerFunction'), 'fake.event'); + $manager->attach(array($anotherListener, 'secondListenerFunction'), 'fake.event', array('passParams' => true)); + $event = new CakeEvent('fake.event', $this, array('some' => 'data')); + + $listener->expects($this->once())->method('listenerFunction')->with($event); + $anotherListener->expects($this->once())->method('secondListenerFunction')->with('data'); + $manager->dispatch($event); + } + +/** + * Tests subscribing a listener object and firing the events it subscribed to + * + * @return void + */ + public function testAttachSubscriber() { + $manager = new CakeEventManager; + $listener = $this->getMock('CustomTestEventListerner', array('secondListenerFunction')); + $manager->attach($listener); + $event = new CakeEvent('fake.event'); + + $manager->dispatch($event); + + $expected = array('listenerFunction'); + $this->assertEquals($expected, $listener->callStack); + + $listener->expects($this->at(0))->method('secondListenerFunction')->with('data'); + $event = new CakeEvent('another.event', $this, array('some' => 'data')); + $manager->dispatch($event); + + $manager = new CakeEventManager; + $listener = $this->getMock('CustomTestEventListerner', array('listenerFunction', 'thirdListenerFunction')); + $manager->attach($listener); + $event = new CakeEvent('multiple.handlers'); + $listener->expects($this->once())->method('listenerFunction')->with($event); + $listener->expects($this->once())->method('thirdListenerFunction')->with($event); + $manager->dispatch($event); + } + +/** + * Tests subscribing a listener object and firing the events it subscribed to + * + * @return void + */ + public function testDetachSubscriber() { + $manager = new CakeEventManager; + $listener = $this->getMock('CustomTestEventListerner', array('secondListenerFunction')); + $manager->attach($listener); + $expected = array( + array('callable' => array($listener, 'secondListenerFunction'), 'passParams' => true) + ); + $this->assertEquals($expected, $manager->listeners('another.event')); + $expected = array( + array('callable' => array($listener, 'listenerFunction'), 'passParams' => false) + ); + $this->assertEquals($expected, $manager->listeners('fake.event')); + $manager->detach($listener); + $this->assertEquals(array(), $manager->listeners('fake.event')); + $this->assertEquals(array(), $manager->listeners('another.event')); + } + +/** + * Tests that it is possible to get/set the manager singleton + * + * @return void + */ + public function testGlobalDispatcherGetter() { + $this->assertInstanceOf('CakeEventManager', CakeEventManager::instance()); + $manager = new CakeEventManager; + + CakeEventManager::instance($manager); + $this->assertSame($manager, CakeEventManager::instance()); + } + +/** + * Tests that the global event manager gets the event too from any other manager + * + * @return void + */ + public function testDispatchWithGlobal() { + $generalManager = $this->getMock('CakeEventManager', array('dispatch')); + $manager = new CakeEventManager; + $event = new CakeEvent('fake.event'); + CakeEventManager::instance($generalManager); + + $generalManager->expects($this->once())->method('dispatch')->with($event); + $manager->dispatch($event); + } + +/** + * Tests that stopping an event will not notify the rest of the listeners + * + * @return void + */ + public function testStopPropagation() { + $manager = new CakeEventManager; + $listener = new CakeEventTestListener; + $manager->attach(array($listener, 'listenerFunction'), 'fake.event'); + $manager->attach(array($listener, 'stopListener'), 'fake.event', array('priority' => 8)); + $manager->attach(array($listener, 'secondListenerFunction'), 'fake.event', array('priority' => 5)); + $event = new CakeEvent('fake.event'); + $manager->dispatch($event); + + $expected = array('secondListenerFunction'); + $this->assertEquals($expected, $listener->callStack); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Event/CakeEventTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Event/CakeEventTest.php new file mode 100644 index 0000000..592a93a --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Event/CakeEventTest.php @@ -0,0 +1,85 @@ +assertEquals('fake.event', $event->name()); + } + +/** + * Tests the subject() method + * + * @return void + */ + public function testSubject() { + $event = new CakeEvent('fake.event', $this); + $this->assertSame($this, $event->subject()); + + $event = new CakeEvent('fake.event'); + $this->assertNull($event->subject()); + } + +/** + * Tests the event propagation stopping property + * + * @return void + */ + public function testPropagation() { + $event = new CakeEvent('fake.event'); + $this->assertFalse($event->isStopped()); + $event->stopPropagation(); + $this->assertTrue($event->isStopped()); + } + +/** + * Tests that it is possible to get/set custom data in a event + * + * @return void + */ + public function testEventData() { + $event = new CakeEvent('fake.event', $this, array('some' => 'data')); + $this->assertEquals(array('some' => 'data'), $event->data); + } + +/** + * Tests that it is possible to get the name and subject directly + * + * @return void + */ + public function testEventDirectPropertyAccess() { + $event = new CakeEvent('fake.event', $this); + $this->assertEquals($this, $event->subject); + $this->assertEquals('fake.event', $event->name); + } +} \ No newline at end of file diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/I18n/I18nTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/I18n/I18nTest.php new file mode 100644 index 0000000..e86628b --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/I18n/I18nTest.php @@ -0,0 +1,1952 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.I18n + * @since CakePHP(tm) v 1.2.0.5432 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ +App::uses('I18n', 'I18n'); + +/** + * I18nTest class + * + * @package Cake.Test.Case.I18n + */ +class I18nTest extends CakeTestCase { + +/** + * setUp method + * + * @return void + */ + public function setUp() { + Cache::delete('object_map', '_cake_core_'); + App::build(array( + 'Locale' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Locale' . DS), + 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS) + ), App::RESET); + CakePlugin::load(array('TestPlugin')); + } + +/** + * tearDown method + * + * @return void + */ + public function tearDown() { + Cache::delete('object_map', '_cake_core_'); + App::build(); + CakePlugin::unload(); + } + +/** + * testTranslationCaching method + * + * @return void + */ + public function testTranslationCaching() { + Configure::write('Config.language', 'cache_test_po'); + + // reset internally stored entries + I18n::clear(); + + Cache::clear(false, '_cake_core_'); + $lang = Configure::read('Config.language'); + + Cache::config('_cake_core_', Cache::config('default')); + + // make some calls to translate using different domains + $this->assertEquals('Dom 1 Foo', I18n::translate('dom1.foo', false, 'dom1')); + $this->assertEquals('Dom 1 Bar', I18n::translate('dom1.bar', false, 'dom1')); + $domains = I18n::domains(); + $this->assertEquals('Dom 1 Foo', $domains['dom1']['cache_test_po']['LC_MESSAGES']['dom1.foo']); + + // reset internally stored entries + I18n::clear(); + + // now only dom1 should be in cache + $cachedDom1 = Cache::read('dom1_' . $lang, '_cake_core_'); + $this->assertEquals('Dom 1 Foo', $cachedDom1['LC_MESSAGES']['dom1.foo']); + $this->assertEquals('Dom 1 Bar', $cachedDom1['LC_MESSAGES']['dom1.bar']); + // dom2 not in cache + $this->assertFalse(Cache::read('dom2_' . $lang, '_cake_core_')); + + // translate a item of dom2 (adds dom2 to cache) + $this->assertEquals('Dom 2 Foo', I18n::translate('dom2.foo', false, 'dom2')); + + // verify dom2 was cached through manual read from cache + $cachedDom2 = Cache::read('dom2_' . $lang, '_cake_core_'); + $this->assertEquals('Dom 2 Foo', $cachedDom2['LC_MESSAGES']['dom2.foo']); + $this->assertEquals('Dom 2 Bar', $cachedDom2['LC_MESSAGES']['dom2.bar']); + + // modify cache entry manually to verify that dom1 entries now will be read from cache + $cachedDom1['LC_MESSAGES']['dom1.foo'] = 'FOO'; + Cache::write('dom1_' . $lang, $cachedDom1, '_cake_core_'); + $this->assertEquals('FOO', I18n::translate('dom1.foo', false, 'dom1')); + } + +/** + * testDefaultStrings method + * + * @return void + */ + public function testDefaultStrings() { + $singular = $this->__singular(); + $this->assertEquals('Plural Rule 1', $singular); + + $plurals = $this->__plural(); + $this->assertTrue(in_array('0 = 0 or > 1', $plurals)); + $this->assertTrue(in_array('1 = 1', $plurals)); + $this->assertTrue(in_array('2 = 0 or > 1', $plurals)); + $this->assertTrue(in_array('3 = 0 or > 1', $plurals)); + $this->assertTrue(in_array('4 = 0 or > 1', $plurals)); + $this->assertTrue(in_array('5 = 0 or > 1', $plurals)); + $this->assertTrue(in_array('6 = 0 or > 1', $plurals)); + $this->assertTrue(in_array('7 = 0 or > 1', $plurals)); + $this->assertTrue(in_array('8 = 0 or > 1', $plurals)); + $this->assertTrue(in_array('9 = 0 or > 1', $plurals)); + $this->assertTrue(in_array('10 = 0 or > 1', $plurals)); + $this->assertTrue(in_array('11 = 0 or > 1', $plurals)); + $this->assertTrue(in_array('12 = 0 or > 1', $plurals)); + $this->assertTrue(in_array('13 = 0 or > 1', $plurals)); + $this->assertTrue(in_array('14 = 0 or > 1', $plurals)); + $this->assertTrue(in_array('15 = 0 or > 1', $plurals)); + $this->assertTrue(in_array('16 = 0 or > 1', $plurals)); + $this->assertTrue(in_array('17 = 0 or > 1', $plurals)); + $this->assertTrue(in_array('18 = 0 or > 1', $plurals)); + $this->assertTrue(in_array('19 = 0 or > 1', $plurals)); + $this->assertTrue(in_array('20 = 0 or > 1', $plurals)); + $this->assertTrue(in_array('21 = 0 or > 1', $plurals)); + $this->assertTrue(in_array('22 = 0 or > 1', $plurals)); + $this->assertTrue(in_array('23 = 0 or > 1', $plurals)); + $this->assertTrue(in_array('24 = 0 or > 1', $plurals)); + $this->assertTrue(in_array('25 = 0 or > 1', $plurals)); + + $coreSingular = $this->__singularFromCore(); + $this->assertEquals('Plural Rule 1 (from core)', $coreSingular); + + $corePlurals = $this->__pluralFromCore(); + $this->assertTrue(in_array('0 = 0 or > 1 (from core)', $corePlurals)); + $this->assertTrue(in_array('1 = 1 (from core)', $corePlurals)); + $this->assertTrue(in_array('2 = 0 or > 1 (from core)', $corePlurals)); + $this->assertTrue(in_array('3 = 0 or > 1 (from core)', $corePlurals)); + $this->assertTrue(in_array('4 = 0 or > 1 (from core)', $corePlurals)); + $this->assertTrue(in_array('5 = 0 or > 1 (from core)', $corePlurals)); + $this->assertTrue(in_array('6 = 0 or > 1 (from core)', $corePlurals)); + $this->assertTrue(in_array('7 = 0 or > 1 (from core)', $corePlurals)); + $this->assertTrue(in_array('8 = 0 or > 1 (from core)', $corePlurals)); + $this->assertTrue(in_array('9 = 0 or > 1 (from core)', $corePlurals)); + $this->assertTrue(in_array('10 = 0 or > 1 (from core)', $corePlurals)); + $this->assertTrue(in_array('11 = 0 or > 1 (from core)', $corePlurals)); + $this->assertTrue(in_array('12 = 0 or > 1 (from core)', $corePlurals)); + $this->assertTrue(in_array('13 = 0 or > 1 (from core)', $corePlurals)); + $this->assertTrue(in_array('14 = 0 or > 1 (from core)', $corePlurals)); + $this->assertTrue(in_array('15 = 0 or > 1 (from core)', $corePlurals)); + $this->assertTrue(in_array('16 = 0 or > 1 (from core)', $corePlurals)); + $this->assertTrue(in_array('17 = 0 or > 1 (from core)', $corePlurals)); + $this->assertTrue(in_array('18 = 0 or > 1 (from core)', $corePlurals)); + $this->assertTrue(in_array('19 = 0 or > 1 (from core)', $corePlurals)); + $this->assertTrue(in_array('20 = 0 or > 1 (from core)', $corePlurals)); + $this->assertTrue(in_array('21 = 0 or > 1 (from core)', $corePlurals)); + $this->assertTrue(in_array('22 = 0 or > 1 (from core)', $corePlurals)); + $this->assertTrue(in_array('23 = 0 or > 1 (from core)', $corePlurals)); + $this->assertTrue(in_array('24 = 0 or > 1 (from core)', $corePlurals)); + $this->assertTrue(in_array('25 = 0 or > 1 (from core)', $corePlurals)); + } + +/** + * testPoRulesZero method + * + * @return void + */ + public function testPoRulesZero() { + Configure::write('Config.language', 'rule_0_po'); + $this->assertRulesZero(); + } + +/** + * testMoRulesZero method + * + * @return void + */ + public function testMoRulesZero() { + Configure::write('Config.language', 'rule_0_mo'); + $this->assertRulesZero(); + } + +/** + * Assertions for rules zero. + * + * @return + */ + public function assertRulesZero() { + $singular = $this->__singular(); + $this->assertEquals('Plural Rule 0 (translated)', $singular); + + $plurals = $this->__plural(); + $this->assertTrue(in_array('0 ends with any # (translated)', $plurals)); + $this->assertTrue(in_array('1 ends with any # (translated)', $plurals)); + $this->assertTrue(in_array('2 ends with any # (translated)', $plurals)); + $this->assertTrue(in_array('3 ends with any # (translated)', $plurals)); + $this->assertTrue(in_array('4 ends with any # (translated)', $plurals)); + $this->assertTrue(in_array('5 ends with any # (translated)', $plurals)); + $this->assertTrue(in_array('6 ends with any # (translated)', $plurals)); + $this->assertTrue(in_array('7 ends with any # (translated)', $plurals)); + $this->assertTrue(in_array('8 ends with any # (translated)', $plurals)); + $this->assertTrue(in_array('9 ends with any # (translated)', $plurals)); + $this->assertTrue(in_array('10 ends with any # (translated)', $plurals)); + $this->assertTrue(in_array('11 ends with any # (translated)', $plurals)); + $this->assertTrue(in_array('12 ends with any # (translated)', $plurals)); + $this->assertTrue(in_array('13 ends with any # (translated)', $plurals)); + $this->assertTrue(in_array('14 ends with any # (translated)', $plurals)); + $this->assertTrue(in_array('15 ends with any # (translated)', $plurals)); + $this->assertTrue(in_array('16 ends with any # (translated)', $plurals)); + $this->assertTrue(in_array('17 ends with any # (translated)', $plurals)); + $this->assertTrue(in_array('18 ends with any # (translated)', $plurals)); + $this->assertTrue(in_array('19 ends with any # (translated)', $plurals)); + $this->assertTrue(in_array('20 ends with any # (translated)', $plurals)); + $this->assertTrue(in_array('21 ends with any # (translated)', $plurals)); + $this->assertTrue(in_array('22 ends with any # (translated)', $plurals)); + $this->assertTrue(in_array('23 ends with any # (translated)', $plurals)); + $this->assertTrue(in_array('24 ends with any # (translated)', $plurals)); + $this->assertTrue(in_array('25 ends with any # (translated)', $plurals)); + + $coreSingular = $this->__singularFromCore(); + $this->assertEquals('Plural Rule 0 (from core translated)', $coreSingular); + + $corePlurals = $this->__pluralFromCore(); + $this->assertTrue(in_array('0 ends with any # (from core translated)', $corePlurals)); + $this->assertTrue(in_array('1 ends with any # (from core translated)', $corePlurals)); + $this->assertTrue(in_array('2 ends with any # (from core translated)', $corePlurals)); + $this->assertTrue(in_array('3 ends with any # (from core translated)', $corePlurals)); + $this->assertTrue(in_array('4 ends with any # (from core translated)', $corePlurals)); + $this->assertTrue(in_array('5 ends with any # (from core translated)', $corePlurals)); + $this->assertTrue(in_array('6 ends with any # (from core translated)', $corePlurals)); + $this->assertTrue(in_array('7 ends with any # (from core translated)', $corePlurals)); + $this->assertTrue(in_array('8 ends with any # (from core translated)', $corePlurals)); + $this->assertTrue(in_array('9 ends with any # (from core translated)', $corePlurals)); + $this->assertTrue(in_array('10 ends with any # (from core translated)', $corePlurals)); + $this->assertTrue(in_array('11 ends with any # (from core translated)', $corePlurals)); + $this->assertTrue(in_array('12 ends with any # (from core translated)', $corePlurals)); + $this->assertTrue(in_array('13 ends with any # (from core translated)', $corePlurals)); + $this->assertTrue(in_array('14 ends with any # (from core translated)', $corePlurals)); + $this->assertTrue(in_array('15 ends with any # (from core translated)', $corePlurals)); + $this->assertTrue(in_array('16 ends with any # (from core translated)', $corePlurals)); + $this->assertTrue(in_array('17 ends with any # (from core translated)', $corePlurals)); + $this->assertTrue(in_array('18 ends with any # (from core translated)', $corePlurals)); + $this->assertTrue(in_array('19 ends with any # (from core translated)', $corePlurals)); + $this->assertTrue(in_array('20 ends with any # (from core translated)', $corePlurals)); + $this->assertTrue(in_array('21 ends with any # (from core translated)', $corePlurals)); + $this->assertTrue(in_array('22 ends with any # (from core translated)', $corePlurals)); + $this->assertTrue(in_array('23 ends with any # (from core translated)', $corePlurals)); + $this->assertTrue(in_array('24 ends with any # (from core translated)', $corePlurals)); + $this->assertTrue(in_array('25 ends with any # (from core translated)', $corePlurals)); + } + +/** + * testPoRulesOne method + * + * @return void + */ + public function testPoRulesOne() { + Configure::write('Config.language', 'rule_1_po'); + $this->assertRulesOne(); + } + +/** + * testMoRulesOne method + * + * @return void + */ + public function testMoRulesOne() { + Configure::write('Config.language', 'rule_1_mo'); + $this->assertRulesOne(); + } + +/** + * Assertions for plural rule one + * + * @return void + */ + public function assertRulesOne() { + $singular = $this->__singular(); + $this->assertEquals('Plural Rule 1 (translated)', $singular); + + $plurals = $this->__plural(); + $this->assertTrue(in_array('0 = 0 or > 1 (translated)', $plurals)); + $this->assertTrue(in_array('1 = 1 (translated)', $plurals)); + $this->assertTrue(in_array('2 = 0 or > 1 (translated)', $plurals)); + $this->assertTrue(in_array('3 = 0 or > 1 (translated)', $plurals)); + $this->assertTrue(in_array('4 = 0 or > 1 (translated)', $plurals)); + $this->assertTrue(in_array('5 = 0 or > 1 (translated)', $plurals)); + $this->assertTrue(in_array('6 = 0 or > 1 (translated)', $plurals)); + $this->assertTrue(in_array('7 = 0 or > 1 (translated)', $plurals)); + $this->assertTrue(in_array('8 = 0 or > 1 (translated)', $plurals)); + $this->assertTrue(in_array('9 = 0 or > 1 (translated)', $plurals)); + $this->assertTrue(in_array('10 = 0 or > 1 (translated)', $plurals)); + $this->assertTrue(in_array('11 = 0 or > 1 (translated)', $plurals)); + $this->assertTrue(in_array('12 = 0 or > 1 (translated)', $plurals)); + $this->assertTrue(in_array('13 = 0 or > 1 (translated)', $plurals)); + $this->assertTrue(in_array('14 = 0 or > 1 (translated)', $plurals)); + $this->assertTrue(in_array('15 = 0 or > 1 (translated)', $plurals)); + $this->assertTrue(in_array('16 = 0 or > 1 (translated)', $plurals)); + $this->assertTrue(in_array('17 = 0 or > 1 (translated)', $plurals)); + $this->assertTrue(in_array('18 = 0 or > 1 (translated)', $plurals)); + $this->assertTrue(in_array('19 = 0 or > 1 (translated)', $plurals)); + $this->assertTrue(in_array('20 = 0 or > 1 (translated)', $plurals)); + $this->assertTrue(in_array('21 = 0 or > 1 (translated)', $plurals)); + $this->assertTrue(in_array('22 = 0 or > 1 (translated)', $plurals)); + $this->assertTrue(in_array('23 = 0 or > 1 (translated)', $plurals)); + $this->assertTrue(in_array('24 = 0 or > 1 (translated)', $plurals)); + $this->assertTrue(in_array('25 = 0 or > 1 (translated)', $plurals)); + + $coreSingular = $this->__singularFromCore(); + $this->assertEquals('Plural Rule 1 (from core translated)', $coreSingular); + + $corePlurals = $this->__pluralFromCore(); + $this->assertTrue(in_array('0 = 0 or > 1 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('1 = 1 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('2 = 0 or > 1 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('3 = 0 or > 1 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('4 = 0 or > 1 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('5 = 0 or > 1 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('6 = 0 or > 1 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('7 = 0 or > 1 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('8 = 0 or > 1 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('9 = 0 or > 1 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('10 = 0 or > 1 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('11 = 0 or > 1 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('12 = 0 or > 1 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('13 = 0 or > 1 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('14 = 0 or > 1 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('15 = 0 or > 1 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('16 = 0 or > 1 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('17 = 0 or > 1 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('18 = 0 or > 1 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('19 = 0 or > 1 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('20 = 0 or > 1 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('21 = 0 or > 1 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('22 = 0 or > 1 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('23 = 0 or > 1 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('24 = 0 or > 1 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('25 = 0 or > 1 (from core translated)', $corePlurals)); + } + +/** + * testMoRulesTwo method + * + * @return void + */ + public function testMoRulesTwo() { + Configure::write('Config.language', 'rule_2_mo'); + $this->assertRulesTwo(); + } + +/** + * testPoRulesTwo method + * + * @return void + */ + public function testPoRulesTwo() { + Configure::write('Config.language', 'rule_2_po'); + $this->assertRulesTwo(); + } + +/** + * Assertions for rules Two + * + * @return void + */ + public function assertRulesTwo() { + $singular = $this->__singular(); + $this->assertEquals('Plural Rule 2 (translated)', $singular); + + $plurals = $this->__plural(); + $this->assertTrue(in_array('0 = 0 or 1 (translated)', $plurals)); + $this->assertTrue(in_array('1 = 0 or 1 (translated)', $plurals)); + $this->assertTrue(in_array('2 > 1 (translated)', $plurals)); + $this->assertTrue(in_array('3 > 1 (translated)', $plurals)); + $this->assertTrue(in_array('4 > 1 (translated)', $plurals)); + $this->assertTrue(in_array('5 > 1 (translated)', $plurals)); + $this->assertTrue(in_array('6 > 1 (translated)', $plurals)); + $this->assertTrue(in_array('7 > 1 (translated)', $plurals)); + $this->assertTrue(in_array('8 > 1 (translated)', $plurals)); + $this->assertTrue(in_array('9 > 1 (translated)', $plurals)); + $this->assertTrue(in_array('10 > 1 (translated)', $plurals)); + $this->assertTrue(in_array('11 > 1 (translated)', $plurals)); + $this->assertTrue(in_array('12 > 1 (translated)', $plurals)); + $this->assertTrue(in_array('13 > 1 (translated)', $plurals)); + $this->assertTrue(in_array('14 > 1 (translated)', $plurals)); + $this->assertTrue(in_array('15 > 1 (translated)', $plurals)); + $this->assertTrue(in_array('16 > 1 (translated)', $plurals)); + $this->assertTrue(in_array('17 > 1 (translated)', $plurals)); + $this->assertTrue(in_array('18 > 1 (translated)', $plurals)); + $this->assertTrue(in_array('19 > 1 (translated)', $plurals)); + $this->assertTrue(in_array('20 > 1 (translated)', $plurals)); + $this->assertTrue(in_array('21 > 1 (translated)', $plurals)); + $this->assertTrue(in_array('22 > 1 (translated)', $plurals)); + $this->assertTrue(in_array('23 > 1 (translated)', $plurals)); + $this->assertTrue(in_array('24 > 1 (translated)', $plurals)); + $this->assertTrue(in_array('25 > 1 (translated)', $plurals)); + + $coreSingular = $this->__singularFromCore(); + $this->assertEquals('Plural Rule 2 (from core translated)', $coreSingular); + + $corePlurals = $this->__pluralFromCore(); + $this->assertTrue(in_array('0 = 0 or 1 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('1 = 0 or 1 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('2 > 1 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('3 > 1 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('4 > 1 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('5 > 1 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('6 > 1 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('7 > 1 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('8 > 1 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('9 > 1 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('10 > 1 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('11 > 1 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('12 > 1 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('13 > 1 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('14 > 1 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('15 > 1 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('16 > 1 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('17 > 1 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('18 > 1 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('19 > 1 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('20 > 1 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('21 > 1 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('22 > 1 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('23 > 1 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('24 > 1 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('25 > 1 (from core translated)', $corePlurals)); + } + +/** + * testPoRulesThree method + * + * @return void + */ + public function testPoRulesThree() { + Configure::write('Config.language', 'rule_3_po'); + $this->assertRulesThree(); + } + +/** + * testMoRulesThree method + * + * @return void + */ + public function testMoRulesThree() { + Configure::write('Config.language', 'rule_3_mo'); + $this->assertRulesThree(); + } + +/** + * Assert rules for plural three. + * + * @return void + */ + public function assertRulesThree() { + $singular = $this->__singular(); + $this->assertEquals('Plural Rule 3 (translated)', $singular); + + $plurals = $this->__plural(); + $this->assertTrue(in_array('0 = 0 (translated)', $plurals)); + $this->assertTrue(in_array('1 ends 1 but not 11 (translated)', $plurals)); + $this->assertTrue(in_array('2 everything else (translated)', $plurals)); + $this->assertTrue(in_array('3 everything else (translated)', $plurals)); + $this->assertTrue(in_array('4 everything else (translated)', $plurals)); + $this->assertTrue(in_array('5 everything else (translated)', $plurals)); + $this->assertTrue(in_array('6 everything else (translated)', $plurals)); + $this->assertTrue(in_array('7 everything else (translated)', $plurals)); + $this->assertTrue(in_array('8 everything else (translated)', $plurals)); + $this->assertTrue(in_array('9 everything else (translated)', $plurals)); + $this->assertTrue(in_array('10 everything else (translated)', $plurals)); + $this->assertTrue(in_array('11 everything else (translated)', $plurals)); + $this->assertTrue(in_array('12 everything else (translated)', $plurals)); + $this->assertTrue(in_array('13 everything else (translated)', $plurals)); + $this->assertTrue(in_array('14 everything else (translated)', $plurals)); + $this->assertTrue(in_array('15 everything else (translated)', $plurals)); + $this->assertTrue(in_array('16 everything else (translated)', $plurals)); + $this->assertTrue(in_array('17 everything else (translated)', $plurals)); + $this->assertTrue(in_array('18 everything else (translated)', $plurals)); + $this->assertTrue(in_array('19 everything else (translated)', $plurals)); + $this->assertTrue(in_array('20 everything else (translated)', $plurals)); + $this->assertTrue(in_array('21 ends 1 but not 11 (translated)', $plurals)); + $this->assertTrue(in_array('22 everything else (translated)', $plurals)); + $this->assertTrue(in_array('23 everything else (translated)', $plurals)); + $this->assertTrue(in_array('24 everything else (translated)', $plurals)); + $this->assertTrue(in_array('25 everything else (translated)', $plurals)); + + $coreSingular = $this->__singularFromCore(); + $this->assertEquals('Plural Rule 3 (from core translated)', $coreSingular); + + $corePlurals = $this->__pluralFromCore(); + $this->assertTrue(in_array('0 = 0 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('1 ends 1 but not 11 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('2 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('3 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('4 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('5 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('6 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('7 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('8 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('9 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('10 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('11 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('12 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('13 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('14 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('15 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('16 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('17 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('18 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('19 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('20 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('21 ends 1 but not 11 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('22 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('23 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('24 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('25 everything else (from core translated)', $corePlurals)); + } + +/** + * testPoRulesFour method + * + * @return void + */ + public function testPoRulesFour() { + Configure::write('Config.language', 'rule_4_po'); + $this->assertRulesFour(); + } + +/** + * testMoRulesFour method + * + * @return void + */ + public function testMoRulesFour() { + Configure::write('Config.language', 'rule_4_mo'); + $this->assertRulesFour(); + } + +/** + * Run the assertions for Rule 4 plurals. + * + * @return void + */ + public function assertRulesFour() { + $singular = $this->__singular(); + $this->assertEquals('Plural Rule 4 (translated)', $singular); + + $plurals = $this->__plural(); + $this->assertTrue(in_array('0 everything else (translated)', $plurals)); + $this->assertTrue(in_array('1 = 1 (translated)', $plurals)); + $this->assertTrue(in_array('2 = 2 (translated)', $plurals)); + $this->assertTrue(in_array('3 everything else (translated)', $plurals)); + $this->assertTrue(in_array('4 everything else (translated)', $plurals)); + $this->assertTrue(in_array('5 everything else (translated)', $plurals)); + $this->assertTrue(in_array('6 everything else (translated)', $plurals)); + $this->assertTrue(in_array('7 everything else (translated)', $plurals)); + $this->assertTrue(in_array('8 everything else (translated)', $plurals)); + $this->assertTrue(in_array('9 everything else (translated)', $plurals)); + $this->assertTrue(in_array('10 everything else (translated)', $plurals)); + $this->assertTrue(in_array('11 everything else (translated)', $plurals)); + $this->assertTrue(in_array('12 everything else (translated)', $plurals)); + $this->assertTrue(in_array('13 everything else (translated)', $plurals)); + $this->assertTrue(in_array('14 everything else (translated)', $plurals)); + $this->assertTrue(in_array('15 everything else (translated)', $plurals)); + $this->assertTrue(in_array('16 everything else (translated)', $plurals)); + $this->assertTrue(in_array('17 everything else (translated)', $plurals)); + $this->assertTrue(in_array('18 everything else (translated)', $plurals)); + $this->assertTrue(in_array('19 everything else (translated)', $plurals)); + $this->assertTrue(in_array('20 everything else (translated)', $plurals)); + $this->assertTrue(in_array('21 everything else (translated)', $plurals)); + $this->assertTrue(in_array('22 everything else (translated)', $plurals)); + $this->assertTrue(in_array('23 everything else (translated)', $plurals)); + $this->assertTrue(in_array('24 everything else (translated)', $plurals)); + $this->assertTrue(in_array('25 everything else (translated)', $plurals)); + + $coreSingular = $this->__singularFromCore(); + $this->assertEquals('Plural Rule 4 (from core translated)', $coreSingular); + + $corePlurals = $this->__pluralFromCore(); + $this->assertTrue(in_array('0 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('1 = 1 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('2 = 2 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('3 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('4 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('5 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('6 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('7 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('8 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('9 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('10 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('11 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('12 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('13 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('14 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('15 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('16 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('17 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('18 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('19 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('20 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('21 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('22 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('23 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('24 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('25 everything else (from core translated)', $corePlurals)); + } + +/** + * testPoRulesFive method + * + * @return void + */ + public function testPoRulesFive() { + Configure::write('Config.language', 'rule_5_po'); + $this->assertRulesFive(); + } + +/** + * testMoRulesFive method + * + * @return void + */ + public function testMoRulesFive() { + Configure::write('Config.language', 'rule_5_mo'); + $this->assertRulesFive(); + } + +/** + * Run the assertions for rule 5 plurals + * + * @return void + */ + public function assertRulesFive() { + $singular = $this->__singular(); + $this->assertEquals('Plural Rule 5 (translated)', $singular); + + $plurals = $this->__plural(); + $this->assertTrue(in_array('0 = 0 or ends in 01-19 (translated)', $plurals)); + $this->assertTrue(in_array('0 = 0 or ends in 01-19 (translated)', $plurals)); + $this->assertTrue(in_array('1 = 1 (translated)', $plurals)); + $this->assertTrue(in_array('2 = 0 or ends in 01-19 (translated)', $plurals)); + $this->assertTrue(in_array('3 = 0 or ends in 01-19 (translated)', $plurals)); + $this->assertTrue(in_array('4 = 0 or ends in 01-19 (translated)', $plurals)); + $this->assertTrue(in_array('5 = 0 or ends in 01-19 (translated)', $plurals)); + $this->assertTrue(in_array('6 = 0 or ends in 01-19 (translated)', $plurals)); + $this->assertTrue(in_array('7 = 0 or ends in 01-19 (translated)', $plurals)); + $this->assertTrue(in_array('8 = 0 or ends in 01-19 (translated)', $plurals)); + $this->assertTrue(in_array('9 = 0 or ends in 01-19 (translated)', $plurals)); + $this->assertTrue(in_array('10 = 0 or ends in 01-19 (translated)', $plurals)); + $this->assertTrue(in_array('11 = 0 or ends in 01-19 (translated)', $plurals)); + $this->assertTrue(in_array('12 = 0 or ends in 01-19 (translated)', $plurals)); + $this->assertTrue(in_array('13 = 0 or ends in 01-19 (translated)', $plurals)); + $this->assertTrue(in_array('14 = 0 or ends in 01-19 (translated)', $plurals)); + $this->assertTrue(in_array('15 = 0 or ends in 01-19 (translated)', $plurals)); + $this->assertTrue(in_array('16 = 0 or ends in 01-19 (translated)', $plurals)); + $this->assertTrue(in_array('17 = 0 or ends in 01-19 (translated)', $plurals)); + $this->assertTrue(in_array('18 = 0 or ends in 01-19 (translated)', $plurals)); + $this->assertTrue(in_array('19 = 0 or ends in 01-19 (translated)', $plurals)); + $this->assertTrue(in_array('20 everything else (translated)', $plurals)); + $this->assertTrue(in_array('21 everything else (translated)', $plurals)); + $this->assertTrue(in_array('22 everything else (translated)', $plurals)); + $this->assertTrue(in_array('23 everything else (translated)', $plurals)); + $this->assertTrue(in_array('24 everything else (translated)', $plurals)); + $this->assertTrue(in_array('25 everything else (translated)', $plurals)); + + $coreSingular = $this->__singularFromCore(); + $this->assertEquals('Plural Rule 5 (from core translated)', $coreSingular); + + $corePlurals = $this->__pluralFromCore(); + $this->assertTrue(in_array('0 = 0 or ends in 01-19 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('0 = 0 or ends in 01-19 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('1 = 1 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('2 = 0 or ends in 01-19 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('3 = 0 or ends in 01-19 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('4 = 0 or ends in 01-19 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('5 = 0 or ends in 01-19 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('6 = 0 or ends in 01-19 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('7 = 0 or ends in 01-19 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('8 = 0 or ends in 01-19 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('9 = 0 or ends in 01-19 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('10 = 0 or ends in 01-19 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('11 = 0 or ends in 01-19 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('12 = 0 or ends in 01-19 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('13 = 0 or ends in 01-19 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('14 = 0 or ends in 01-19 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('15 = 0 or ends in 01-19 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('16 = 0 or ends in 01-19 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('17 = 0 or ends in 01-19 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('18 = 0 or ends in 01-19 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('19 = 0 or ends in 01-19 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('20 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('21 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('22 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('23 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('24 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('25 everything else (from core translated)', $corePlurals)); + } + +/** + * testPoRulesSix method + * + * @return void + */ + public function testPoRulesSix() { + Configure::write('Config.language', 'rule_6_po'); + $this->assertRulesSix(); + } + +/** + * testMoRulesSix method + * + * @return void + */ + public function testMoRulesSix() { + Configure::write('Config.language', 'rule_6_mo'); + $this->assertRulesSix(); + } + +/** + * Assertions for the sixth plural rules. + * + * @return void + */ + public function assertRulesSix() { + $singular = $this->__singular(); + $this->assertEquals('Plural Rule 6 (translated)', $singular); + + $plurals = $this->__plural(); + $this->assertTrue(in_array('0 ends in 0 or ends in 10-20 (translated)', $plurals)); + $this->assertTrue(in_array('1 ends in 1, not 11 (translated)', $plurals)); + $this->assertTrue(in_array('2 everything else (translated)', $plurals)); + $this->assertTrue(in_array('3 everything else (translated)', $plurals)); + $this->assertTrue(in_array('4 everything else (translated)', $plurals)); + $this->assertTrue(in_array('5 everything else (translated)', $plurals)); + $this->assertTrue(in_array('6 everything else (translated)', $plurals)); + $this->assertTrue(in_array('7 everything else (translated)', $plurals)); + $this->assertTrue(in_array('8 everything else (translated)', $plurals)); + $this->assertTrue(in_array('9 everything else (translated)', $plurals)); + $this->assertTrue(in_array('10 ends in 0 or ends in 10-20 (translated)', $plurals)); + $this->assertTrue(in_array('11 ends in 0 or ends in 10-20 (translated)', $plurals)); + $this->assertTrue(in_array('12 ends in 0 or ends in 10-20 (translated)', $plurals)); + $this->assertTrue(in_array('13 ends in 0 or ends in 10-20 (translated)', $plurals)); + $this->assertTrue(in_array('14 ends in 0 or ends in 10-20 (translated)', $plurals)); + $this->assertTrue(in_array('15 ends in 0 or ends in 10-20 (translated)', $plurals)); + $this->assertTrue(in_array('16 ends in 0 or ends in 10-20 (translated)', $plurals)); + $this->assertTrue(in_array('17 ends in 0 or ends in 10-20 (translated)', $plurals)); + $this->assertTrue(in_array('18 ends in 0 or ends in 10-20 (translated)', $plurals)); + $this->assertTrue(in_array('19 ends in 0 or ends in 10-20 (translated)', $plurals)); + $this->assertTrue(in_array('20 ends in 0 or ends in 10-20 (translated)', $plurals)); + $this->assertTrue(in_array('21 ends in 1, not 11 (translated)', $plurals)); + $this->assertTrue(in_array('22 everything else (translated)', $plurals)); + $this->assertTrue(in_array('23 everything else (translated)', $plurals)); + $this->assertTrue(in_array('24 everything else (translated)', $plurals)); + $this->assertTrue(in_array('25 everything else (translated)', $plurals)); + + $coreSingular = $this->__singularFromCore(); + $this->assertEquals('Plural Rule 6 (from core translated)', $coreSingular); + + $corePlurals = $this->__pluralFromCore(); + $this->assertTrue(in_array('0 ends in 0 or ends in 10-20 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('1 ends in 1, not 11 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('2 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('3 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('4 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('5 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('6 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('7 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('8 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('9 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('10 ends in 0 or ends in 10-20 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('11 ends in 0 or ends in 10-20 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('12 ends in 0 or ends in 10-20 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('13 ends in 0 or ends in 10-20 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('14 ends in 0 or ends in 10-20 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('15 ends in 0 or ends in 10-20 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('16 ends in 0 or ends in 10-20 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('17 ends in 0 or ends in 10-20 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('18 ends in 0 or ends in 10-20 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('19 ends in 0 or ends in 10-20 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('20 ends in 0 or ends in 10-20 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('21 ends in 1, not 11 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('22 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('23 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('24 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('25 everything else (from core translated)', $corePlurals)); + } + +/** + * testPoRulesSeven method + * + * @return void + */ + public function testPoRulesSeven() { + Configure::write('Config.language', 'rule_7_po'); + $this->assertRulesSeven(); + } + +/** + * testMoRulesSeven method + * + * @return void + */ + public function testMoRulesSeven() { + Configure::write('Config.language', 'rule_7_mo'); + $this->assertRulesSeven(); + } + +/** + * Run assertions for seventh plural rules + * + * @return void + */ + public function assertRulesSeven() { + $singular = $this->__singular(); + $this->assertEquals('Plural Rule 7 (translated)', $singular); + + $plurals = $this->__plural(); + $this->assertTrue(in_array('0 everything else (translated)', $plurals)); + $this->assertTrue(in_array('1 ends in 1, not 11 (translated)', $plurals)); + $this->assertTrue(in_array('2 ends in 2-4, not 12-14 (translated)', $plurals)); + $this->assertTrue(in_array('3 ends in 2-4, not 12-14 (translated)', $plurals)); + $this->assertTrue(in_array('4 ends in 2-4, not 12-14 (translated)', $plurals)); + $this->assertTrue(in_array('5 everything else (translated)', $plurals)); + $this->assertTrue(in_array('6 everything else (translated)', $plurals)); + $this->assertTrue(in_array('7 everything else (translated)', $plurals)); + $this->assertTrue(in_array('8 everything else (translated)', $plurals)); + $this->assertTrue(in_array('9 everything else (translated)', $plurals)); + $this->assertTrue(in_array('10 everything else (translated)', $plurals)); + $this->assertTrue(in_array('11 everything else (translated)', $plurals)); + $this->assertTrue(in_array('12 everything else (translated)', $plurals)); + $this->assertTrue(in_array('13 everything else (translated)', $plurals)); + $this->assertTrue(in_array('14 everything else (translated)', $plurals)); + $this->assertTrue(in_array('15 everything else (translated)', $plurals)); + $this->assertTrue(in_array('16 everything else (translated)', $plurals)); + $this->assertTrue(in_array('17 everything else (translated)', $plurals)); + $this->assertTrue(in_array('18 everything else (translated)', $plurals)); + $this->assertTrue(in_array('19 everything else (translated)', $plurals)); + $this->assertTrue(in_array('20 everything else (translated)', $plurals)); + $this->assertTrue(in_array('21 ends in 1, not 11 (translated)', $plurals)); + $this->assertTrue(in_array('22 ends in 2-4, not 12-14 (translated)', $plurals)); + $this->assertTrue(in_array('23 ends in 2-4, not 12-14 (translated)', $plurals)); + $this->assertTrue(in_array('24 ends in 2-4, not 12-14 (translated)', $plurals)); + $this->assertTrue(in_array('25 everything else (translated)', $plurals)); + + $coreSingular = $this->__singularFromCore(); + $this->assertEquals('Plural Rule 7 (from core translated)', $coreSingular); + + $corePlurals = $this->__pluralFromCore(); + $this->assertTrue(in_array('0 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('1 ends in 1, not 11 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('2 ends in 2-4, not 12-14 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('3 ends in 2-4, not 12-14 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('4 ends in 2-4, not 12-14 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('5 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('6 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('7 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('8 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('9 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('10 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('11 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('12 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('13 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('14 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('15 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('16 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('17 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('18 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('19 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('20 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('21 ends in 1, not 11 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('22 ends in 2-4, not 12-14 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('23 ends in 2-4, not 12-14 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('24 ends in 2-4, not 12-14 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('25 everything else (from core translated)', $corePlurals)); + } + +/** + * testPoRulesEight method + * + * @return void + */ + public function testPoRulesEight() { + Configure::write('Config.language', 'rule_8_po'); + $this->assertRulesEight(); + } + +/** + * testMoRulesEight method + * + * @return void + */ + public function testMoRulesEight() { + Configure::write('Config.language', 'rule_8_mo'); + $this->assertRulesEight(); + } + +/** + * Run assertions for the eighth plural rule. + * + * @return void + */ + public function assertRulesEight() { + $singular = $this->__singular(); + $this->assertEquals('Plural Rule 8 (translated)', $singular); + + $plurals = $this->__plural(); + $this->assertTrue(in_array('0 everything else (translated)', $plurals)); + $this->assertTrue(in_array('1 is 1 (translated)', $plurals)); + $this->assertTrue(in_array('2 is 2-4 (translated)', $plurals)); + $this->assertTrue(in_array('3 is 2-4 (translated)', $plurals)); + $this->assertTrue(in_array('4 is 2-4 (translated)', $plurals)); + $this->assertTrue(in_array('5 everything else (translated)', $plurals)); + $this->assertTrue(in_array('6 everything else (translated)', $plurals)); + $this->assertTrue(in_array('7 everything else (translated)', $plurals)); + $this->assertTrue(in_array('8 everything else (translated)', $plurals)); + $this->assertTrue(in_array('9 everything else (translated)', $plurals)); + $this->assertTrue(in_array('10 everything else (translated)', $plurals)); + $this->assertTrue(in_array('11 everything else (translated)', $plurals)); + $this->assertTrue(in_array('12 everything else (translated)', $plurals)); + $this->assertTrue(in_array('13 everything else (translated)', $plurals)); + $this->assertTrue(in_array('14 everything else (translated)', $plurals)); + $this->assertTrue(in_array('15 everything else (translated)', $plurals)); + $this->assertTrue(in_array('16 everything else (translated)', $plurals)); + $this->assertTrue(in_array('17 everything else (translated)', $plurals)); + $this->assertTrue(in_array('18 everything else (translated)', $plurals)); + $this->assertTrue(in_array('19 everything else (translated)', $plurals)); + $this->assertTrue(in_array('20 everything else (translated)', $plurals)); + $this->assertTrue(in_array('21 everything else (translated)', $plurals)); + $this->assertTrue(in_array('22 everything else (translated)', $plurals)); + $this->assertTrue(in_array('23 everything else (translated)', $plurals)); + $this->assertTrue(in_array('24 everything else (translated)', $plurals)); + $this->assertTrue(in_array('25 everything else (translated)', $plurals)); + + $coreSingular = $this->__singularFromCore(); + $this->assertEquals('Plural Rule 8 (from core translated)', $coreSingular); + + $corePlurals = $this->__pluralFromCore(); + $this->assertTrue(in_array('0 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('1 is 1 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('2 is 2-4 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('3 is 2-4 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('4 is 2-4 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('5 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('6 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('7 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('8 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('9 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('10 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('11 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('12 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('13 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('14 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('15 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('16 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('17 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('18 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('19 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('20 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('21 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('22 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('23 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('24 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('25 everything else (from core translated)', $corePlurals)); + } + +/** + * testPoRulesNine method + * + * @return void + */ + public function testPoRulesNine() { + Configure::write('Config.language', 'rule_9_po'); + $this->assertRulesNine(); + } + +/** + * testMoRulesNine method + * + * @return void + */ + public function testMoRulesNine() { + Configure::write('Config.language', 'rule_9_mo'); + $this->assertRulesNine(); + } + +/** + * Assert plural rules nine + * + * @return void + */ + public function assertRulesNine() { + $singular = $this->__singular(); + $this->assertEquals('Plural Rule 9 (translated)', $singular); + + $plurals = $this->__plural(); + $this->assertTrue(in_array('0 everything else (translated)', $plurals)); + $this->assertTrue(in_array('0 everything else (translated)', $plurals)); + $this->assertTrue(in_array('1 is 1 (translated)', $plurals)); + $this->assertTrue(in_array('2 ends in 2-4, not 12-14 (translated)', $plurals)); + $this->assertTrue(in_array('3 ends in 2-4, not 12-14 (translated)', $plurals)); + $this->assertTrue(in_array('4 ends in 2-4, not 12-14 (translated)', $plurals)); + $this->assertTrue(in_array('5 everything else (translated)', $plurals)); + $this->assertTrue(in_array('6 everything else (translated)', $plurals)); + $this->assertTrue(in_array('7 everything else (translated)', $plurals)); + $this->assertTrue(in_array('8 everything else (translated)', $plurals)); + $this->assertTrue(in_array('9 everything else (translated)', $plurals)); + $this->assertTrue(in_array('10 everything else (translated)', $plurals)); + $this->assertTrue(in_array('11 everything else (translated)', $plurals)); + $this->assertTrue(in_array('12 everything else (translated)', $plurals)); + $this->assertTrue(in_array('13 everything else (translated)', $plurals)); + $this->assertTrue(in_array('14 everything else (translated)', $plurals)); + $this->assertTrue(in_array('15 everything else (translated)', $plurals)); + $this->assertTrue(in_array('16 everything else (translated)', $plurals)); + $this->assertTrue(in_array('17 everything else (translated)', $plurals)); + $this->assertTrue(in_array('18 everything else (translated)', $plurals)); + $this->assertTrue(in_array('19 everything else (translated)', $plurals)); + $this->assertTrue(in_array('20 everything else (translated)', $plurals)); + $this->assertTrue(in_array('21 everything else (translated)', $plurals)); + $this->assertTrue(in_array('22 ends in 2-4, not 12-14 (translated)', $plurals)); + $this->assertTrue(in_array('23 ends in 2-4, not 12-14 (translated)', $plurals)); + $this->assertTrue(in_array('24 ends in 2-4, not 12-14 (translated)', $plurals)); + $this->assertTrue(in_array('25 everything else (translated)', $plurals)); + + $coreSingular = $this->__singularFromCore(); + $this->assertEquals('Plural Rule 9 (from core translated)', $coreSingular); + + $corePlurals = $this->__pluralFromCore(); + $this->assertTrue(in_array('0 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('0 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('0 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('1 is 1 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('2 ends in 2-4, not 12-14 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('3 ends in 2-4, not 12-14 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('4 ends in 2-4, not 12-14 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('5 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('6 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('7 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('8 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('9 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('10 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('11 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('12 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('13 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('14 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('15 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('16 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('17 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('18 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('19 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('20 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('21 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('22 ends in 2-4, not 12-14 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('23 ends in 2-4, not 12-14 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('24 ends in 2-4, not 12-14 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('25 everything else (from core translated)', $corePlurals)); + } + +/** + * testPoRulesTen method + * + * @return void + */ + public function testPoRulesTen() { + Configure::write('Config.language', 'rule_10_po'); + $this->assertRulesTen(); + } + +/** + * testMoRulesTen method + * + * @return void + */ + public function testMoRulesTen() { + Configure::write('Config.language', 'rule_10_mo'); + $this->assertRulesTen(); + } + +/** + * Assertions for plural rules 10 + * + * @return void + */ + public function assertRulesTen() { + $singular = $this->__singular(); + $this->assertEquals('Plural Rule 10 (translated)', $singular); + + $plurals = $this->__plural(); + $this->assertTrue(in_array('0 everything else (translated)', $plurals)); + $this->assertTrue(in_array('0 everything else (translated)', $plurals)); + $this->assertTrue(in_array('1 ends in 1 (translated)', $plurals)); + $this->assertTrue(in_array('2 ends in 2 (translated)', $plurals)); + $this->assertTrue(in_array('3 ends in 03-04 (translated)', $plurals)); + $this->assertTrue(in_array('4 ends in 03-04 (translated)', $plurals)); + $this->assertTrue(in_array('5 everything else (translated)', $plurals)); + $this->assertTrue(in_array('6 everything else (translated)', $plurals)); + $this->assertTrue(in_array('7 everything else (translated)', $plurals)); + $this->assertTrue(in_array('8 everything else (translated)', $plurals)); + $this->assertTrue(in_array('9 everything else (translated)', $plurals)); + $this->assertTrue(in_array('10 everything else (translated)', $plurals)); + $this->assertTrue(in_array('11 everything else (translated)', $plurals)); + $this->assertTrue(in_array('12 everything else (translated)', $plurals)); + $this->assertTrue(in_array('13 everything else (translated)', $plurals)); + $this->assertTrue(in_array('14 everything else (translated)', $plurals)); + $this->assertTrue(in_array('15 everything else (translated)', $plurals)); + $this->assertTrue(in_array('16 everything else (translated)', $plurals)); + $this->assertTrue(in_array('17 everything else (translated)', $plurals)); + $this->assertTrue(in_array('18 everything else (translated)', $plurals)); + $this->assertTrue(in_array('19 everything else (translated)', $plurals)); + $this->assertTrue(in_array('20 everything else (translated)', $plurals)); + $this->assertTrue(in_array('21 everything else (translated)', $plurals)); + $this->assertTrue(in_array('22 everything else (translated)', $plurals)); + $this->assertTrue(in_array('23 everything else (translated)', $plurals)); + $this->assertTrue(in_array('24 everything else (translated)', $plurals)); + $this->assertTrue(in_array('25 everything else (translated)', $plurals)); + + $coreSingular = $this->__singularFromCore(); + $this->assertEquals('Plural Rule 10 (from core translated)', $coreSingular); + + $corePlurals = $this->__pluralFromCore(); + $this->assertTrue(in_array('0 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('0 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('1 ends in 1 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('2 ends in 2 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('3 ends in 03-04 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('4 ends in 03-04 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('5 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('6 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('7 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('8 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('9 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('10 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('11 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('12 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('13 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('14 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('15 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('16 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('17 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('18 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('19 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('20 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('21 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('22 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('23 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('24 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('25 everything else (from core translated)', $corePlurals)); + } + +/** + * testPoRulesEleven method + * + * @return void + */ + public function testPoRulesEleven() { + Configure::write('Config.language', 'rule_11_po'); + $this->assertRulesEleven(); + } + +/** + * testMoRulesEleven method + * + * @return void + */ + public function testMoRulesEleven() { + Configure::write('Config.language', 'rule_11_mo'); + $this->assertRulesEleven(); + } + +/** + * Assertions for plural rules eleven + * + * @return void + */ + public function assertRulesEleven() { + $singular = $this->__singular(); + $this->assertEquals('Plural Rule 11 (translated)', $singular); + + $plurals = $this->__plural(); + $this->assertTrue(in_array('0 everything else (translated)', $plurals)); + $this->assertTrue(in_array('1 is 1 (translated)', $plurals)); + $this->assertTrue(in_array('2 is 2 (translated)', $plurals)); + $this->assertTrue(in_array('3 is 3-6 (translated)', $plurals)); + $this->assertTrue(in_array('4 is 3-6 (translated)', $plurals)); + $this->assertTrue(in_array('5 is 3-6 (translated)', $plurals)); + $this->assertTrue(in_array('6 is 3-6 (translated)', $plurals)); + $this->assertTrue(in_array('7 is 7-10 (translated)', $plurals)); + $this->assertTrue(in_array('8 is 7-10 (translated)', $plurals)); + $this->assertTrue(in_array('9 is 7-10 (translated)', $plurals)); + $this->assertTrue(in_array('10 is 7-10 (translated)', $plurals)); + $this->assertTrue(in_array('11 everything else (translated)', $plurals)); + $this->assertTrue(in_array('12 everything else (translated)', $plurals)); + $this->assertTrue(in_array('13 everything else (translated)', $plurals)); + $this->assertTrue(in_array('14 everything else (translated)', $plurals)); + $this->assertTrue(in_array('15 everything else (translated)', $plurals)); + $this->assertTrue(in_array('16 everything else (translated)', $plurals)); + $this->assertTrue(in_array('17 everything else (translated)', $plurals)); + $this->assertTrue(in_array('18 everything else (translated)', $plurals)); + $this->assertTrue(in_array('19 everything else (translated)', $plurals)); + $this->assertTrue(in_array('20 everything else (translated)', $plurals)); + $this->assertTrue(in_array('21 everything else (translated)', $plurals)); + $this->assertTrue(in_array('22 everything else (translated)', $plurals)); + $this->assertTrue(in_array('23 everything else (translated)', $plurals)); + $this->assertTrue(in_array('24 everything else (translated)', $plurals)); + $this->assertTrue(in_array('25 everything else (translated)', $plurals)); + + $coreSingular = $this->__singularFromCore(); + $this->assertEquals('Plural Rule 11 (from core translated)', $coreSingular); + + $corePlurals = $this->__pluralFromCore(); + $this->assertTrue(in_array('0 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('1 is 1 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('2 is 2 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('3 is 3-6 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('4 is 3-6 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('5 is 3-6 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('6 is 3-6 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('7 is 7-10 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('8 is 7-10 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('9 is 7-10 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('10 is 7-10 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('11 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('12 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('13 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('14 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('15 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('16 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('17 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('18 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('19 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('20 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('21 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('22 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('23 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('24 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('25 everything else (from core translated)', $corePlurals)); + } + +/** + * testPoRulesTwelve method + * + * @return void + */ + public function testPoRulesTwelve() { + Configure::write('Config.language', 'rule_12_po'); + $this->assertRulesTwelve(); + } + +/** + * testMoRulesTwelve method + * + * @return void + */ + public function testMoRulesTwelve() { + Configure::write('Config.language', 'rule_12_mo'); + $this->assertRulesTwelve(); + } + +/** + * Assertions for plural rules twelve + * + * @return void + */ + public function assertRulesTwelve() { + $singular = $this->__singular(); + $this->assertEquals('Plural Rule 12 (translated)', $singular); + + $plurals = $this->__plural(); + $this->assertTrue(in_array('0 is 0 or 3-10 (translated)', $plurals)); + $this->assertTrue(in_array('1 is 1 (translated)', $plurals)); + $this->assertTrue(in_array('2 is 2 (translated)', $plurals)); + $this->assertTrue(in_array('3 is 0 or 3-10 (translated)', $plurals)); + $this->assertTrue(in_array('4 is 0 or 3-10 (translated)', $plurals)); + $this->assertTrue(in_array('5 is 0 or 3-10 (translated)', $plurals)); + $this->assertTrue(in_array('6 is 0 or 3-10 (translated)', $plurals)); + $this->assertTrue(in_array('7 is 0 or 3-10 (translated)', $plurals)); + $this->assertTrue(in_array('8 is 0 or 3-10 (translated)', $plurals)); + $this->assertTrue(in_array('9 is 0 or 3-10 (translated)', $plurals)); + $this->assertTrue(in_array('10 is 0 or 3-10 (translated)', $plurals)); + $this->assertTrue(in_array('11 everything else (translated)', $plurals)); + $this->assertTrue(in_array('12 everything else (translated)', $plurals)); + $this->assertTrue(in_array('13 everything else (translated)', $plurals)); + $this->assertTrue(in_array('14 everything else (translated)', $plurals)); + $this->assertTrue(in_array('15 everything else (translated)', $plurals)); + $this->assertTrue(in_array('16 everything else (translated)', $plurals)); + $this->assertTrue(in_array('17 everything else (translated)', $plurals)); + $this->assertTrue(in_array('18 everything else (translated)', $plurals)); + $this->assertTrue(in_array('19 everything else (translated)', $plurals)); + $this->assertTrue(in_array('20 everything else (translated)', $plurals)); + $this->assertTrue(in_array('21 everything else (translated)', $plurals)); + $this->assertTrue(in_array('22 everything else (translated)', $plurals)); + $this->assertTrue(in_array('23 everything else (translated)', $plurals)); + $this->assertTrue(in_array('24 everything else (translated)', $plurals)); + $this->assertTrue(in_array('25 everything else (translated)', $plurals)); + + $coreSingular = $this->__singularFromCore(); + $this->assertEquals('Plural Rule 12 (from core translated)', $coreSingular); + + $corePlurals = $this->__pluralFromCore(); + $this->assertTrue(in_array('0 is 0 or 3-10 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('1 is 1 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('2 is 2 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('3 is 0 or 3-10 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('4 is 0 or 3-10 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('5 is 0 or 3-10 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('6 is 0 or 3-10 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('7 is 0 or 3-10 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('8 is 0 or 3-10 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('9 is 0 or 3-10 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('10 is 0 or 3-10 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('11 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('12 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('13 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('14 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('15 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('16 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('17 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('18 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('19 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('20 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('21 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('22 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('23 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('24 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('25 everything else (from core translated)', $corePlurals)); + } + +/** + * testMoRulesThirteen method + * + * @return void + */ + public function testmoRulesThirteen() { + Configure::write('Config.language', 'rule_13_mo'); + $this->assertRulesThirteen(); + } + +/** + * testPoRulesThirteen method + * + * @return void + */ + public function testPoRulesThirteen() { + Configure::write('Config.language', 'rule_13_po'); + $this->assertRulesThirteen(); + } + +/** + * Assertions for plural rules thirteen + * + * @return void + */ + public function assertRulesThirteen() { + $singular = $this->__singular(); + $this->assertEquals('Plural Rule 13 (translated)', $singular); + + $plurals = $this->__plural(); + $this->assertTrue(in_array('0 is 0 or ends in 01-10 (translated)', $plurals)); + $this->assertTrue(in_array('1 is 1 (translated)', $plurals)); + $this->assertTrue(in_array('2 is 0 or ends in 01-10 (translated)', $plurals)); + $this->assertTrue(in_array('3 is 0 or ends in 01-10 (translated)', $plurals)); + $this->assertTrue(in_array('4 is 0 or ends in 01-10 (translated)', $plurals)); + $this->assertTrue(in_array('5 is 0 or ends in 01-10 (translated)', $plurals)); + $this->assertTrue(in_array('6 is 0 or ends in 01-10 (translated)', $plurals)); + $this->assertTrue(in_array('7 is 0 or ends in 01-10 (translated)', $plurals)); + $this->assertTrue(in_array('8 is 0 or ends in 01-10 (translated)', $plurals)); + $this->assertTrue(in_array('9 is 0 or ends in 01-10 (translated)', $plurals)); + $this->assertTrue(in_array('10 is 0 or ends in 01-10 (translated)', $plurals)); + $this->assertTrue(in_array('11 ends in 11-20 (translated)', $plurals)); + $this->assertTrue(in_array('12 ends in 11-20 (translated)', $plurals)); + $this->assertTrue(in_array('13 ends in 11-20 (translated)', $plurals)); + $this->assertTrue(in_array('14 ends in 11-20 (translated)', $plurals)); + $this->assertTrue(in_array('15 ends in 11-20 (translated)', $plurals)); + $this->assertTrue(in_array('16 ends in 11-20 (translated)', $plurals)); + $this->assertTrue(in_array('17 ends in 11-20 (translated)', $plurals)); + $this->assertTrue(in_array('18 ends in 11-20 (translated)', $plurals)); + $this->assertTrue(in_array('19 ends in 11-20 (translated)', $plurals)); + $this->assertTrue(in_array('20 ends in 11-20 (translated)', $plurals)); + $this->assertTrue(in_array('21 everything else (translated)', $plurals)); + $this->assertTrue(in_array('22 everything else (translated)', $plurals)); + $this->assertTrue(in_array('23 everything else (translated)', $plurals)); + $this->assertTrue(in_array('24 everything else (translated)', $plurals)); + $this->assertTrue(in_array('25 everything else (translated)', $plurals)); + + $coreSingular = $this->__singularFromCore(); + $this->assertEquals('Plural Rule 13 (from core translated)', $coreSingular); + + $corePlurals = $this->__pluralFromCore(); + $this->assertTrue(in_array('0 is 0 or ends in 01-10 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('1 is 1 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('2 is 0 or ends in 01-10 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('3 is 0 or ends in 01-10 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('4 is 0 or ends in 01-10 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('5 is 0 or ends in 01-10 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('6 is 0 or ends in 01-10 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('7 is 0 or ends in 01-10 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('8 is 0 or ends in 01-10 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('9 is 0 or ends in 01-10 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('10 is 0 or ends in 01-10 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('11 ends in 11-20 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('12 ends in 11-20 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('13 ends in 11-20 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('14 ends in 11-20 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('15 ends in 11-20 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('16 ends in 11-20 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('17 ends in 11-20 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('18 ends in 11-20 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('19 ends in 11-20 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('20 ends in 11-20 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('21 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('22 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('23 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('24 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('25 everything else (from core translated)', $corePlurals)); + } + +/** + * testMoRulesFourteen method + * + * @return void + */ + public function testMoRulesFourteen() { + Configure::write('Config.language', 'rule_14_mo'); + $this->assertRulesFourteen(); + } + +/** + * testPoRulesFourteen method + * + * @return void + */ + public function testPoRulesFourteen() { + Configure::write('Config.language', 'rule_14_po'); + $this->assertRulesFourteen(); + } + +/** + * Assertions for plural rules fourteen + * + * @return void + */ + public function assertRulesFourteen() { + $singular = $this->__singular(); + $this->assertEquals('Plural Rule 14 (translated)', $singular); + + $plurals = $this->__plural(); + $this->assertTrue(in_array('0 everything else (translated)', $plurals)); + $this->assertTrue(in_array('1 ends in 1 (translated)', $plurals)); + $this->assertTrue(in_array('2 ends in 2 (translated)', $plurals)); + $this->assertTrue(in_array('3 everything else (translated)', $plurals)); + $this->assertTrue(in_array('4 everything else (translated)', $plurals)); + $this->assertTrue(in_array('5 everything else (translated)', $plurals)); + $this->assertTrue(in_array('6 everything else (translated)', $plurals)); + $this->assertTrue(in_array('7 everything else (translated)', $plurals)); + $this->assertTrue(in_array('8 everything else (translated)', $plurals)); + $this->assertTrue(in_array('9 everything else (translated)', $plurals)); + $this->assertTrue(in_array('10 everything else (translated)', $plurals)); + $this->assertTrue(in_array('11 ends in 1 (translated)', $plurals)); + $this->assertTrue(in_array('12 ends in 2 (translated)', $plurals)); + $this->assertTrue(in_array('13 everything else (translated)', $plurals)); + $this->assertTrue(in_array('14 everything else (translated)', $plurals)); + $this->assertTrue(in_array('15 everything else (translated)', $plurals)); + $this->assertTrue(in_array('16 everything else (translated)', $plurals)); + $this->assertTrue(in_array('17 everything else (translated)', $plurals)); + $this->assertTrue(in_array('18 everything else (translated)', $plurals)); + $this->assertTrue(in_array('19 everything else (translated)', $plurals)); + $this->assertTrue(in_array('20 everything else (translated)', $plurals)); + $this->assertTrue(in_array('21 ends in 1 (translated)', $plurals)); + $this->assertTrue(in_array('22 ends in 2 (translated)', $plurals)); + $this->assertTrue(in_array('23 everything else (translated)', $plurals)); + $this->assertTrue(in_array('24 everything else (translated)', $plurals)); + $this->assertTrue(in_array('25 everything else (translated)', $plurals)); + + $coreSingular = $this->__singularFromCore(); + $this->assertEquals('Plural Rule 14 (from core translated)', $coreSingular); + + $corePlurals = $this->__pluralFromCore(); + $this->assertTrue(in_array('0 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('1 ends in 1 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('2 ends in 2 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('3 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('4 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('5 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('6 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('7 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('8 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('9 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('10 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('11 ends in 1 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('12 ends in 2 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('13 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('14 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('15 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('16 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('17 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('18 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('19 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('20 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('21 ends in 1 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('22 ends in 2 (from core translated)', $corePlurals)); + $this->assertTrue(in_array('23 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('24 everything else (from core translated)', $corePlurals)); + $this->assertTrue(in_array('25 everything else (from core translated)', $corePlurals)); + } + +/** + * testSetLanguageWithSession method + * + * @return void + */ + public function testSetLanguageWithSession() { + $_SESSION['Config']['language'] = 'po'; + $singular = $this->__singular(); + $this->assertEquals('Po (translated)', $singular); + + $plurals = $this->__plural(); + $this->assertTrue(in_array('0 everything else (po translated)', $plurals)); + $this->assertTrue(in_array('1 is 1 (po translated)', $plurals)); + $this->assertTrue(in_array('2 is 2-4 (po translated)', $plurals)); + $this->assertTrue(in_array('3 is 2-4 (po translated)', $plurals)); + $this->assertTrue(in_array('4 is 2-4 (po translated)', $plurals)); + $this->assertTrue(in_array('5 everything else (po translated)', $plurals)); + $this->assertTrue(in_array('6 everything else (po translated)', $plurals)); + $this->assertTrue(in_array('7 everything else (po translated)', $plurals)); + $this->assertTrue(in_array('8 everything else (po translated)', $plurals)); + $this->assertTrue(in_array('9 everything else (po translated)', $plurals)); + $this->assertTrue(in_array('10 everything else (po translated)', $plurals)); + $this->assertTrue(in_array('11 everything else (po translated)', $plurals)); + $this->assertTrue(in_array('12 everything else (po translated)', $plurals)); + $this->assertTrue(in_array('13 everything else (po translated)', $plurals)); + $this->assertTrue(in_array('14 everything else (po translated)', $plurals)); + $this->assertTrue(in_array('15 everything else (po translated)', $plurals)); + $this->assertTrue(in_array('16 everything else (po translated)', $plurals)); + $this->assertTrue(in_array('17 everything else (po translated)', $plurals)); + $this->assertTrue(in_array('18 everything else (po translated)', $plurals)); + $this->assertTrue(in_array('19 everything else (po translated)', $plurals)); + $this->assertTrue(in_array('20 everything else (po translated)', $plurals)); + $this->assertTrue(in_array('21 everything else (po translated)', $plurals)); + $this->assertTrue(in_array('22 everything else (po translated)', $plurals)); + $this->assertTrue(in_array('23 everything else (po translated)', $plurals)); + $this->assertTrue(in_array('24 everything else (po translated)', $plurals)); + $this->assertTrue(in_array('25 everything else (po translated)', $plurals)); + unset($_SESSION['Config']['language']); + } + +/** + * testNoCoreTranslation method + * + * @return void + */ + public function testNoCoreTranslation() { + Configure::write('Config.language', 'po'); + $singular = $this->__singular(); + $this->assertEquals('Po (translated)', $singular); + + $coreSingular = $this->__singularFromCore(); + $this->assertNotEquals('Po (from core translated)', $coreSingular); + + $corePlurals = $this->__pluralFromCore(); + $this->assertFalse(in_array('0 everything else (from core translated)', $corePlurals)); + $this->assertFalse(in_array('1 is 1 (from core translated)', $corePlurals)); + $this->assertFalse(in_array('2 is 2-4 (from core translated)', $corePlurals)); + $this->assertFalse(in_array('3 is 2-4 (from core translated)', $corePlurals)); + $this->assertFalse(in_array('4 is 2-4 (from core translated)', $corePlurals)); + $this->assertFalse(in_array('5 everything else (from core translated)', $corePlurals)); + $this->assertFalse(in_array('6 everything else (from core translated)', $corePlurals)); + $this->assertFalse(in_array('7 everything else (from core translated)', $corePlurals)); + $this->assertFalse(in_array('8 everything else (from core translated)', $corePlurals)); + $this->assertFalse(in_array('9 everything else (from core translated)', $corePlurals)); + $this->assertFalse(in_array('10 everything else (from core translated)', $corePlurals)); + $this->assertFalse(in_array('11 everything else (from core translated)', $corePlurals)); + $this->assertFalse(in_array('12 everything else (from core translated)', $corePlurals)); + $this->assertFalse(in_array('13 everything else (from core translated)', $corePlurals)); + $this->assertFalse(in_array('14 everything else (from core translated)', $corePlurals)); + $this->assertFalse(in_array('15 everything else (from core translated)', $corePlurals)); + $this->assertFalse(in_array('16 everything else (from core translated)', $corePlurals)); + $this->assertFalse(in_array('17 everything else (from core translated)', $corePlurals)); + $this->assertFalse(in_array('18 everything else (from core translated)', $corePlurals)); + $this->assertFalse(in_array('19 everything else (from core translated)', $corePlurals)); + $this->assertFalse(in_array('20 everything else (from core translated)', $corePlurals)); + $this->assertFalse(in_array('21 everything else (from core translated)', $corePlurals)); + $this->assertFalse(in_array('22 everything else (from core translated)', $corePlurals)); + $this->assertFalse(in_array('23 everything else (from core translated)', $corePlurals)); + $this->assertFalse(in_array('24 everything else (from core translated)', $corePlurals)); + $this->assertFalse(in_array('25 everything else (from core translated)', $corePlurals)); + } + +/** + * testPluginTranslation method + * + * @return void + */ + public function testPluginTranslation() { + App::build(array( + 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS) + )); + + Configure::write('Config.language', 'po'); + $singular = $this->__domainSingular(); + $this->assertEquals('Plural Rule 1 (from plugin)', $singular); + + $plurals = $this->__domainPlural(); + $this->assertTrue(in_array('0 = 0 or > 1 (from plugin)', $plurals)); + $this->assertTrue(in_array('1 = 1 (from plugin)', $plurals)); + $this->assertTrue(in_array('2 = 0 or > 1 (from plugin)', $plurals)); + $this->assertTrue(in_array('3 = 0 or > 1 (from plugin)', $plurals)); + $this->assertTrue(in_array('4 = 0 or > 1 (from plugin)', $plurals)); + $this->assertTrue(in_array('5 = 0 or > 1 (from plugin)', $plurals)); + $this->assertTrue(in_array('6 = 0 or > 1 (from plugin)', $plurals)); + $this->assertTrue(in_array('7 = 0 or > 1 (from plugin)', $plurals)); + $this->assertTrue(in_array('8 = 0 or > 1 (from plugin)', $plurals)); + $this->assertTrue(in_array('9 = 0 or > 1 (from plugin)', $plurals)); + $this->assertTrue(in_array('10 = 0 or > 1 (from plugin)', $plurals)); + $this->assertTrue(in_array('11 = 0 or > 1 (from plugin)', $plurals)); + $this->assertTrue(in_array('12 = 0 or > 1 (from plugin)', $plurals)); + $this->assertTrue(in_array('13 = 0 or > 1 (from plugin)', $plurals)); + $this->assertTrue(in_array('14 = 0 or > 1 (from plugin)', $plurals)); + $this->assertTrue(in_array('15 = 0 or > 1 (from plugin)', $plurals)); + $this->assertTrue(in_array('16 = 0 or > 1 (from plugin)', $plurals)); + $this->assertTrue(in_array('17 = 0 or > 1 (from plugin)', $plurals)); + $this->assertTrue(in_array('18 = 0 or > 1 (from plugin)', $plurals)); + $this->assertTrue(in_array('19 = 0 or > 1 (from plugin)', $plurals)); + $this->assertTrue(in_array('20 = 0 or > 1 (from plugin)', $plurals)); + $this->assertTrue(in_array('21 = 0 or > 1 (from plugin)', $plurals)); + $this->assertTrue(in_array('22 = 0 or > 1 (from plugin)', $plurals)); + $this->assertTrue(in_array('23 = 0 or > 1 (from plugin)', $plurals)); + $this->assertTrue(in_array('24 = 0 or > 1 (from plugin)', $plurals)); + $this->assertTrue(in_array('25 = 0 or > 1 (from plugin)', $plurals)); + } + +/** + * testPoMultipleLineTranslation method + * + * @return void + */ + public function testPoMultipleLineTranslation() { + Configure::write('Config.language', 'po'); + + $string = "This is a multiline translation\n"; + $string .= "broken up over multiple lines.\n"; + $string .= "This is the third line.\n"; + $string .= "This is the forth line."; + $result = __($string); + + $expected = "This is a multiline translation\n"; + $expected .= "broken up over multiple lines.\n"; + $expected .= "This is the third line.\n"; + $expected .= "This is the forth line. (translated)"; + $this->assertEquals($expected, $result); + + // Windows Newline is \r\n + $string = "This is a multiline translation\r\n"; + $string .= "broken up over multiple lines.\r\n"; + $string .= "This is the third line.\r\n"; + $string .= "This is the forth line."; + $result = __($string); + $this->assertEquals($expected, $result); + + $singular = "valid\nsecond line"; + $plural = "valids\nsecond line"; + + $result = __n($singular, $plural, 1); + $expected = "v\nsecond line"; + $this->assertEquals($expected, $result); + + $result = __n($singular, $plural, 2); + $expected = "vs\nsecond line"; + $this->assertEquals($expected, $result); + + $string = "This is a multiline translation\n"; + $string .= "broken up over multiple lines.\n"; + $string .= "This is the third line.\n"; + $string .= "This is the forth line."; + + $singular = "%d = 1\n" . $string; + $plural = "%d = 0 or > 1\n" . $string; + + $result = __n($singular, $plural, 1); + $expected = "%d is 1\n" . $string; + $this->assertEquals($expected, $result); + + $result = __n($singular, $plural, 2); + $expected = "%d is 2-4\n" . $string; + $this->assertEquals($expected, $result); + + // Windows Newline is \r\n + $string = "This is a multiline translation\r\n"; + $string .= "broken up over multiple lines.\r\n"; + $string .= "This is the third line.\r\n"; + $string .= "This is the forth line."; + + $singular = "%d = 1\r\n" . $string; + $plural = "%d = 0 or > 1\r\n" . $string; + + $result = __n($singular, $plural, 1); + $expected = "%d is 1\n" . str_replace("\r\n", "\n", $string); + $this->assertEquals($expected, $result); + + $result = __n($singular, $plural, 2); + $expected = "%d is 2-4\n" . str_replace("\r\n", "\n", $string); + $this->assertEquals($expected, $result); + } + +/** + * testPoNoTranslationNeeded method + * + * @return void + */ + public function testPoNoTranslationNeeded() { + Configure::write('Config.language', 'po'); + $result = __('No Translation needed'); + $this->assertEquals('No Translation needed', $result); + } + +/** + * testPoQuotedString method + * + * @return void + */ + public function testPoQuotedString() { + Configure::write('Config.language', 'po'); + $expected = 'this is a "quoted string" (translated)'; + $this->assertEquals($expected, __('this is a "quoted string"')); + } + +/** + * testFloatValue method + * + * @return void + */ + public function testFloatValue() { + Configure::write('Config.language', 'rule_9_po'); + + $result = __n('%d = 1', '%d = 0 or > 1', (float)1); + $expected = '%d is 1 (translated)'; + $this->assertEquals($expected, $result); + + $result = __n('%d = 1', '%d = 0 or > 1', (float)2); + $expected = "%d ends in 2-4, not 12-14 (translated)"; + $this->assertEquals($expected, $result); + + $result = __n('%d = 1', '%d = 0 or > 1', (float)5); + $expected = "%d everything else (translated)"; + $this->assertEquals($expected, $result); + } + +/** + * testCategory method + * + * @return void + */ + public function testCategory() { + Configure::write('Config.language', 'po'); + $category = $this->__category(); + $this->assertEquals('Monetary Po (translated)', $category); + } + +/** + * testPluginCategory method + * + * @return void + */ + public function testPluginCategory() { + Configure::write('Config.language', 'po'); + + $singular = $this->__domainCategorySingular(); + $this->assertEquals('Monetary Plural Rule 1 (from plugin)', $singular); + + $plurals = $this->__domainCategoryPlural(); + $this->assertTrue(in_array('Monetary 0 = 0 or > 1 (from plugin)', $plurals)); + $this->assertTrue(in_array('Monetary 1 = 1 (from plugin)', $plurals)); + } + +/** + * testCategoryThenSingular method + * + * @return void + */ + public function testCategoryThenSingular() { + Configure::write('Config.language', 'po'); + $category = $this->__category(); + $this->assertEquals('Monetary Po (translated)', $category); + + $singular = $this->__singular(); + $this->assertEquals('Po (translated)', $singular); + } + +/** + * testTimeDefinition method + * + * @return void + */ + public function testTimeDefinition() { + Configure::write('Config.language', 'po'); + $result = __c('d_fmt', 5); + $expected = '%m/%d/%Y'; + $this->assertEquals($expected, $result); + + $result = __c('am_pm', 5); + $expected = array('AM', 'PM'); + $this->assertEquals($expected, $result); + + $result = __c('abmon', 5); + $expected = array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'); + $this->assertEquals($expected, $result); + } + +/** + * testTimeDefinitionJapanese method + * + * @return void + */ + public function testTimeDefinitionJapanese() { + Configure::write('Config.language', 'ja_jp'); + $result = __c('d_fmt', 5); + + $expected = "%Y年%m月%d日"; + + $this->assertEquals($expected, $result); + + $result = __c('am_pm', 5); + $expected = array("午前", "午後"); + $this->assertEquals($expected, $result); + + $result = __c('abmon', 5); + $expected = array(" 1月", " 2月", " 3月", " 4月", " 5月", " 6月", " 7月", " 8月", " 9月", "10月", "11月", "12月"); + $this->assertEquals($expected, $result); + } + +/** + * testTranslateLanguageParam method + * + * @return void + */ + public function testTranslateLanguageParam() { + Configure::write('Config.language', 'rule_0_po'); + + $result = I18n::translate('Plural Rule 1', null, null, 6); + $expected = 'Plural Rule 0 (translated)'; + $this->assertEquals($expected, $result); + + $result = I18n::translate('Plural Rule 1', null, null, 6, null, 'rule_1_po'); + $expected = 'Plural Rule 1 (translated)'; + $this->assertEquals($expected, $result); + } + +/** + * Singular method + * + * @return void + */ + private function __domainCategorySingular($domain = 'test_plugin', $category = 3) { + $singular = __dc($domain, 'Plural Rule 1', $category); + return $singular; + } + +/** + * Plural method + * + * @return void + */ + private function __domainCategoryPlural($domain = 'test_plugin', $category = 3) { + $plurals = array(); + for ($number = 0; $number <= 25; $number++) { + $plurals[] = sprintf(__dcn($domain, '%d = 1', '%d = 0 or > 1', (float)$number, $category), (float)$number); + } + return $plurals; + } + +/** + * Singular method + * + * @return void + */ + private function __domainSingular($domain = 'test_plugin') { + $singular = __d($domain, 'Plural Rule 1'); + return $singular; + } + +/** + * Plural method + * + * @return void + */ + private function __domainPlural($domain = 'test_plugin') { + $plurals = array(); + for ($number = 0; $number <= 25; $number++) { + $plurals[] = sprintf(__dn($domain, '%d = 1', '%d = 0 or > 1', (float)$number), (float)$number ); + } + return $plurals; + } + +/** + * category method + * + * @return void + */ + private function __category($category = 3) { + $singular = __c('Plural Rule 1', $category); + return $singular; + } + +/** + * Singular method + * + * @return void + */ + private function __singular() { + $singular = __('Plural Rule 1'); + return $singular; + } + +/** + * Plural method + * + * @return void + */ + private function __plural() { + $plurals = array(); + for ($number = 0; $number <= 25; $number++) { + $plurals[] = sprintf(__n('%d = 1', '%d = 0 or > 1', (float)$number), (float)$number); + } + return $plurals; + } + +/** + * singularFromCore method + * + * @return void + */ + private function __singularFromCore() { + $singular = __('Plural Rule 1 (from core)'); + return $singular; + } + +/** + * pluralFromCore method + * + * @return void + */ + private function __pluralFromCore() { + $plurals = array(); + for ($number = 0; $number <= 25; $number++) { + $plurals[] = sprintf(__n('%d = 1 (from core)', '%d = 0 or > 1 (from core)', (float)$number), (float)$number ); + } + return $plurals; + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/I18n/L10nTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/I18n/L10nTest.php new file mode 100644 index 0000000..d52c3a6 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/I18n/L10nTest.php @@ -0,0 +1,955 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.I18n + * @since CakePHP(tm) v 1.2.0.5432 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ +App::uses('L10n', 'I18n'); + +/** + * L10nTest class + * + * @package Cake.Test.Case.I18n + */ +class L10nTest extends CakeTestCase { + +/** + * testGet method + * + * @return void + */ + public function testGet() { + $localize = new L10n(); + + // Catalog Entry + $lang = $localize->get('en'); + + $this->assertEquals('en', $lang); + $this->assertEquals('English', $localize->language); + $this->assertEquals(array('eng', 'eng'), $localize->languagePath); + $this->assertEquals('eng', $localize->locale); + + // Map Entry + $localize->get('eng'); + + $this->assertEquals('English', $localize->language); + $this->assertEquals(array('eng', 'eng'), $localize->languagePath); + $this->assertEquals('eng', $localize->locale); + + // Catalog Entry + $localize->get('en-ca'); + + $this->assertEquals('English (Canadian)', $localize->language); + $this->assertEquals(array('en_ca', 'eng'), $localize->languagePath); + $this->assertEquals('en_ca', $localize->locale); + + // Default Entry + define('DEFAULT_LANGUAGE', 'en-us'); + + $lang = $localize->get('use_default'); + + $this->assertEquals('en-us', $lang); + $this->assertEquals('English (United States)', $localize->language); + $this->assertEquals(array('en_us', 'eng'), $localize->languagePath); + $this->assertEquals('en_us', $localize->locale); + + $localize->get('es'); + $localize->get(''); + $this->assertEquals('en-us', $localize->lang); + + // Using $this->default + $localize = new L10n(); + + $localize->get('use_default'); + $this->assertEquals('English (United States)', $localize->language); + $this->assertEquals(array('en_us', 'eng', 'eng'), $localize->languagePath); + $this->assertEquals('en_us', $localize->locale); + } + +/** + * testGetAutoLanguage method + * + * @return void + */ + public function testGetAutoLanguage() { + $serverBackup = $_SERVER; + $_SERVER['HTTP_ACCEPT_LANGUAGE'] = 'inexistent,en-ca'; + + $localize = new L10n(); + $lang = $localize->get(); + + $this->assertEquals('en-ca', $lang); + $this->assertEquals('English (Canadian)', $localize->language); + $this->assertEquals(array('en_ca', 'eng', 'eng'), $localize->languagePath); + $this->assertEquals('en_ca', $localize->locale); + + $_SERVER['HTTP_ACCEPT_LANGUAGE'] = 'es_mx'; + $lang = $localize->get(); + + $this->assertEquals('es-mx', $lang); + $this->assertEquals('Spanish (Mexican)', $localize->language); + $this->assertEquals(array('es_mx', 'spa', 'eng'), $localize->languagePath); + $this->assertEquals('es_mx', $localize->locale); + + $_SERVER['HTTP_ACCEPT_LANGUAGE'] = 'en_xy,en_ca'; + $localize->get(); + + $this->assertEquals('English', $localize->language); + $this->assertEquals(array('eng', 'eng', 'eng'), $localize->languagePath); + $this->assertEquals('eng', $localize->locale); + + $_SERVER = $serverBackup; + } + +/** + * testMap method + * + * @return void + */ + public function testMap() { + $localize = new L10n(); + + $result = $localize->map(array('afr', 'af')); + $expected = array('afr' => 'af', 'af' => 'afr'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('alb', 'sq')); + $expected = array('alb' => 'sq', 'sq' => 'alb'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('ara', 'ar')); + $expected = array('ara' => 'ar', 'ar' => 'ara'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('hye', 'hy')); + $expected = array('hye' => 'hy', 'hy' => 'hye'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('baq', 'eu')); + $expected = array('baq' => 'eu', 'eu' => 'baq'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('baq', 'eu')); + $expected = array('baq' => 'eu', 'eu' => 'baq'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('bos', 'bs')); + $expected = array('bos' => 'bs', 'bs' => 'bos'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('bul', 'bg')); + $expected = array('bul' => 'bg', 'bg' => 'bul'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('bel', 'be')); + $expected = array('bel' => 'be', 'be' => 'bel'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('cat', 'ca')); + $expected = array('cat' => 'ca', 'ca' => 'cat'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('chi', 'zh')); + $expected = array('chi' => 'zh', 'zh' => 'chi'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('zho', 'zh')); + $expected = array('zho' => 'zh', 'zh' => 'chi'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('hrv', 'hr')); + $expected = array('hrv' => 'hr', 'hr' => 'hrv'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('ces', 'cs')); + $expected = array('ces' => 'cs', 'cs' => 'cze'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('cze', 'cs')); + $expected = array('cze' => 'cs', 'cs' => 'cze'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('dan', 'da')); + $expected = array('dan' => 'da', 'da' => 'dan'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('dut', 'nl')); + $expected = array('dut' => 'nl', 'nl' => 'dut'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('nld', 'nl')); + $expected = array('nld' => 'nl', 'nl' => 'dut'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('nld')); + $expected = array('nld' => 'nl'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('eng', 'en')); + $expected = array('eng' => 'en', 'en' => 'eng'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('est', 'et')); + $expected = array('est' => 'et', 'et' => 'est'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('fao', 'fo')); + $expected = array('fao' => 'fo', 'fo' => 'fao'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('fas', 'fa')); + $expected = array('fas' => 'fa', 'fa' => 'fas'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('per', 'fa')); + $expected = array('per' => 'fa', 'fa' => 'fas'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('fin', 'fi')); + $expected = array('fin' => 'fi', 'fi' => 'fin'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('fra', 'fr')); + $expected = array('fra' => 'fr', 'fr' => 'fre'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('fre', 'fr')); + $expected = array('fre' => 'fr', 'fr' => 'fre'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('gla', 'gd')); + $expected = array('gla' => 'gd', 'gd' => 'gla'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('glg', 'gl')); + $expected = array('glg' => 'gl', 'gl' => 'glg'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('deu', 'de')); + $expected = array('deu' => 'de', 'de' => 'deu'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('ger', 'de')); + $expected = array('ger' => 'de', 'de' => 'deu'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('ell', 'el')); + $expected = array('ell' => 'el', 'el' => 'gre'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('gre', 'el')); + $expected = array('gre' => 'el', 'el' => 'gre'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('heb', 'he')); + $expected = array('heb' => 'he', 'he' => 'heb'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('hin', 'hi')); + $expected = array('hin' => 'hi', 'hi' => 'hin'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('hun', 'hu')); + $expected = array('hun' => 'hu', 'hu' => 'hun'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('ice', 'is')); + $expected = array('ice' => 'is', 'is' => 'ice'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('isl', 'is')); + $expected = array('isl' => 'is', 'is' => 'ice'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('ind', 'id')); + $expected = array('ind' => 'id', 'id' => 'ind'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('gle', 'ga')); + $expected = array('gle' => 'ga', 'ga' => 'gle'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('ita', 'it')); + $expected = array('ita' => 'it', 'it' => 'ita'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('jpn', 'ja')); + $expected = array('jpn' => 'ja', 'ja' => 'jpn'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('kor', 'ko')); + $expected = array('kor' => 'ko', 'ko' => 'kor'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('lav', 'lv')); + $expected = array('lav' => 'lv', 'lv' => 'lav'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('lit', 'lt')); + $expected = array('lit' => 'lt', 'lt' => 'lit'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('mac', 'mk')); + $expected = array('mac' => 'mk', 'mk' => 'mac'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('mkd', 'mk')); + $expected = array('mkd' => 'mk', 'mk' => 'mac'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('may', 'ms')); + $expected = array('may' => 'ms', 'ms' => 'may'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('msa', 'ms')); + $expected = array('msa' => 'ms', 'ms' => 'may'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('mlt', 'mt')); + $expected = array('mlt' => 'mt', 'mt' => 'mlt'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('nor', 'no')); + $expected = array('nor' => 'no', 'no' => 'nor'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('nob', 'nb')); + $expected = array('nob' => 'nb', 'nb' => 'nob'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('nno', 'nn')); + $expected = array('nno' => 'nn', 'nn' => 'nno'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('pol', 'pl')); + $expected = array('pol' => 'pl', 'pl' => 'pol'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('por', 'pt')); + $expected = array('por' => 'pt', 'pt' => 'por'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('roh', 'rm')); + $expected = array('roh' => 'rm', 'rm' => 'roh'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('ron', 'ro')); + $expected = array('ron' => 'ro', 'ro' => 'rum'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('rum', 'ro')); + $expected = array('rum' => 'ro', 'ro' => 'rum'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('rus', 'ru')); + $expected = array('rus' => 'ru', 'ru' => 'rus'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('smi', 'sz')); + $expected = array('smi' => 'sz', 'sz' => 'smi'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('scc', 'sr')); + $expected = array('scc' => 'sr', 'sr' => 'scc'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('srp', 'sr')); + $expected = array('srp' => 'sr', 'sr' => 'scc'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('slk', 'sk')); + $expected = array('slk' => 'sk', 'sk' => 'slo'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('slo', 'sk')); + $expected = array('slo' => 'sk', 'sk' => 'slo'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('slv', 'sl')); + $expected = array('slv' => 'sl', 'sl' => 'slv'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('wen', 'sb')); + $expected = array('wen' => 'sb', 'sb' => 'wen'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('spa', 'es')); + $expected = array('spa' => 'es', 'es' => 'spa'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('swe', 'sv')); + $expected = array('swe' => 'sv', 'sv' => 'swe'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('tha', 'th')); + $expected = array('tha' => 'th', 'th' => 'tha'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('tso', 'ts')); + $expected = array('tso' => 'ts', 'ts' => 'tso'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('tsn', 'tn')); + $expected = array('tsn' => 'tn', 'tn' => 'tsn'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('tur', 'tr')); + $expected = array('tur' => 'tr', 'tr' => 'tur'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('ukr', 'uk')); + $expected = array('ukr' => 'uk', 'uk' => 'ukr'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('urd', 'ur')); + $expected = array('urd' => 'ur', 'ur' => 'urd'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('ven', 've')); + $expected = array('ven' => 've', 've' => 'ven'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('vie', 'vi')); + $expected = array('vie' => 'vi', 'vi' => 'vie'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('xho', 'xh')); + $expected = array('xho' => 'xh', 'xh' => 'xho'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('cy', 'cym')); + $expected = array('cym' => 'cy', 'cy' => 'cym'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('yid', 'yi')); + $expected = array('yid' => 'yi', 'yi' => 'yid'); + $this->assertEquals($expected, $result); + + $result = $localize->map(array('zul', 'zu')); + $expected = array('zul' => 'zu', 'zu' => 'zul'); + $this->assertEquals($expected, $result); + } + +/** + * testCatalog method + * + * @return void + */ + public function testCatalog() { + $localize = new L10n(); + + $result = $localize->catalog(array('af')); + $expected = array( + 'af' => array('language' => 'Afrikaans', 'locale' => 'afr', 'localeFallback' => 'afr', 'charset' => 'utf-8', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('ar', 'ar-ae', 'ar-bh', 'ar-dz', 'ar-eg', 'ar-iq', 'ar-jo', 'ar-kw', 'ar-lb', 'ar-ly', 'ar-ma', + 'ar-om', 'ar-qa', 'ar-sa', 'ar-sy', 'ar-tn', 'ar-ye')); + $expected = array( + 'ar' => array('language' => 'Arabic', 'locale' => 'ara', 'localeFallback' => 'ara', 'charset' => 'utf-8', 'direction' => 'rtl'), + 'ar-ae' => array('language' => 'Arabic (U.A.E.)', 'locale' => 'ar_ae', 'localeFallback' => 'ara', 'charset' => 'utf-8', 'direction' => 'rtl'), + 'ar-bh' => array('language' => 'Arabic (Bahrain)', 'locale' => 'ar_bh', 'localeFallback' => 'ara', 'charset' => 'utf-8', 'direction' => 'rtl'), + 'ar-dz' => array('language' => 'Arabic (Algeria)', 'locale' => 'ar_dz', 'localeFallback' => 'ara', 'charset' => 'utf-8', 'direction' => 'rtl'), + 'ar-eg' => array('language' => 'Arabic (Egypt)', 'locale' => 'ar_eg', 'localeFallback' => 'ara', 'charset' => 'utf-8', 'direction' => 'rtl'), + 'ar-iq' => array('language' => 'Arabic (Iraq)', 'locale' => 'ar_iq', 'localeFallback' => 'ara', 'charset' => 'utf-8', 'direction' => 'rtl'), + 'ar-jo' => array('language' => 'Arabic (Jordan)', 'locale' => 'ar_jo', 'localeFallback' => 'ara', 'charset' => 'utf-8', 'direction' => 'rtl'), + 'ar-kw' => array('language' => 'Arabic (Kuwait)', 'locale' => 'ar_kw', 'localeFallback' => 'ara', 'charset' => 'utf-8', 'direction' => 'rtl'), + 'ar-lb' => array('language' => 'Arabic (Lebanon)', 'locale' => 'ar_lb', 'localeFallback' => 'ara', 'charset' => 'utf-8', 'direction' => 'rtl'), + 'ar-ly' => array('language' => 'Arabic (Libya)', 'locale' => 'ar_ly', 'localeFallback' => 'ara', 'charset' => 'utf-8', 'direction' => 'rtl'), + 'ar-ma' => array('language' => 'Arabic (Morocco)', 'locale' => 'ar_ma', 'localeFallback' => 'ara', 'charset' => 'utf-8', 'direction' => 'rtl'), + 'ar-om' => array('language' => 'Arabic (Oman)', 'locale' => 'ar_om', 'localeFallback' => 'ara', 'charset' => 'utf-8', 'direction' => 'rtl'), + 'ar-qa' => array('language' => 'Arabic (Qatar)', 'locale' => 'ar_qa', 'localeFallback' => 'ara', 'charset' => 'utf-8', 'direction' => 'rtl'), + 'ar-sa' => array('language' => 'Arabic (Saudi Arabia)', 'locale' => 'ar_sa', 'localeFallback' => 'ara', 'charset' => 'utf-8', 'direction' => 'rtl'), + 'ar-sy' => array('language' => 'Arabic (Syria)', 'locale' => 'ar_sy', 'localeFallback' => 'ara', 'charset' => 'utf-8', 'direction' => 'rtl'), + 'ar-tn' => array('language' => 'Arabic (Tunisia)', 'locale' => 'ar_tn', 'localeFallback' => 'ara', 'charset' => 'utf-8', 'direction' => 'rtl'), + 'ar-ye' => array('language' => 'Arabic (Yemen)', 'locale' => 'ar_ye', 'localeFallback' => 'ara', 'charset' => 'utf-8', 'direction' => 'rtl') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('be')); + $expected = array( + 'be' => array('language' => 'Byelorussian', 'locale' => 'bel', 'localeFallback' => 'bel', 'charset' => 'utf-8', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('bg')); + $expected = array( + 'bg' => array('language' => 'Bulgarian', 'locale' => 'bul', 'localeFallback' => 'bul', 'charset' => 'utf-8', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('bs')); + $expected = array( + 'bs' => array('language' => 'Bosnian', 'locale' => 'bos', 'localeFallback' => 'bos', 'charset' => 'utf-8', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('ca')); + $expected = array( + 'ca' => array('language' => 'Catalan', 'locale' => 'cat', 'localeFallback' => 'cat', 'charset' => 'utf-8', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('cs')); + $expected = array( + 'cs' => array('language' => 'Czech', 'locale' => 'cze', 'localeFallback' => 'cze', 'charset' => 'utf-8', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('da')); + $expected = array( + 'da' => array('language' => 'Danish', 'locale' => 'dan', 'localeFallback' => 'dan', 'charset' => 'utf-8', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('de', 'de-at', 'de-ch', 'de-de', 'de-li', 'de-lu')); + $expected = array( + 'de' => array('language' => 'German (Standard)', 'locale' => 'deu', 'localeFallback' => 'deu', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'de-at' => array('language' => 'German (Austria)', 'locale' => 'de_at', 'localeFallback' => 'deu', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'de-ch' => array('language' => 'German (Swiss)', 'locale' => 'de_ch', 'localeFallback' => 'deu', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'de-de' => array('language' => 'German (Germany)', 'locale' => 'de_de', 'localeFallback' => 'deu', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'de-li' => array('language' => 'German (Liechtenstein)', 'locale' => 'de_li', 'localeFallback' => 'deu', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'de-lu' => array('language' => 'German (Luxembourg)', 'locale' => 'de_lu', 'localeFallback' => 'deu', 'charset' => 'utf-8', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('e', 'el')); + $expected = array( + 'e' => array('language' => 'Greek', 'locale' => 'gre', 'localeFallback' => 'gre', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'el' => array('language' => 'Greek', 'locale' => 'gre', 'localeFallback' => 'gre', 'charset' => 'utf-8', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('en', 'en-au', 'en-bz', 'en-ca', 'en-gb', 'en-ie', 'en-jm', 'en-nz', 'en-tt', 'en-us', 'en-za')); + $expected = array( + 'en' => array('language' => 'English', 'locale' => 'eng', 'localeFallback' => 'eng', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'en-au' => array('language' => 'English (Australian)', 'locale' => 'en_au', 'localeFallback' => 'eng', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'en-bz' => array('language' => 'English (Belize)', 'locale' => 'en_bz', 'localeFallback' => 'eng', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'en-ca' => array('language' => 'English (Canadian)', 'locale' => 'en_ca', 'localeFallback' => 'eng', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'en-gb' => array('language' => 'English (British)', 'locale' => 'en_gb', 'localeFallback' => 'eng', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'en-ie' => array('language' => 'English (Ireland)', 'locale' => 'en_ie', 'localeFallback' => 'eng', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'en-jm' => array('language' => 'English (Jamaica)', 'locale' => 'en_jm', 'localeFallback' => 'eng', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'en-nz' => array('language' => 'English (New Zealand)', 'locale' => 'en_nz', 'localeFallback' => 'eng', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'en-tt' => array('language' => 'English (Trinidad)', 'locale' => 'en_tt', 'localeFallback' => 'eng', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'en-us' => array('language' => 'English (United States)', 'locale' => 'en_us', 'localeFallback' => 'eng', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'en-za' => array('language' => 'English (South Africa)', 'locale' => 'en_za', 'localeFallback' => 'eng', 'charset' => 'utf-8', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('es', 'es-ar', 'es-bo', 'es-cl', 'es-co', 'es-cr', 'es-do', 'es-ec', 'es-es', 'es-gt', 'es-hn', + 'es-mx', 'es-ni', 'es-pa', 'es-pe', 'es-pr', 'es-py', 'es-sv', 'es-uy', 'es-ve')); + $expected = array( + 'es' => array('language' => 'Spanish (Spain - Traditional)', 'locale' => 'spa', 'localeFallback' => 'spa', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'es-ar' => array('language' => 'Spanish (Argentina)', 'locale' => 'es_ar', 'localeFallback' => 'spa', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'es-bo' => array('language' => 'Spanish (Bolivia)', 'locale' => 'es_bo', 'localeFallback' => 'spa', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'es-cl' => array('language' => 'Spanish (Chile)', 'locale' => 'es_cl', 'localeFallback' => 'spa', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'es-co' => array('language' => 'Spanish (Colombia)', 'locale' => 'es_co', 'localeFallback' => 'spa', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'es-cr' => array('language' => 'Spanish (Costa Rica)', 'locale' => 'es_cr', 'localeFallback' => 'spa', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'es-do' => array('language' => 'Spanish (Dominican Republic)', 'locale' => 'es_do', 'localeFallback' => 'spa', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'es-ec' => array('language' => 'Spanish (Ecuador)', 'locale' => 'es_ec', 'localeFallback' => 'spa', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'es-es' => array('language' => 'Spanish (Spain)', 'locale' => 'es_es', 'localeFallback' => 'spa', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'es-gt' => array('language' => 'Spanish (Guatemala)', 'locale' => 'es_gt', 'localeFallback' => 'spa', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'es-hn' => array('language' => 'Spanish (Honduras)', 'locale' => 'es_hn', 'localeFallback' => 'spa', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'es-mx' => array('language' => 'Spanish (Mexican)', 'locale' => 'es_mx', 'localeFallback' => 'spa', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'es-ni' => array('language' => 'Spanish (Nicaragua)', 'locale' => 'es_ni', 'localeFallback' => 'spa', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'es-pa' => array('language' => 'Spanish (Panama)', 'locale' => 'es_pa', 'localeFallback' => 'spa', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'es-pe' => array('language' => 'Spanish (Peru)', 'locale' => 'es_pe', 'localeFallback' => 'spa', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'es-pr' => array('language' => 'Spanish (Puerto Rico)', 'locale' => 'es_pr', 'localeFallback' => 'spa', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'es-py' => array('language' => 'Spanish (Paraguay)', 'locale' => 'es_py', 'localeFallback' => 'spa', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'es-sv' => array('language' => 'Spanish (El Salvador)', 'locale' => 'es_sv', 'localeFallback' => 'spa', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'es-uy' => array('language' => 'Spanish (Uruguay)', 'locale' => 'es_uy', 'localeFallback' => 'spa', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'es-ve' => array('language' => 'Spanish (Venezuela)', 'locale' => 'es_ve', 'localeFallback' => 'spa', 'charset' => 'utf-8', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('et')); + $expected = array( + 'et' => array('language' => 'Estonian', 'locale' => 'est', 'localeFallback' => 'est', 'charset' => 'utf-8', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('eu')); + $expected = array( + 'eu' => array('language' => 'Basque', 'locale' => 'baq', 'localeFallback' => 'baq', 'charset' => 'utf-8', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('fa')); + $expected = array( + 'fa' => array('language' => 'Farsi', 'locale' => 'per', 'localeFallback' => 'per', 'charset' => 'utf-8', 'direction' => 'rtl') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('fi')); + $expected = array( + 'fi' => array('language' => 'Finnish', 'locale' => 'fin', 'localeFallback' => 'fin', 'charset' => 'utf-8', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('fo')); + $expected = array( + 'fo' => array('language' => 'Faeroese', 'locale' => 'fao', 'localeFallback' => 'fao', 'charset' => 'utf-8', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('fr', 'fr-be', 'fr-ca', 'fr-ch', 'fr-fr', 'fr-lu')); + $expected = array( + 'fr' => array('language' => 'French (Standard)', 'locale' => 'fre', 'localeFallback' => 'fre', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'fr-be' => array('language' => 'French (Belgium)', 'locale' => 'fr_be', 'localeFallback' => 'fre', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'fr-ca' => array('language' => 'French (Canadian)', 'locale' => 'fr_ca', 'localeFallback' => 'fre', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'fr-ch' => array('language' => 'French (Swiss)', 'locale' => 'fr_ch', 'localeFallback' => 'fre', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'fr-fr' => array('language' => 'French (France)', 'locale' => 'fr_fr', 'localeFallback' => 'fre', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'fr-lu' => array('language' => 'French (Luxembourg)', 'locale' => 'fr_lu', 'localeFallback' => 'fre', 'charset' => 'utf-8', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('ga')); + $expected = array( + 'ga' => array('language' => 'Irish', 'locale' => 'gle', 'localeFallback' => 'gle', 'charset' => 'utf-8', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('gd', 'gd-ie')); + $expected = array( + 'gd' => array('language' => 'Gaelic (Scots)', 'locale' => 'gla', 'localeFallback' => 'gla', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'gd-ie' => array('language' => 'Gaelic (Irish)', 'locale' => 'gd_ie', 'localeFallback' => 'gla', 'charset' => 'utf-8', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('gl')); + $expected = array( + 'gl' => array('language' => 'Galician', 'locale' => 'glg', 'localeFallback' => 'glg', 'charset' => 'utf-8', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('he')); + $expected = array( + 'he' => array('language' => 'Hebrew', 'locale' => 'heb', 'localeFallback' => 'heb', 'charset' => 'utf-8', 'direction' => 'rtl') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('hi')); + $expected = array( + 'hi' => array('language' => 'Hindi', 'locale' => 'hin', 'localeFallback' => 'hin', 'charset' => 'utf-8', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('hr')); + $expected = array( + 'hr' => array('language' => 'Croatian', 'locale' => 'hrv', 'localeFallback' => 'hrv', 'charset' => 'utf-8', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('hu')); + $expected = array( + 'hu' => array('language' => 'Hungarian', 'locale' => 'hun', 'localeFallback' => 'hun', 'charset' => 'utf-8', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('hy')); + $expected = array( + 'hy' => array('language' => 'Armenian - Armenia', 'locale' => 'hye', 'localeFallback' => 'hye', 'charset' => 'utf-8', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('id', 'in')); + $expected = array( + 'id' => array('language' => 'Indonesian', 'locale' => 'ind', 'localeFallback' => 'ind', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'in' => array('language' => 'Indonesian', 'locale' => 'ind', 'localeFallback' => 'ind', 'charset' => 'utf-8', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('is')); + $expected = array( + 'is' => array('language' => 'Icelandic', 'locale' => 'ice', 'localeFallback' => 'ice', 'charset' => 'utf-8', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('it', 'it-ch')); + $expected = array( + 'it' => array('language' => 'Italian', 'locale' => 'ita', 'localeFallback' => 'ita', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'it-ch' => array('language' => 'Italian (Swiss) ', 'locale' => 'it_ch', 'localeFallback' => 'ita', 'charset' => 'utf-8', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('ja')); + $expected = array( + 'ja' => array('language' => 'Japanese', 'locale' => 'jpn', 'localeFallback' => 'jpn', 'charset' => 'utf-8', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('ko', 'ko-kp', 'ko-kr')); + $expected = array( + 'ko' => array('language' => 'Korean', 'locale' => 'kor', 'localeFallback' => 'kor', 'charset' => 'kr', 'direction' => 'ltr'), + 'ko-kp' => array('language' => 'Korea (North)', 'locale' => 'ko_kp', 'localeFallback' => 'kor', 'charset' => 'kr', 'direction' => 'ltr'), + 'ko-kr' => array('language' => 'Korea (South)', 'locale' => 'ko_kr', 'localeFallback' => 'kor', 'charset' => 'kr', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('koi8-r', 'ru', 'ru-mo')); + $expected = array( + 'koi8-r' => array('language' => 'Russian', 'locale' => 'koi8_r', 'localeFallback' => 'rus', 'charset' => 'koi8-r', 'direction' => 'ltr'), + 'ru' => array('language' => 'Russian', 'locale' => 'rus', 'localeFallback' => 'rus', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'ru-mo' => array('language' => 'Russian (Moldavia)', 'locale' => 'ru_mo', 'localeFallback' => 'rus', 'charset' => 'utf-8', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('lt')); + $expected = array( + 'lt' => array('language' => 'Lithuanian', 'locale' => 'lit', 'localeFallback' => 'lit', 'charset' => 'utf-8', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('lv')); + $expected = array( + 'lv' => array('language' => 'Latvian', 'locale' => 'lav', 'localeFallback' => 'lav', 'charset' => 'utf-8', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('mk', 'mk-mk')); + $expected = array( + 'mk' => array('language' => 'FYRO Macedonian', 'locale' => 'mk', 'localeFallback' => 'mac', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'mk-mk' => array('language' => 'Macedonian', 'locale' => 'mk_mk', 'localeFallback' => 'mac', 'charset' => 'utf-8', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('ms')); + $expected = array( + 'ms' => array('language' => 'Malaysian', 'locale' => 'may', 'localeFallback' => 'may', 'charset' => 'utf-8', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('mt')); + $expected = array( + 'mt' => array('language' => 'Maltese', 'locale' => 'mlt', 'localeFallback' => 'mlt', 'charset' => 'utf-8', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('n', 'nl', 'nl-be')); + $expected = array( + 'n' => array('language' => 'Dutch (Standard)', 'locale' => 'dut', 'localeFallback' => 'dut', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'nl' => array('language' => 'Dutch (Standard)', 'locale' => 'dut', 'localeFallback' => 'dut', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'nl-be' => array('language' => 'Dutch (Belgium)', 'locale' => 'nl_be', 'localeFallback' => 'dut', 'charset' => 'utf-8', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog('nl'); + $expected = array('language' => 'Dutch (Standard)', 'locale' => 'dut', 'localeFallback' => 'dut', 'charset' => 'utf-8', 'direction' => 'ltr'); + $this->assertEquals($expected, $result); + + $result = $localize->catalog('nld'); + $expected = array('language' => 'Dutch (Standard)', 'locale' => 'dut', 'localeFallback' => 'dut', 'charset' => 'utf-8', 'direction' => 'ltr'); + $this->assertEquals($expected, $result); + + $result = $localize->catalog('dut'); + $expected = array('language' => 'Dutch (Standard)', 'locale' => 'dut', 'localeFallback' => 'dut', 'charset' => 'utf-8', 'direction' => 'ltr'); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('nb')); + $expected = array( + 'nb' => array('language' => 'Norwegian Bokmal', 'locale' => 'nob', 'localeFallback' => 'nor', 'charset' => 'utf-8', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('nn', 'no')); + $expected = array( + 'nn' => array('language' => 'Norwegian Nynorsk', 'locale' => 'nno', 'localeFallback' => 'nor', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'no' => array('language' => 'Norwegian', 'locale' => 'nor', 'localeFallback' => 'nor', 'charset' => 'utf-8', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('p', 'pl')); + $expected = array( + 'p' => array('language' => 'Polish', 'locale' => 'pol', 'localeFallback' => 'pol', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'pl' => array('language' => 'Polish', 'locale' => 'pol', 'localeFallback' => 'pol', 'charset' => 'utf-8', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('pt', 'pt-br')); + $expected = array( + 'pt' => array('language' => 'Portuguese (Portugal)', 'locale' => 'por', 'localeFallback' => 'por', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'pt-br' => array('language' => 'Portuguese (Brazil)', 'locale' => 'pt_br', 'localeFallback' => 'por', 'charset' => 'utf-8', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('rm')); + $expected = array( + 'rm' => array('language' => 'Rhaeto-Romanic', 'locale' => 'roh', 'localeFallback' => 'roh', 'charset' => 'utf-8', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('ro', 'ro-mo')); + $expected = array( + 'ro' => array('language' => 'Romanian', 'locale' => 'rum', 'localeFallback' => 'rum', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'ro-mo' => array('language' => 'Romanian (Moldavia)', 'locale' => 'ro_mo', 'localeFallback' => 'rum', 'charset' => 'utf-8', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('sb')); + $expected = array( + 'sb' => array('language' => 'Sorbian', 'locale' => 'wen', 'localeFallback' => 'wen', 'charset' => 'utf-8', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('sk')); + $expected = array( + 'sk' => array('language' => 'Slovak', 'locale' => 'slo', 'localeFallback' => 'slo', 'charset' => 'utf-8', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('sl')); + $expected = array( + 'sl' => array('language' => 'Slovenian', 'locale' => 'slv', 'localeFallback' => 'slv', 'charset' => 'utf-8', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('sq')); + $expected = array( + 'sq' => array('language' => 'Albanian', 'locale' => 'alb', 'localeFallback' => 'alb', 'charset' => 'utf-8', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('sr')); + $expected = array( + 'sr' => array('language' => 'Serbian', 'locale' => 'scc', 'localeFallback' => 'scc', 'charset' => 'utf-8', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('sv', 'sv-fi')); + $expected = array( + 'sv' => array('language' => 'Swedish', 'locale' => 'swe', 'localeFallback' => 'swe', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'sv-fi' => array('language' => 'Swedish (Finland)', 'locale' => 'sv_fi', 'localeFallback' => 'swe', 'charset' => 'utf-8', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('sx')); + $expected = array( + 'sx' => array('language' => 'Sutu', 'locale' => 'sx', 'localeFallback' => 'sx', 'charset' => 'utf-8', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('sz')); + $expected = array( + 'sz' => array('language' => 'Sami (Lappish)', 'locale' => 'smi', 'localeFallback' => 'smi', 'charset' => 'utf-8', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('th')); + $expected = array( + 'th' => array('language' => 'Thai', 'locale' => 'tha', 'localeFallback' => 'tha', 'charset' => 'utf-8', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('tn')); + $expected = array( + 'tn' => array('language' => 'Tswana', 'locale' => 'tsn', 'localeFallback' => 'tsn', 'charset' => 'utf-8', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('tr')); + $expected = array( + 'tr' => array('language' => 'Turkish', 'locale' => 'tur', 'localeFallback' => 'tur', 'charset' => 'utf-8', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('ts')); + $expected = array( + 'ts' => array('language' => 'Tsonga', 'locale' => 'tso', 'localeFallback' => 'tso', 'charset' => 'utf-8', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('uk')); + $expected = array( + 'uk' => array('language' => 'Ukrainian', 'locale' => 'ukr', 'localeFallback' => 'ukr', 'charset' => 'utf-8', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('ur')); + $expected = array( + 'ur' => array('language' => 'Urdu', 'locale' => 'urd', 'localeFallback' => 'urd', 'charset' => 'utf-8', 'direction' => 'rtl') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('ve')); + $expected = array( + 've' => array('language' => 'Venda', 'locale' => 'ven', 'localeFallback' => 'ven', 'charset' => 'utf-8', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('vi')); + $expected = array( + 'vi' => array('language' => 'Vietnamese', 'locale' => 'vie', 'localeFallback' => 'vie', 'charset' => 'utf-8', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('cy')); + $expected = array( + 'cy' => array('language' => 'Welsh', 'locale' => 'cym', 'localeFallback' => 'cym', 'charset' => 'utf-8', + 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('xh')); + $expected = array( + 'xh' => array('language' => 'Xhosa', 'locale' => 'xho', 'localeFallback' => 'xho', 'charset' => 'utf-8', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('yi')); + $expected = array( + 'yi' => array('language' => 'Yiddish', 'locale' => 'yid', 'localeFallback' => 'yid', 'charset' => 'utf-8', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('zh', 'zh-cn', 'zh-hk', 'zh-sg', 'zh-tw')); + $expected = array( + 'zh' => array('language' => 'Chinese', 'locale' => 'chi', 'localeFallback' => 'chi', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'zh-cn' => array('language' => 'Chinese (PRC)', 'locale' => 'zh_cn', 'localeFallback' => 'chi', 'charset' => 'GB2312', 'direction' => 'ltr'), + 'zh-hk' => array('language' => 'Chinese (Hong Kong)', 'locale' => 'zh_hk', 'localeFallback' => 'chi', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'zh-sg' => array('language' => 'Chinese (Singapore)', 'locale' => 'zh_sg', 'localeFallback' => 'chi', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'zh-tw' => array('language' => 'Chinese (Taiwan)', 'locale' => 'zh_tw', 'localeFallback' => 'chi', 'charset' => 'utf-8', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('zu')); + $expected = array( + 'zu' => array('language' => 'Zulu', 'locale' => 'zul', 'localeFallback' => 'zul', 'charset' => 'utf-8', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('en-nz', 'es-do', 'sz', 'ar-lb', 'zh-hk', 'pt-br')); + $expected = array( + 'en-nz' => array('language' => 'English (New Zealand)', 'locale' => 'en_nz', 'localeFallback' => 'eng', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'es-do' => array('language' => 'Spanish (Dominican Republic)', 'locale' => 'es_do', 'localeFallback' => 'spa', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'sz' => array('language' => 'Sami (Lappish)', 'locale' => 'smi', 'localeFallback' => 'smi', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'ar-lb' => array('language' => 'Arabic (Lebanon)', 'locale' => 'ar_lb', 'localeFallback' => 'ara', 'charset' => 'utf-8', 'direction' => 'rtl'), + 'zh-hk' => array('language' => 'Chinese (Hong Kong)', 'locale' => 'zh_hk', 'localeFallback' => 'chi', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'pt-br' => array('language' => 'Portuguese (Brazil)', 'locale' => 'pt_br', 'localeFallback' => 'por', 'charset' => 'utf-8', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + + $result = $localize->catalog(array('eng', 'deu', 'zho', 'rum', 'zul', 'yid')); + $expected = array( + 'eng' => array('language' => 'English', 'locale' => 'eng', 'localeFallback' => 'eng', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'deu' => array('language' => 'German (Standard)', 'locale' => 'deu', 'localeFallback' => 'deu', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'zho' => array('language' => 'Chinese', 'locale' => 'chi', 'localeFallback' => 'chi', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'rum' => array('language' => 'Romanian', 'locale' => 'rum', 'localeFallback' => 'rum', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'zul' => array('language' => 'Zulu', 'locale' => 'zul', 'localeFallback' => 'zul', 'charset' => 'utf-8', 'direction' => 'ltr'), + 'yid' => array('language' => 'Yiddish', 'locale' => 'yid', 'localeFallback' => 'yid', 'charset' => 'utf-8', 'direction' => 'ltr') + ); + $this->assertEquals($expected, $result); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/I18n/MultibyteTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/I18n/MultibyteTest.php new file mode 100644 index 0000000..927b844 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/I18n/MultibyteTest.php @@ -0,0 +1,9228 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.I18n + * @since CakePHP(tm) v 1.2.0.6833 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ +App::uses('Multibyte', 'I18n'); + +/** + * MultibyteTest class + * + * @package Cake.Test.Case.I18n + */ +class MultibyteTest extends CakeTestCase { + +/** + * testUtf8 method + * + * @return void + */ + public function testUtf8() { + $string = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'; + $result = Multibyte::utf8($string); + $expected = array(33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, + 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, + 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, + 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126); + $this->assertEquals($expected, $result); + + $string = '¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈ'; + $result = Multibyte::utf8($string); + $expected = array(161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, + 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200); + $this->assertEquals($expected, $result); + + $string = 'ÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬ'; + $result = Multibyte::utf8($string); + $expected = array(201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, + 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, + 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, + 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, + 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300); + $this->assertEquals($expected, $result); + + $string = 'ĭĮįİıIJijĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏƐ'; + $result = Multibyte::utf8($string); + $expected = array(301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, + 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, + 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, + 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, + 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400); + $this->assertEquals($expected, $result); + + $string = 'ƑƒƓƔƕƖƗƘƙƚƛƜƝƞƟƠơƢƣƤƥƦƧƨƩƪƫƬƭƮƯưƱƲƳƴƵƶƷƸƹƺƻƼƽƾƿǀǁǂǃDŽDždžLJLjljNJNjnjǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰDZDzdzǴ'; + $result = Multibyte::utf8($string); + $expected = array(401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 420, 421, + 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 442, + 443, 444, 445, 446, 447, 448, 449, 450, 451, 452, 453, 454, 455, 456, 457, 458, 459, 460, 461, 462, 463, + 464, 465, 466, 467, 468, 469, 470, 471, 472, 473, 474, 475, 476, 477, 478, 479, 480, 481, 482, 483, 484, + 485, 486, 487, 488, 489, 490, 491, 492, 493, 494, 495, 496, 497, 498, 499, 500); + $this->assertEquals($expected, $result); + + $string = 'əɚɛɜɝɞɟɠɡɢɣɤɥɦɧɨɩɪɫɬɭɮɯɰɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿʀʁʂʃʄʅʆʇʈʉʊʋʌʍʎʏʐʑʒʓʔʕʖʗʘʙʚʛʜʝʞʟʠʡʢʣʤʥʦʧʨʩʪʫʬʭʮʯʰʱʲʳʴʵʶʷʸʹʺʻʼ'; + $result = Multibyte::utf8($string); + $expected = array(601, 602, 603, 604, 605, 606, 607, 608, 609, 610, 611, 612, 613, 614, 615, 616, 617, 618, 619, 620, 621, + 622, 623, 624, 625, 626, 627, 628, 629, 630, 631, 632, 633, 634, 635, 636, 637, 638, 639, 640, 641, 642, + 643, 644, 645, 646, 647, 648, 649, 650, 651, 652, 653, 654, 655, 656, 657, 658, 659, 660, 661, 662, 663, + 664, 665, 666, 667, 668, 669, 670, 671, 672, 673, 674, 675, 676, 677, 678, 679, 680, 681, 682, 683, 684, + 685, 686, 687, 688, 689, 690, 691, 692, 693, 694, 695, 696, 697, 698, 699, 700); + $this->assertEquals($expected, $result); + + $string = 'ЀЁЂЃЄЅІЇЈЉЊЋЌЍЎЏАБВГДЕЖЗИЙКЛ'; + $result = Multibyte::utf8($string); + $expected = array(1024, 1025, 1026, 1027, 1028, 1029, 1030, 1031, 1032, 1033, 1034, 1035, 1036, 1037, 1038, 1039, 1040, 1041, + 1042, 1043, 1044, 1045, 1046, 1047, 1048, 1049, 1050, 1051); + $this->assertEquals($expected, $result); + + $string = 'МНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыь'; + $result = Multibyte::utf8($string); + $expected = array(1052, 1053, 1054, 1055, 1056, 1057, 1058, 1059, 1060, 1061, 1062, 1063, 1064, 1065, 1066, 1067, 1068, 1069, + 1070, 1071, 1072, 1073, 1074, 1075, 1076, 1077, 1078, 1079, 1080, 1081, 1082, 1083, 1084, 1085, 1086, 1087, + 1088, 1089, 1090, 1091, 1092, 1093, 1094, 1095, 1096, 1097, 1098, 1099, 1100); + $this->assertEquals($expected, $result); + + $string = 'չպջռսվտ'; + $result = Multibyte::utf8($string); + $expected = array(1401, 1402, 1403, 1404, 1405, 1406, 1407); + $this->assertEquals($expected, $result); + + $string = 'فقكلمنهوىيًٌٍَُ'; + $result = Multibyte::utf8($string); + $expected = array(1601, 1602, 1603, 1604, 1605, 1606, 1607, 1608, 1609, 1610, 1611, 1612, 1613, 1614, 1615); + $this->assertEquals($expected, $result); + + $string = '✰✱✲✳✴✵✶✷✸✹✺✻✼✽✾✿❀❁❂❃❄❅❆❇❈❉❊❋❌❍❎❏❐❑❒❓❔❕❖❗❘❙❚❛❜❝❞'; + $result = Multibyte::utf8($string); + $expected = array(10032, 10033, 10034, 10035, 10036, 10037, 10038, 10039, 10040, 10041, 10042, 10043, 10044, + 10045, 10046, 10047, 10048, 10049, 10050, 10051, 10052, 10053, 10054, 10055, 10056, 10057, + 10058, 10059, 10060, 10061, 10062, 10063, 10064, 10065, 10066, 10067, 10068, 10069, 10070, + 10071, 10072, 10073, 10074, 10075, 10076, 10077, 10078); + $this->assertEquals($expected, $result); + + $string = '⺀⺁⺂⺃⺄⺅⺆⺇⺈⺉⺊⺋⺌⺍⺎⺏⺐⺑⺒⺓⺔⺕⺖⺗⺘⺙⺛⺜⺝⺞⺟⺠⺡⺢⺣⺤⺥⺦⺧⺨⺩⺪⺫⺬⺭⺮⺯⺰⺱⺲⺳⺴⺵⺶⺷⺸⺹⺺⺻⺼⺽⺾⺿⻀⻁⻂⻃⻄⻅⻆⻇⻈⻉⻊⻋⻌⻍⻎⻏⻐⻑⻒⻓⻔⻕⻖⻗⻘⻙⻚⻛⻜⻝⻞⻟⻠'; + $result = Multibyte::utf8($string); + $expected = array(11904, 11905, 11906, 11907, 11908, 11909, 11910, 11911, 11912, 11913, 11914, 11915, 11916, 11917, 11918, 11919, + 11920, 11921, 11922, 11923, 11924, 11925, 11926, 11927, 11928, 11929, 11931, 11932, 11933, 11934, 11935, 11936, + 11937, 11938, 11939, 11940, 11941, 11942, 11943, 11944, 11945, 11946, 11947, 11948, 11949, 11950, 11951, 11952, + 11953, 11954, 11955, 11956, 11957, 11958, 11959, 11960, 11961, 11962, 11963, 11964, 11965, 11966, 11967, 11968, + 11969, 11970, 11971, 11972, 11973, 11974, 11975, 11976, 11977, 11978, 11979, 11980, 11981, 11982, 11983, 11984, + 11985, 11986, 11987, 11988, 11989, 11990, 11991, 11992, 11993, 11994, 11995, 11996, 11997, 11998, 11999, 12000); + $this->assertEquals($expected, $result); + + $string = '⽅⽆⽇⽈⽉⽊⽋⽌⽍⽎⽏⽐⽑⽒⽓⽔⽕⽖⽗⽘⽙⽚⽛⽜⽝⽞⽟⽠⽡⽢⽣⽤⽥⽦⽧⽨⽩⽪⽫⽬⽭⽮⽯⽰⽱⽲⽳⽴⽵⽶⽷⽸⽹⽺⽻⽼⽽⽾⽿'; + $result = Multibyte::utf8($string); + $expected = array(12101, 12102, 12103, 12104, 12105, 12106, 12107, 12108, 12109, 12110, 12111, 12112, 12113, 12114, 12115, 12116, + 12117, 12118, 12119, 12120, 12121, 12122, 12123, 12124, 12125, 12126, 12127, 12128, 12129, 12130, 12131, 12132, + 12133, 12134, 12135, 12136, 12137, 12138, 12139, 12140, 12141, 12142, 12143, 12144, 12145, 12146, 12147, 12148, + 12149, 12150, 12151, 12152, 12153, 12154, 12155, 12156, 12157, 12158, 12159); + $this->assertEquals($expected, $result); + + $string = '눡눢눣눤눥눦눧눨눩눪눫눬눭눮눯눰눱눲눳눴눵눶눷눸눹눺눻눼눽눾눿뉀뉁뉂뉃뉄뉅뉆뉇뉈뉉뉊뉋뉌뉍뉎뉏뉐뉑뉒뉓뉔뉕뉖뉗뉘뉙뉚뉛뉜뉝뉞뉟뉠뉡뉢뉣뉤뉥뉦뉧뉨뉩뉪뉫뉬뉭뉮뉯뉰뉱뉲뉳뉴뉵뉶뉷뉸뉹뉺뉻뉼뉽뉾뉿늀늁늂늃늄'; + $result = Multibyte::utf8($string); + $expected = array(45601, 45602, 45603, 45604, 45605, 45606, 45607, 45608, 45609, 45610, 45611, 45612, 45613, 45614, 45615, 45616, + 45617, 45618, 45619, 45620, 45621, 45622, 45623, 45624, 45625, 45626, 45627, 45628, 45629, 45630, 45631, 45632, + 45633, 45634, 45635, 45636, 45637, 45638, 45639, 45640, 45641, 45642, 45643, 45644, 45645, 45646, 45647, 45648, + 45649, 45650, 45651, 45652, 45653, 45654, 45655, 45656, 45657, 45658, 45659, 45660, 45661, 45662, 45663, 45664, + 45665, 45666, 45667, 45668, 45669, 45670, 45671, 45672, 45673, 45674, 45675, 45676, 45677, 45678, 45679, 45680, + 45681, 45682, 45683, 45684, 45685, 45686, 45687, 45688, 45689, 45690, 45691, 45692, 45693, 45694, 45695, 45696, + 45697, 45698, 45699, 45700); + $this->assertEquals($expected, $result); + + $string = 'ﹰﹱﹲﹳﹴ﹵ﹶﹷﹸﹹﹺﹻﹼﹽﹾﹿﺀﺁﺂﺃﺄﺅﺆﺇﺈﺉﺊﺋﺌﺍﺎﺏﺐﺑﺒﺓﺔﺕﺖﺗﺘﺙﺚﺛﺜﺝﺞﺟﺠﺡﺢﺣﺤﺥﺦﺧﺨﺩﺪﺫﺬﺭﺮﺯﺰ'; + $result = Multibyte::utf8($string); + $expected = array(65136, 65137, 65138, 65139, 65140, 65141, 65142, 65143, 65144, 65145, 65146, 65147, 65148, 65149, 65150, 65151, + 65152, 65153, 65154, 65155, 65156, 65157, 65158, 65159, 65160, 65161, 65162, 65163, 65164, 65165, 65166, 65167, + 65168, 65169, 65170, 65171, 65172, 65173, 65174, 65175, 65176, 65177, 65178, 65179, 65180, 65181, 65182, 65183, + 65184, 65185, 65186, 65187, 65188, 65189, 65190, 65191, 65192, 65193, 65194, 65195, 65196, 65197, 65198, 65199, + 65200); + $this->assertEquals($expected, $result); + + $string = 'ﺱﺲﺳﺴﺵﺶﺷﺸﺹﺺﺻﺼﺽﺾﺿﻀﻁﻂﻃﻄﻅﻆﻇﻈﻉﻊﻋﻌﻍﻎﻏﻐﻑﻒﻓﻔﻕﻖﻗﻘﻙﻚﻛﻜﻝﻞﻟﻠﻡﻢﻣﻤﻥﻦﻧﻨﻩﻪﻫﻬﻭﻮﻯﻰﻱﻲﻳﻴﻵﻶﻷﻸﻹﻺﻻﻼ'; + $result = Multibyte::utf8($string); + $expected = array(65201, 65202, 65203, 65204, 65205, 65206, 65207, 65208, 65209, 65210, 65211, 65212, 65213, 65214, 65215, 65216, + 65217, 65218, 65219, 65220, 65221, 65222, 65223, 65224, 65225, 65226, 65227, 65228, 65229, 65230, 65231, 65232, + 65233, 65234, 65235, 65236, 65237, 65238, 65239, 65240, 65241, 65242, 65243, 65244, 65245, 65246, 65247, 65248, + 65249, 65250, 65251, 65252, 65253, 65254, 65255, 65256, 65257, 65258, 65259, 65260, 65261, 65262, 65263, 65264, + 65265, 65266, 65267, 65268, 65269, 65270, 65271, 65272, 65273, 65274, 65275, 65276); + $this->assertEquals($expected, $result); + + $string = 'abcdefghijklmnopqrstuvwxyz'; + $result = Multibyte::utf8($string); + $expected = array(65345, 65346, 65347, 65348, 65349, 65350, 65351, 65352, 65353, 65354, 65355, 65356, 65357, 65358, 65359, 65360, + 65361, 65362, 65363, 65364, 65365, 65366, 65367, 65368, 65369, 65370); + $this->assertEquals($expected, $result); + + $string = '。「」、・ヲァィゥェォャュョッーアイウエオカキク'; + $result = Multibyte::utf8($string); + $expected = array(65377, 65378, 65379, 65380, 65381, 65382, 65383, 65384, 65385, 65386, 65387, 65388, 65389, 65390, 65391, 65392, + 65393, 65394, 65395, 65396, 65397, 65398, 65399, 65400); + $this->assertEquals($expected, $result); + + $string = 'ケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン゙'; + $result = Multibyte::utf8($string); + $expected = array(65401, 65402, 65403, 65404, 65405, 65406, 65407, 65408, 65409, 65410, 65411, 65412, 65413, 65414, 65415, 65416, + 65417, 65418, 65419, 65420, 65421, 65422, 65423, 65424, 65425, 65426, 65427, 65428, 65429, 65430, 65431, 65432, + 65433, 65434, 65435, 65436, 65437, 65438); + $this->assertEquals($expected, $result); + + $string = 'Ĥēĺļŏ, Ŵőřļď!'; + $result = Multibyte::utf8($string); + $expected = array(292, 275, 314, 316, 335, 44, 32, 372, 337, 345, 316, 271, 33); + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $result = Multibyte::utf8($string); + $expected = array(72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33); + $this->assertEquals($expected, $result); + + $string = '¨'; + $result = Multibyte::utf8($string); + $expected = array(168); + $this->assertEquals($expected, $result); + + $string = '¿'; + $result = Multibyte::utf8($string); + $expected = array(191); + $this->assertEquals($expected, $result); + + $string = 'čini'; + $result = Multibyte::utf8($string); + $expected = array(269, 105, 110, 105); + $this->assertEquals($expected, $result); + + $string = 'moći'; + $result = Multibyte::utf8($string); + $expected = array(109, 111, 263, 105); + $this->assertEquals($expected, $result); + + $string = 'državni'; + $result = Multibyte::utf8($string); + $expected = array(100, 114, 382, 97, 118, 110, 105); + $this->assertEquals($expected, $result); + + $string = '把百度设为首页'; + $result = Multibyte::utf8($string); + $expected = array(25226, 30334, 24230, 35774, 20026, 39318, 39029); + $this->assertEquals($expected, $result); + + $string = '一二三周永龍'; + $result = Multibyte::utf8($string); + $expected = array(19968, 20108, 19977, 21608, 27704, 40845); + $this->assertEquals($expected, $result); + + $string = 'ԀԂԄԆԈԊԌԎԐԒ'; + $result = Multibyte::utf8($string); + $expected = array(1280, 1282, 1284, 1286, 1288, 1290, 1292, 1294, 1296, 1298); + $this->assertEquals($expected, $result); + + $string = 'ԁԃԅԇԉԋԍԏԐԒ'; + $result = Multibyte::utf8($string); + $expected = array(1281, 1283, 1285, 1287, 1289, 1291, 1293, 1295, 1296, 1298); + $this->assertEquals($expected, $result); + + $string = 'ԱԲԳԴԵԶԷԸԹԺԻԼԽԾԿՀՁՂՃՄՅՆՇՈՉՊՋՌՍՎՏՐՑՒՓՔՕՖև'; + $result = Multibyte::utf8($string); + $expected = array(1329, 1330, 1331, 1332, 1333, 1334, 1335, 1336, 1337, 1338, 1339, 1340, 1341, 1342, 1343, 1344, 1345, 1346, + 1347, 1348, 1349, 1350, 1351, 1352, 1353, 1354, 1355, 1356, 1357, 1358, 1359, 1360, 1361, 1362, 1363, 1364, + 1365, 1366, 1415); + $this->assertEquals($expected, $result); + + $string = 'աբգդեզէըթժիլխծկհձղճմյնշոչպջռսվտրցւփքօֆև'; + $result = Multibyte::utf8($string); + $expected = array(1377, 1378, 1379, 1380, 1381, 1382, 1383, 1384, 1385, 1386, 1387, 1388, 1389, 1390, 1391, 1392, 1393, 1394, + 1395, 1396, 1397, 1398, 1399, 1400, 1401, 1402, 1403, 1404, 1405, 1406, 1407, 1408, 1409, 1410, 1411, 1412, + 1413, 1414, 1415); + $this->assertEquals($expected, $result); + + $string = 'ႠႡႢႣႤႥႦႧႨႩႪႫႬႭႮႯႰႱႲႳႴႵႶႷႸႹႺႻႼႽႾႿჀჁჂჃჄჅ'; + $result = Multibyte::utf8($string); + $expected = array(4256, 4257, 4258, 4259, 4260, 4261, 4262, 4263, 4264, 4265, 4266, 4267, 4268, 4269, 4270, 4271, 4272, 4273, + 4274, 4275, 4276, 4277, 4278, 4279, 4280, 4281, 4282, 4283, 4284, 4285, 4286, 4287, 4288, 4289, 4290, 4291, + 4292, 4293); + $this->assertEquals($expected, $result); + + $string = 'ḀḂḄḆḈḊḌḎḐḒḔḖḘḚḜḞḠḢḤḦḨḪḬḮḰḲḴḶḸḺḼḾṀṂṄṆṈṊṌṎṐṒṔṖṘṚṜṞṠṢṤṦṨṪṬṮṰṲṴṶṸṺṼṾẀẂẄẆẈẊẌẎẐẒẔẖẗẘẙẚẠẢẤẦẨẪẬẮẰẲẴẶẸẺẼẾỀỂỄỆỈỊỌỎỐỒỔỖỘỚỜỞỠỢỤỦỨỪỬỮỰỲỴỶỸ'; + $result = Multibyte::utf8($string); + $expected = array(7680, 7682, 7684, 7686, 7688, 7690, 7692, 7694, 7696, 7698, 7700, 7702, 7704, 7706, 7708, 7710, 7712, 7714, + 7716, 7718, 7720, 7722, 7724, 7726, 7728, 7730, 7732, 7734, 7736, 7738, 7740, 7742, 7744, 7746, 7748, 7750, + 7752, 7754, 7756, 7758, 7760, 7762, 7764, 7766, 7768, 7770, 7772, 7774, 7776, 7778, 7780, 7782, 7784, 7786, + 7788, 7790, 7792, 7794, 7796, 7798, 7800, 7802, 7804, 7806, 7808, 7810, 7812, 7814, 7816, 7818, 7820, 7822, + 7824, 7826, 7828, 7830, 7831, 7832, 7833, 7834, 7840, 7842, 7844, 7846, 7848, 7850, 7852, 7854, 7856, + 7858, 7860, 7862, 7864, 7866, 7868, 7870, 7872, 7874, 7876, 7878, 7880, 7882, 7884, 7886, 7888, 7890, 7892, + 7894, 7896, 7898, 7900, 7902, 7904, 7906, 7908, 7910, 7912, 7914, 7916, 7918, 7920, 7922, 7924, 7926, 7928); + $this->assertEquals($expected, $result); + + $string = 'ḁḃḅḇḉḋḍḏḑḓḕḗḙḛḝḟḡḣḥḧḩḫḭḯḱḳḵḷḹḻḽḿṁṃṅṇṉṋṍṏṑṓṕṗṙṛṝṟṡṣṥṧṩṫṭṯṱṳṵṷṹṻṽṿẁẃẅẇẉẋẍẏẑẓẕẖẗẘẙẚạảấầẩẫậắằẳẵặẹẻẽếềểễệỉịọỏốồổỗộớờởỡợụủứừửữựỳỵỷỹ'; + $result = Multibyte::utf8($string); + $expected = array(7681, 7683, 7685, 7687, 7689, 7691, 7693, 7695, 7697, 7699, 7701, 7703, 7705, 7707, 7709, 7711, 7713, 7715, + 7717, 7719, 7721, 7723, 7725, 7727, 7729, 7731, 7733, 7735, 7737, 7739, 7741, 7743, 7745, 7747, 7749, 7751, + 7753, 7755, 7757, 7759, 7761, 7763, 7765, 7767, 7769, 7771, 7773, 7775, 7777, 7779, 7781, 7783, 7785, 7787, + 7789, 7791, 7793, 7795, 7797, 7799, 7801, 7803, 7805, 7807, 7809, 7811, 7813, 7815, 7817, 7819, 7821, 7823, + 7825, 7827, 7829, 7830, 7831, 7832, 7833, 7834, 7841, 7843, 7845, 7847, 7849, 7851, 7853, 7855, 7857, 7859, + 7861, 7863, 7865, 7867, 7869, 7871, 7873, 7875, 7877, 7879, 7881, 7883, 7885, 7887, 7889, 7891, 7893, 7895, + 7897, 7899, 7901, 7903, 7905, 7907, 7909, 7911, 7913, 7915, 7917, 7919, 7921, 7923, 7925, 7927, 7929); + $this->assertEquals($expected, $result); + + $string = 'ΩKÅℲ'; + $result = Multibyte::utf8($string); + $expected = array(8486, 8490, 8491, 8498); + $this->assertEquals($expected, $result); + + $string = 'ωkåⅎ'; + $result = Multibyte::utf8($string); + $expected = array(969, 107, 229, 8526); + $this->assertEquals($expected, $result); + + $string = 'ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪⅫⅬⅭⅮⅯↃ'; + $result = Multibyte::utf8($string); + $expected = array(8544, 8545, 8546, 8547, 8548, 8549, 8550, 8551, 8552, 8553, 8554, 8555, 8556, 8557, 8558, 8559, 8579); + $this->assertEquals($expected, $result); + + $string = 'ⅰⅱⅲⅳⅴⅵⅶⅷⅸⅹⅺⅻⅼⅽⅾⅿↄ'; + $result = Multibyte::utf8($string); + $expected = array(8560, 8561, 8562, 8563, 8564, 8565, 8566, 8567, 8568, 8569, 8570, 8571, 8572, 8573, 8574, 8575, 8580); + $this->assertEquals($expected, $result); + + $string = 'ⒶⒷⒸⒹⒺⒻⒼⒽⒾⒿⓀⓁⓂⓃⓄⓅⓆⓇⓈⓉⓊⓋⓌⓍⓎⓏ'; + $result = Multibyte::utf8($string); + $expected = array(9398, 9399, 9400, 9401, 9402, 9403, 9404, 9405, 9406, 9407, 9408, 9409, 9410, 9411, 9412, 9413, 9414, + 9415, 9416, 9417, 9418, 9419, 9420, 9421, 9422, 9423); + $this->assertEquals($expected, $result); + + $string = 'ⓐⓑⓒⓓⓔⓕⓖⓗⓘⓙⓚⓛⓜⓝⓞⓟⓠⓡⓢⓣⓤⓥⓦⓧⓨⓩ'; + $result = Multibyte::utf8($string); + $expected = array(9424, 9425, 9426, 9427, 9428, 9429, 9430, 9431, 9432, 9433, 9434, 9435, 9436, 9437, 9438, 9439, 9440, 9441, + 9442, 9443, 9444, 9445, 9446, 9447, 9448, 9449); + $this->assertEquals($expected, $result); + + $string = 'ⰀⰁⰂⰃⰄⰅⰆⰇⰈⰉⰊⰋⰌⰍⰎⰏⰐⰑⰒⰓⰔⰕⰖⰗⰘⰙⰚⰛⰜⰝⰞⰟⰠⰡⰢⰣⰤⰥⰦⰧⰨⰩⰪⰫⰬⰭⰮ'; + $result = Multibyte::utf8($string); + $expected = array(11264, 11265, 11266, 11267, 11268, 11269, 11270, 11271, 11272, 11273, 11274, 11275, 11276, 11277, 11278, + 11279, 11280, 11281, 11282, 11283, 11284, 11285, 11286, 11287, 11288, 11289, 11290, 11291, 11292, 11293, + 11294, 11295, 11296, 11297, 11298, 11299, 11300, 11301, 11302, 11303, 11304, 11305, 11306, 11307, 11308, + 11309, 11310); + $this->assertEquals($expected, $result); + + $string = 'ⰰⰱⰲⰳⰴⰵⰶⰷⰸⰹⰺⰻⰼⰽⰾⰿⱀⱁⱂⱃⱄⱅⱆⱇⱈⱉⱊⱋⱌⱍⱎⱏⱐⱑⱒⱓⱔⱕⱖⱗⱘⱙⱚⱛⱜⱝⱞ'; + $result = Multibyte::utf8($string); + $expected = array(11312, 11313, 11314, 11315, 11316, 11317, 11318, 11319, 11320, 11321, 11322, 11323, 11324, 11325, 11326, 11327, + 11328, 11329, 11330, 11331, 11332, 11333, 11334, 11335, 11336, 11337, 11338, 11339, 11340, 11341, 11342, 11343, + 11344, 11345, 11346, 11347, 11348, 11349, 11350, 11351, 11352, 11353, 11354, 11355, 11356, 11357, 11358); + $this->assertEquals($expected, $result); + + $string = 'ⲀⲂⲄⲆⲈⲊⲌⲎⲐⲒⲔⲖⲘⲚⲜⲞⲠⲢⲤⲦⲨⲪⲬⲮⲰⲲⲴⲶⲸⲺⲼⲾⳀⳂⳄⳆⳈⳊⳌⳎⳐⳒⳔⳖⳘⳚⳜⳞⳠⳢ'; + $result = Multibyte::utf8($string); + $expected = array(11392, 11394, 11396, 11398, 11400, 11402, 11404, 11406, 11408, 11410, 11412, 11414, 11416, 11418, 11420, + 11422, 11424, 11426, 11428, 11430, 11432, 11434, 11436, 11438, 11440, 11442, 11444, 11446, 11448, 11450, + 11452, 11454, 11456, 11458, 11460, 11462, 11464, 11466, 11468, 11470, 11472, 11474, 11476, 11478, 11480, + 11482, 11484, 11486, 11488, 11490); + $this->assertEquals($expected, $result); + + $string = 'ⲁⲃⲅⲇⲉⲋⲍⲏⲑⲓⲕⲗⲙⲛⲝⲟⲡⲣⲥⲧⲩⲫⲭⲯⲱⲳⲵⲷⲹⲻⲽⲿⳁⳃⳅⳇⳉⳋⳍⳏⳑⳓⳕⳗⳙⳛⳝⳟⳡⳣ'; + $result = Multibyte::utf8($string); + $expected = array(11393, 11395, 11397, 11399, 11401, 11403, 11405, 11407, 11409, 11411, 11413, 11415, 11417, 11419, 11421, 11423, + 11425, 11427, 11429, 11431, 11433, 11435, 11437, 11439, 11441, 11443, 11445, 11447, 11449, 11451, 11453, 11455, + 11457, 11459, 11461, 11463, 11465, 11467, 11469, 11471, 11473, 11475, 11477, 11479, 11481, 11483, 11485, 11487, + 11489, 11491); + $this->assertEquals($expected, $result); + + $string = 'fffiflffifflſtstﬓﬔﬕﬖﬗ'; + $result = Multibyte::utf8($string); + $expected = array(64256, 64257, 64258, 64259, 64260, 64261, 64262, 64275, 64276, 64277, 64278, 64279); + $this->assertEquals($expected, $result); + } + +/** + * testAscii method + * + * @return void + */ + public function testAscii() { + $input = array(33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, + 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, + 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, + 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126); + $result = Multibyte::ascii($input); + + $expected = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'; + $this->assertEquals($expected, $result); + + $input = array(161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, + 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200); + $result = Multibyte::ascii($input); + + $expected = '¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈ'; + $this->assertEquals($expected, $result); + + $input = array(201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, + 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, + 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, + 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, + 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300); + $result = Multibyte::ascii($input); + $expected = 'ÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬ'; + $this->assertEquals($expected, $result); + + $input = array(301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, + 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, + 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, + 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, + 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400); + $expected = 'ĭĮįİıIJijĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏƐ'; + $result = Multibyte::ascii($input); + $this->assertEquals($expected, $result); + + $input = array(401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 420, 421, + 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 442, + 443, 444, 445, 446, 447, 448, 449, 450, 451, 452, 453, 454, 455, 456, 457, 458, 459, 460, 461, 462, 463, + 464, 465, 466, 467, 468, 469, 470, 471, 472, 473, 474, 475, 476, 477, 478, 479, 480, 481, 482, 483, 484, + 485, 486, 487, 488, 489, 490, 491, 492, 493, 494, 495, 496, 497, 498, 499, 500); + $expected = 'ƑƒƓƔƕƖƗƘƙƚƛƜƝƞƟƠơƢƣƤƥƦƧƨƩƪƫƬƭƮƯưƱƲƳƴƵƶƷƸƹƺƻƼƽƾƿǀǁǂǃDŽDždžLJLjljNJNjnjǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰDZDzdzǴ'; + $result = Multibyte::ascii($input); + $this->assertEquals($expected, $result); + + $input = array(601, 602, 603, 604, 605, 606, 607, 608, 609, 610, 611, 612, 613, 614, 615, 616, 617, 618, 619, 620, 621, + 622, 623, 624, 625, 626, 627, 628, 629, 630, 631, 632, 633, 634, 635, 636, 637, 638, 639, 640, 641, 642, + 643, 644, 645, 646, 647, 648, 649, 650, 651, 652, 653, 654, 655, 656, 657, 658, 659, 660, 661, 662, 663, + 664, 665, 666, 667, 668, 669, 670, 671, 672, 673, 674, 675, 676, 677, 678, 679, 680, 681, 682, 683, 684, + 685, 686, 687, 688, 689, 690, 691, 692, 693, 694, 695, 696, 697, 698, 699, 700); + $expected = 'əɚɛɜɝɞɟɠɡɢɣɤɥɦɧɨɩɪɫɬɭɮɯɰɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿʀʁʂʃʄʅʆʇʈʉʊʋʌʍʎʏʐʑʒʓʔʕʖʗʘʙʚʛʜʝʞʟʠʡʢʣʤʥʦʧʨʩʪʫʬʭʮʯʰʱʲʳʴʵʶʷʸʹʺʻʼ'; + $result = Multibyte::ascii($input); + $this->assertEquals($expected, $result); + + $input = array(1024, 1025, 1026, 1027, 1028, 1029, 1030, 1031, 1032, 1033, 1034, 1035, 1036, 1037, 1038, 1039, 1040, 1041, + 1042, 1043, 1044, 1045, 1046, 1047, 1048, 1049, 1050, 1051); + $expected = 'ЀЁЂЃЄЅІЇЈЉЊЋЌЍЎЏАБВГДЕЖЗИЙКЛ'; + $result = Multibyte::ascii($input); + $this->assertEquals($expected, $result); + + $input = array(1052, 1053, 1054, 1055, 1056, 1057, 1058, 1059, 1060, 1061, 1062, 1063, 1064, 1065, 1066, 1067, 1068, 1069, + 1070, 1071, 1072, 1073, 1074, 1075, 1076, 1077, 1078, 1079, 1080, 1081, 1082, 1083, 1084, 1085, 1086, 1087, + 1088, 1089, 1090, 1091, 1092, 1093, 1094, 1095, 1096, 1097, 1098, 1099, 1100); + $expected = 'МНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыь'; + $result = Multibyte::ascii($input); + $this->assertEquals($expected, $result); + + $input = array(1401, 1402, 1403, 1404, 1405, 1406, 1407); + $expected = 'չպջռսվտ'; + $result = Multibyte::ascii($input); + $this->assertEquals($expected, $result); + + $input = array(1601, 1602, 1603, 1604, 1605, 1606, 1607, 1608, 1609, 1610, 1611, 1612, 1613, 1614, 1615); + $expected = 'فقكلمنهوىيًٌٍَُ'; + $result = Multibyte::ascii($input); + $this->assertEquals($expected, $result); + + $input = array(10032, 10033, 10034, 10035, 10036, 10037, 10038, 10039, 10040, 10041, 10042, 10043, 10044, + 10045, 10046, 10047, 10048, 10049, 10050, 10051, 10052, 10053, 10054, 10055, 10056, 10057, + 10058, 10059, 10060, 10061, 10062, 10063, 10064, 10065, 10066, 10067, 10068, 10069, 10070, + 10071, 10072, 10073, 10074, 10075, 10076, 10077, 10078); + $expected = '✰✱✲✳✴✵✶✷✸✹✺✻✼✽✾✿❀❁❂❃❄❅❆❇❈❉❊❋❌❍❎❏❐❑❒❓❔❕❖❗❘❙❚❛❜❝❞'; + $result = Multibyte::ascii($input); + $this->assertEquals($expected, $result); + + $input = array(11904, 11905, 11906, 11907, 11908, 11909, 11910, 11911, 11912, 11913, 11914, 11915, 11916, 11917, 11918, 11919, + 11920, 11921, 11922, 11923, 11924, 11925, 11926, 11927, 11928, 11929, 11931, 11932, 11933, 11934, 11935, 11936, + 11937, 11938, 11939, 11940, 11941, 11942, 11943, 11944, 11945, 11946, 11947, 11948, 11949, 11950, 11951, 11952, + 11953, 11954, 11955, 11956, 11957, 11958, 11959, 11960, 11961, 11962, 11963, 11964, 11965, 11966, 11967, 11968, + 11969, 11970, 11971, 11972, 11973, 11974, 11975, 11976, 11977, 11978, 11979, 11980, 11981, 11982, 11983, 11984, + 11985, 11986, 11987, 11988, 11989, 11990, 11991, 11992, 11993, 11994, 11995, 11996, 11997, 11998, 11999, 12000); + $expected = '⺀⺁⺂⺃⺄⺅⺆⺇⺈⺉⺊⺋⺌⺍⺎⺏⺐⺑⺒⺓⺔⺕⺖⺗⺘⺙⺛⺜⺝⺞⺟⺠⺡⺢⺣⺤⺥⺦⺧⺨⺩⺪⺫⺬⺭⺮⺯⺰⺱⺲⺳⺴⺵⺶⺷⺸⺹⺺⺻⺼⺽⺾⺿⻀⻁⻂⻃⻄⻅⻆⻇⻈⻉⻊⻋⻌⻍⻎⻏⻐⻑⻒⻓⻔⻕⻖⻗⻘⻙⻚⻛⻜⻝⻞⻟⻠'; + $result = Multibyte::ascii($input); + $this->assertEquals($expected, $result); + + $input = array(12101, 12102, 12103, 12104, 12105, 12106, 12107, 12108, 12109, 12110, 12111, 12112, 12113, 12114, 12115, 12116, + 12117, 12118, 12119, 12120, 12121, 12122, 12123, 12124, 12125, 12126, 12127, 12128, 12129, 12130, 12131, 12132, + 12133, 12134, 12135, 12136, 12137, 12138, 12139, 12140, 12141, 12142, 12143, 12144, 12145, 12146, 12147, 12148, + 12149, 12150, 12151, 12152, 12153, 12154, 12155, 12156, 12157, 12158, 12159); + $expected = '⽅⽆⽇⽈⽉⽊⽋⽌⽍⽎⽏⽐⽑⽒⽓⽔⽕⽖⽗⽘⽙⽚⽛⽜⽝⽞⽟⽠⽡⽢⽣⽤⽥⽦⽧⽨⽩⽪⽫⽬⽭⽮⽯⽰⽱⽲⽳⽴⽵⽶⽷⽸⽹⽺⽻⽼⽽⽾⽿'; + $result = Multibyte::ascii($input); + $this->assertEquals($expected, $result); + + $input = array(45601, 45602, 45603, 45604, 45605, 45606, 45607, 45608, 45609, 45610, 45611, 45612, 45613, 45614, 45615, 45616, + 45617, 45618, 45619, 45620, 45621, 45622, 45623, 45624, 45625, 45626, 45627, 45628, 45629, 45630, 45631, 45632, + 45633, 45634, 45635, 45636, 45637, 45638, 45639, 45640, 45641, 45642, 45643, 45644, 45645, 45646, 45647, 45648, + 45649, 45650, 45651, 45652, 45653, 45654, 45655, 45656, 45657, 45658, 45659, 45660, 45661, 45662, 45663, 45664, + 45665, 45666, 45667, 45668, 45669, 45670, 45671, 45672, 45673, 45674, 45675, 45676, 45677, 45678, 45679, 45680, + 45681, 45682, 45683, 45684, 45685, 45686, 45687, 45688, 45689, 45690, 45691, 45692, 45693, 45694, 45695, 45696, + 45697, 45698, 45699, 45700); + $expected = '눡눢눣눤눥눦눧눨눩눪눫눬눭눮눯눰눱눲눳눴눵눶눷눸눹눺눻눼눽눾눿뉀뉁뉂뉃뉄뉅뉆뉇뉈뉉뉊뉋뉌뉍뉎뉏뉐뉑뉒뉓뉔뉕뉖뉗뉘뉙뉚뉛뉜뉝뉞뉟뉠뉡뉢뉣뉤뉥뉦뉧뉨뉩뉪뉫뉬뉭뉮뉯뉰뉱뉲뉳뉴뉵뉶뉷뉸뉹뉺뉻뉼뉽뉾뉿늀늁늂늃늄'; + $result = Multibyte::ascii($input); + $this->assertEquals($expected, $result); + + $input = array(65136, 65137, 65138, 65139, 65140, 65141, 65142, 65143, 65144, 65145, 65146, 65147, 65148, 65149, 65150, 65151, + 65152, 65153, 65154, 65155, 65156, 65157, 65158, 65159, 65160, 65161, 65162, 65163, 65164, 65165, 65166, 65167, + 65168, 65169, 65170, 65171, 65172, 65173, 65174, 65175, 65176, 65177, 65178, 65179, 65180, 65181, 65182, 65183, + 65184, 65185, 65186, 65187, 65188, 65189, 65190, 65191, 65192, 65193, 65194, 65195, 65196, 65197, 65198, 65199, + 65200); + $expected = 'ﹰﹱﹲﹳﹴ﹵ﹶﹷﹸﹹﹺﹻﹼﹽﹾﹿﺀﺁﺂﺃﺄﺅﺆﺇﺈﺉﺊﺋﺌﺍﺎﺏﺐﺑﺒﺓﺔﺕﺖﺗﺘﺙﺚﺛﺜﺝﺞﺟﺠﺡﺢﺣﺤﺥﺦﺧﺨﺩﺪﺫﺬﺭﺮﺯﺰ'; + $result = Multibyte::ascii($input); + $this->assertEquals($expected, $result); + + $input = array(65201, 65202, 65203, 65204, 65205, 65206, 65207, 65208, 65209, 65210, 65211, 65212, 65213, 65214, 65215, 65216, + 65217, 65218, 65219, 65220, 65221, 65222, 65223, 65224, 65225, 65226, 65227, 65228, 65229, 65230, 65231, 65232, + 65233, 65234, 65235, 65236, 65237, 65238, 65239, 65240, 65241, 65242, 65243, 65244, 65245, 65246, 65247, 65248, + 65249, 65250, 65251, 65252, 65253, 65254, 65255, 65256, 65257, 65258, 65259, 65260, 65261, 65262, 65263, 65264, + 65265, 65266, 65267, 65268, 65269, 65270, 65271, 65272, 65273, 65274, 65275, 65276); + $expected = 'ﺱﺲﺳﺴﺵﺶﺷﺸﺹﺺﺻﺼﺽﺾﺿﻀﻁﻂﻃﻄﻅﻆﻇﻈﻉﻊﻋﻌﻍﻎﻏﻐﻑﻒﻓﻔﻕﻖﻗﻘﻙﻚﻛﻜﻝﻞﻟﻠﻡﻢﻣﻤﻥﻦﻧﻨﻩﻪﻫﻬﻭﻮﻯﻰﻱﻲﻳﻴﻵﻶﻷﻸﻹﻺﻻﻼ'; + $result = Multibyte::ascii($input); + $this->assertEquals($expected, $result); + + $input = array(65345, 65346, 65347, 65348, 65349, 65350, 65351, 65352, 65353, 65354, 65355, 65356, 65357, 65358, 65359, 65360, + 65361, 65362, 65363, 65364, 65365, 65366, 65367, 65368, 65369, 65370); + $expected = 'abcdefghijklmnopqrstuvwxyz'; + $result = Multibyte::ascii($input); + $this->assertEquals($expected, $result); + + $input = array(65377, 65378, 65379, 65380, 65381, 65382, 65383, 65384, 65385, 65386, 65387, 65388, 65389, 65390, 65391, 65392, + 65393, 65394, 65395, 65396, 65397, 65398, 65399, 65400); + $expected = '。「」、・ヲァィゥェォャュョッーアイウエオカキク'; + $result = Multibyte::ascii($input); + $this->assertEquals($expected, $result); + + $input = array(65401, 65402, 65403, 65404, 65405, 65406, 65407, 65408, 65409, 65410, 65411, 65412, 65413, 65414, 65415, 65416, + 65417, 65418, 65419, 65420, 65421, 65422, 65423, 65424, 65425, 65426, 65427, 65428, 65429, 65430, 65431, 65432, + 65433, 65434, 65435, 65436, 65437, 65438); + $expected = 'ケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン゙'; + $result = Multibyte::ascii($input); + $this->assertEquals($expected, $result); + + $input = array(292, 275, 314, 316, 335, 44, 32, 372, 337, 345, 316, 271, 33); + $expected = 'Ĥēĺļŏ, Ŵőřļď!'; + $result = Multibyte::ascii($input); + $this->assertEquals($expected, $result); + + $input = array(72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33); + $expected = 'Hello, World!'; + $result = Multibyte::ascii($input); + $this->assertEquals($expected, $result); + + $input = array(168); + $expected = '¨'; + $result = Multibyte::ascii($input); + $this->assertEquals($expected, $result); + + $input = array(191); + $expected = '¿'; + $result = Multibyte::ascii($input); + $this->assertEquals($expected, $result); + + $input = array(269, 105, 110, 105); + $expected = 'čini'; + $result = Multibyte::ascii($input); + $this->assertEquals($expected, $result); + + $input = array(109, 111, 263, 105); + $expected = 'moći'; + $result = Multibyte::ascii($input); + $this->assertEquals($expected, $result); + + $input = array(100, 114, 382, 97, 118, 110, 105); + $expected = 'državni'; + $result = Multibyte::ascii($input); + $this->assertEquals($expected, $result); + + $input = array(25226, 30334, 24230, 35774, 20026, 39318, 39029); + $expected = '把百度设为首页'; + $result = Multibyte::ascii($input); + $this->assertEquals($expected, $result); + + $input = array(19968, 20108, 19977, 21608, 27704, 40845); + $expected = '一二三周永龍'; + $result = Multibyte::ascii($input); + $this->assertEquals($expected, $result); + + $input = array(1280, 1282, 1284, 1286, 1288, 1290, 1292, 1294, 1296, 1298); + $expected = 'ԀԂԄԆԈԊԌԎԐԒ'; + $result = Multibyte::ascii($input); + $this->assertEquals($expected, $result); + + $input = array(1281, 1283, 1285, 1287, 1289, 1291, 1293, 1295, 1296, 1298); + $expected = 'ԁԃԅԇԉԋԍԏԐԒ'; + $result = Multibyte::ascii($input); + $this->assertEquals($expected, $result); + + $input = array(1329, 1330, 1331, 1332, 1333, 1334, 1335, 1336, 1337, 1338, 1339, 1340, 1341, 1342, 1343, 1344, 1345, 1346, 1347, + 1348, 1349, 1350, 1351, 1352, 1353, 1354, 1355, 1356, 1357, 1358, 1359, 1360, 1361, 1362, 1363, 1364, 1365, + 1366, 1415); + $result = Multibyte::ascii($input); + $expected = 'ԱԲԳԴԵԶԷԸԹԺԻԼԽԾԿՀՁՂՃՄՅՆՇՈՉՊՋՌՍՎՏՐՑՒՓՔՕՖև'; + $this->assertEquals($expected, $result); + + $input = array(1377, 1378, 1379, 1380, 1381, 1382, 1383, 1384, 1385, 1386, 1387, 1388, 1389, 1390, 1391, 1392, 1393, 1394, + 1395, 1396, 1397, 1398, 1399, 1400, 1401, 1402, 1403, 1404, 1405, 1406, 1407, 1408, 1409, 1410, 1411, 1412, + 1413, 1414, 1415); + $result = Multibyte::ascii($input); + $expected = 'աբգդեզէըթժիլխծկհձղճմյնշոչպջռսվտրցւփքօֆև'; + $this->assertEquals($expected, $result); + + $input = array(4256, 4257, 4258, 4259, 4260, 4261, 4262, 4263, 4264, 4265, 4266, 4267, 4268, 4269, 4270, 4271, 4272, 4273, 4274, + 4275, 4276, 4277, 4278, 4279, 4280, 4281, 4282, 4283, 4284, 4285, 4286, 4287, 4288, 4289, 4290, 4291, 4292, 4293); + $result = Multibyte::ascii($input); + $expected = 'ႠႡႢႣႤႥႦႧႨႩႪႫႬႭႮႯႰႱႲႳႴႵႶႷႸႹႺႻႼႽႾႿჀჁჂჃჄჅ'; + $this->assertEquals($expected, $result); + + $input = array(7680, 7682, 7684, 7686, 7688, 7690, 7692, 7694, 7696, 7698, 7700, 7702, 7704, 7706, 7708, 7710, 7712, 7714, + 7716, 7718, 7720, 7722, 7724, 7726, 7728, 7730, 7732, 7734, 7736, 7738, 7740, 7742, 7744, 7746, 7748, 7750, + 7752, 7754, 7756, 7758, 7760, 7762, 7764, 7766, 7768, 7770, 7772, 7774, 7776, 7778, 7780, 7782, 7784, 7786, + 7788, 7790, 7792, 7794, 7796, 7798, 7800, 7802, 7804, 7806, 7808, 7810, 7812, 7814, 7816, 7818, 7820, 7822, + 7824, 7826, 7828, 7830, 7831, 7832, 7833, 7834, 7840, 7842, 7844, 7846, 7848, 7850, 7852, 7854, 7856, + 7858, 7860, 7862, 7864, 7866, 7868, 7870, 7872, 7874, 7876, 7878, 7880, 7882, 7884, 7886, 7888, 7890, 7892, + 7894, 7896, 7898, 7900, 7902, 7904, 7906, 7908, 7910, 7912, 7914, 7916, 7918, 7920, 7922, 7924, 7926, 7928); + $result = Multibyte::ascii($input); + $expected = 'ḀḂḄḆḈḊḌḎḐḒḔḖḘḚḜḞḠḢḤḦḨḪḬḮḰḲḴḶḸḺḼḾṀṂṄṆṈṊṌṎṐṒṔṖṘṚṜṞṠṢṤṦṨṪṬṮṰṲṴṶṸṺṼṾẀẂẄẆẈẊẌẎẐẒẔẖẗẘẙẚẠẢẤẦẨẪẬẮẰẲẴẶẸẺẼẾỀỂỄỆỈỊỌỎỐỒỔỖỘỚỜỞỠỢỤỦỨỪỬỮỰỲỴỶỸ'; + $this->assertEquals($expected, $result); + + $input = array(7681, 7683, 7685, 7687, 7689, 7691, 7693, 7695, 7697, 7699, 7701, 7703, 7705, 7707, 7709, 7711, 7713, 7715, + 7717, 7719, 7721, 7723, 7725, 7727, 7729, 7731, 7733, 7735, 7737, 7739, 7741, 7743, 7745, 7747, 7749, 7751, + 7753, 7755, 7757, 7759, 7761, 7763, 7765, 7767, 7769, 7771, 7773, 7775, 7777, 7779, 7781, 7783, 7785, 7787, + 7789, 7791, 7793, 7795, 7797, 7799, 7801, 7803, 7805, 7807, 7809, 7811, 7813, 7815, 7817, 7819, 7821, 7823, + 7825, 7827, 7829, 7830, 7831, 7832, 7833, 7834, 7841, 7843, 7845, 7847, 7849, 7851, 7853, 7855, 7857, 7859, + 7861, 7863, 7865, 7867, 7869, 7871, 7873, 7875, 7877, 7879, 7881, 7883, 7885, 7887, 7889, 7891, 7893, 7895, + 7897, 7899, 7901, 7903, 7905, 7907, 7909, 7911, 7913, 7915, 7917, 7919, 7921, 7923, 7925, 7927, 7929); + $result = Multibyte::ascii($input); + $expected = 'ḁḃḅḇḉḋḍḏḑḓḕḗḙḛḝḟḡḣḥḧḩḫḭḯḱḳḵḷḹḻḽḿṁṃṅṇṉṋṍṏṑṓṕṗṙṛṝṟṡṣṥṧṩṫṭṯṱṳṵṷṹṻṽṿẁẃẅẇẉẋẍẏẑẓẕẖẗẘẙẚạảấầẩẫậắằẳẵặẹẻẽếềểễệỉịọỏốồổỗộớờởỡợụủứừửữựỳỵỷỹ'; + $this->assertEquals($expected, $result); + + $input = array(8486, 8490, 8491, 8498); + $result = Multibyte::ascii($input); + $expected = 'ΩKÅℲ'; + $this->assertEquals($expected, $result); + + $input = array(969, 107, 229, 8526); + $result = Multibyte::ascii($input); + $expected = 'ωkåⅎ'; + $this->assertEquals($expected, $result); + + $input = array(8544, 8545, 8546, 8547, 8548, 8549, 8550, 8551, 8552, 8553, 8554, 8555, 8556, 8557, 8558, 8559, 8579); + $result = Multibyte::ascii($input); + $expected = 'ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪⅫⅬⅭⅮⅯↃ'; + $this->assertEquals($expected, $result); + + $input = array(8560, 8561, 8562, 8563, 8564, 8565, 8566, 8567, 8568, 8569, 8570, 8571, 8572, 8573, 8574, 8575, 8580); + $result = Multibyte::ascii($input); + $expected = 'ⅰⅱⅲⅳⅴⅵⅶⅷⅸⅹⅺⅻⅼⅽⅾⅿↄ'; + $this->assertEquals($expected, $result); + + $input = array(9398, 9399, 9400, 9401, 9402, 9403, 9404, 9405, 9406, 9407, 9408, 9409, 9410, 9411, 9412, 9413, 9414, + 9415, 9416, 9417, 9418, 9419, 9420, 9421, 9422, 9423); + $result = Multibyte::ascii($input); + $expected = 'ⒶⒷⒸⒹⒺⒻⒼⒽⒾⒿⓀⓁⓂⓃⓄⓅⓆⓇⓈⓉⓊⓋⓌⓍⓎⓏ'; + $this->assertEquals($expected, $result); + + $input = array(9424, 9425, 9426, 9427, 9428, 9429, 9430, 9431, 9432, 9433, 9434, 9435, 9436, 9437, 9438, 9439, 9440, 9441, + 9442, 9443, 9444, 9445, 9446, 9447, 9448, 9449); + $result = Multibyte::ascii($input); + $expected = 'ⓐⓑⓒⓓⓔⓕⓖⓗⓘⓙⓚⓛⓜⓝⓞⓟⓠⓡⓢⓣⓤⓥⓦⓧⓨⓩ'; + $this->assertEquals($expected, $result); + + $input = array(11264, 11265, 11266, 11267, 11268, 11269, 11270, 11271, 11272, 11273, 11274, 11275, 11276, 11277, 11278, 11279, + 11280, 11281, 11282, 11283, 11284, 11285, 11286, 11287, 11288, 11289, 11290, 11291, 11292, 11293, 11294, 11295, + 11296, 11297, 11298, 11299, 11300, 11301, 11302, 11303, 11304, 11305, 11306, 11307, 11308, 11309, 11310); + $result = Multibyte::ascii($input); + $expected = 'ⰀⰁⰂⰃⰄⰅⰆⰇⰈⰉⰊⰋⰌⰍⰎⰏⰐⰑⰒⰓⰔⰕⰖⰗⰘⰙⰚⰛⰜⰝⰞⰟⰠⰡⰢⰣⰤⰥⰦⰧⰨⰩⰪⰫⰬⰭⰮ'; + $this->assertEquals($expected, $result); + + $input = array(11312, 11313, 11314, 11315, 11316, 11317, 11318, 11319, 11320, 11321, 11322, 11323, 11324, 11325, 11326, 11327, + 11328, 11329, 11330, 11331, 11332, 11333, 11334, 11335, 11336, 11337, 11338, 11339, 11340, 11341, 11342, 11343, + 11344, 11345, 11346, 11347, 11348, 11349, 11350, 11351, 11352, 11353, 11354, 11355, 11356, 11357, 11358); + $result = Multibyte::ascii($input); + $expected = 'ⰰⰱⰲⰳⰴⰵⰶⰷⰸⰹⰺⰻⰼⰽⰾⰿⱀⱁⱂⱃⱄⱅⱆⱇⱈⱉⱊⱋⱌⱍⱎⱏⱐⱑⱒⱓⱔⱕⱖⱗⱘⱙⱚⱛⱜⱝⱞ'; + $this->assertEquals($expected, $result); + + $input = array(11392, 11394, 11396, 11398, 11400, 11402, 11404, 11406, 11408, 11410, 11412, 11414, 11416, 11418, 11420, + 11422, 11424, 11426, 11428, 11430, 11432, 11434, 11436, 11438, 11440, 11442, 11444, 11446, 11448, 11450, + 11452, 11454, 11456, 11458, 11460, 11462, 11464, 11466, 11468, 11470, 11472, 11474, 11476, 11478, 11480, + 11482, 11484, 11486, 11488, 11490); + $result = Multibyte::ascii($input); + $expected = 'ⲀⲂⲄⲆⲈⲊⲌⲎⲐⲒⲔⲖⲘⲚⲜⲞⲠⲢⲤⲦⲨⲪⲬⲮⲰⲲⲴⲶⲸⲺⲼⲾⳀⳂⳄⳆⳈⳊⳌⳎⳐⳒⳔⳖⳘⳚⳜⳞⳠⳢ'; + $this->assertEquals($expected, $result); + + $input = array(11393, 11395, 11397, 11399, 11401, 11403, 11405, 11407, 11409, 11411, 11413, 11415, 11417, 11419, 11421, 11423, + 11425, 11427, 11429, 11431, 11433, 11435, 11437, 11439, 11441, 11443, 11445, 11447, 11449, 11451, 11453, 11455, + 11457, 11459, 11461, 11463, 11465, 11467, 11469, 11471, 11473, 11475, 11477, 11479, 11481, 11483, 11485, 11487, + 11489, 11491); + $result = Multibyte::ascii($input); + $expected = 'ⲁⲃⲅⲇⲉⲋⲍⲏⲑⲓⲕⲗⲙⲛⲝⲟⲡⲣⲥⲧⲩⲫⲭⲯⲱⲳⲵⲷⲹⲻⲽⲿⳁⳃⳅⳇⳉⳋⳍⳏⳑⳓⳕⳗⳙⳛⳝⳟⳡⳣ'; + $this->assertEquals($expected, $result); + + $input = array(64256, 64257, 64258, 64259, 64260, 64261, 64262, 64275, 64276, 64277, 64278, 64279); + $result = Multibyte::ascii($input); + $expected = 'fffiflffifflſtstﬓﬔﬕﬖﬗ'; + $this->assertEquals($expected, $result); + } + +/** + * testUsingMbStripos method + * + * @return void + */ + public function testUsingMbStripos() { + $string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; + $find = 'f'; + $result = mb_stripos($string, $find); + $expected = 5; + $this->assertEquals($expected, $result); + + $string = 'ABCDEFGHIJKLMNOPQFRSTUVWXYZ0123456789'; + $find = 'f'; + $result = mb_stripos($string, $find, 6); + $expected = 17; + $this->assertEquals($expected, $result); + + $string = 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ'; + $find = 'å'; + $result = mb_stripos($string, $find); + $expected = 5; + $this->assertEquals($expected, $result); + + $string = 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÅÙÚÛÜÝÞ'; + $find = 'å'; + $result = mb_stripos($string, $find, 6); + $expected = 24; + $this->assertEquals($expected, $result); + + $string = 'ĀĂĄĆĈĊČĎĐĒĔĖĘĚĜĞĠĢĤĦĨĪĬĮIJĴĶĹĻĽĿŁŃŅŇŊŌŎŐŒŔŖŘŚŜŞŠŢŤŦŨŪŬŮŰŲŴŶŹŻŽ'; + $find = 'ċ'; + $result = mb_stripos($string, $find); + $expected = 5; + $this->assertEquals($expected, $result); + + $string = 'ĀĂĄĆĈĊČĎĐĒĔĖĘĚĜĞĠĢĤĦĨĪĬĮIJĴĶĹĻĽĿŁĊŃŅŇŊŌŎŐŒŔŖŘŚŜŞŠŢŤŦŨŪŬŮŰŲŴŶŹŻŽ'; + $find = 'ċ'; + $result = mb_stripos($string, $find, 6); + $expected = 32; + $this->assertEquals($expected, $result); + + $string = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'; + $find = 'f'; + $result = mb_stripos($string, $find); + $expected = 37; + $this->assertEquals($expected, $result); + + $string = '¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈ'; + $find = 'Μ'; + $result = mb_stripos($string, $find); + $expected = 20; + $this->assertEquals($expected, $result); + + $string = 'ÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬ'; + $find = 'É'; + $result = mb_stripos($string, $find, 6); + $expected = 32; + $this->assertEquals($expected, $result); + + $string = 'ĭĮįİıIJijĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏƐ'; + $find = 'Ņ'; + $result = mb_stripos($string, $find); + $expected = 24; + $this->assertEquals($expected, $result); + + $string = 'ƑƒƓƔƕƖƗƘƙƚƛƜƝƞƟƠơƢƣƤƥƦƧƨƩƪƫƬƭƮƯưƱƲƳƴƵƶƷƸƹƺƻƼƽƾƿǀǁǂǃDŽDždžLJLjljNJNjnjǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰDZDzdzǴ'; + $find = 'Ƹ'; + $result = mb_stripos($string, $find); + $expected = 39; + $this->assertEquals($expected, $result); + + $string = 'ƑƒƓƔƕƖƗƘƙƚƛƜƝƞƟƠơƢƣƤƥƦƧƨƩƪƫƬƭƮƯưƱƲƳƴƵƶƷƸƹƺƻƼƽƾƿǀǁǂǃDŽDždžLJLjljNJNjnjǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰDZDzdzǴ'; + $find = 'Ƹ'; + $result = mb_stripos($string, $find, 40); + $expected = 40; + $this->assertEquals($expected, $result); + + $string = 'əɚɛɜɝɞɟɠɡɢɣɤɥɦɧɨɩɪɫɬɭɮɯɰɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿʀʁʂʃʄʅʆʇʈʉʊʋʌʍʎʏʐʑʒʓʔʕʖʗʘʙʚʛʜʝʞʟʠʡʢʣʤʥʦʧʨʩʪʫʬʭʮʯʰʱʲʳʴʵʶʷʸʹʺʻʼ'; + $find = 'Ʀ'; + $result = mb_stripos($string, $find); + $expected = 39; + $this->assertEquals($expected, $result); + + $string = 'ЀЁЂЃЄЅІЇЈЉЊЋЌЍЎЏАБВГДЕЖЗИЙКЛ'; + $find = 'ї'; + $result = mb_stripos($string, $find); + $expected = 7; + $this->assertEquals($expected, $result); + + $string = 'МНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыь'; + $find = 'Р'; + $result = mb_stripos($string, $find); + $expected = 4; + $this->assertEquals($expected, $result); + + $string = 'МНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыь'; + $find = 'Р'; + $result = mb_stripos($string, $find, 5); + $expected = 36; + $this->assertEquals($expected, $result); + + $string = 'فقكلمنهوىيًٌٍَُ'; + $find = 'ن'; + $result = mb_stripos($string, $find); + $expected = 5; + $this->assertEquals($expected, $result); + + $string = '✰✱✲✳✴✵✶✷✸✹✺✻✼✽✾✿❀❁❂❃❄❅❆❇❈❉❊❋❌❍❎❏❐❑❒❓❔❕❖❗❘❙❚❛❜❝❞'; + $find = '✿'; + $result = mb_stripos($string, $find); + $expected = 15; + $this->assertEquals($expected, $result); + + $string = '⺀⺁⺂⺃⺄⺅⺆⺇⺈⺉⺊⺋⺌⺍⺎⺏⺐⺑⺒⺓⺔⺕⺖⺗⺘⺙⺛⺜⺝⺞⺟⺠⺡⺢⺣⺤⺥⺦⺧⺨⺩⺪⺫⺬⺭⺮⺯⺰⺱⺲⺳⺴⺵⺶⺷⺸⺹⺺⺻⺼⺽⺾⺿⻀⻁⻂⻃⻄⻅⻆⻇⻈⻉⻊⻋⻌⻍⻎⻏⻐⻑⻒⻓⻔⻕⻖⻗⻘⻙⻚⻛⻜⻝⻞⻟⻠'; + $find = '⺐'; + $result = mb_stripos($string, $find); + $expected = 16; + $this->assertEquals($expected, $result); + + $string = '⽅⽆⽇⽈⽉⽊⽋⽌⽍⽎⽏⽐⽑⽒⽓⽔⽕⽖⽗⽘⽙⽚⽛⽜⽝⽞⽟⽠⽡⽢⽣⽤⽥⽦⽧⽨⽩⽪⽫⽬⽭⽮⽯⽰⽱⽲⽳⽴⽵⽶⽷⽸⽹⽺⽻⽼⽽⽾⽿'; + $find = '⽤'; + $result = mb_stripos($string, $find); + $expected = 31; + $this->assertEquals($expected, $result); + + $string = '눡눢눣눤눥눦눧눨눩눪눫눬눭눮눯눰눱눲눳눴눵눶눷눸눹눺눻눼눽눾눿뉀뉁뉂뉃뉄뉅뉆뉇뉈뉉뉊뉋뉌뉍뉎뉏뉐뉑뉒뉓뉔뉕뉖뉗뉘뉙뉚뉛뉜뉝뉞뉟뉠뉡뉢뉣뉤뉥뉦뉧뉨뉩뉪뉫뉬뉭뉮뉯뉰뉱뉲뉳뉴뉵뉶뉷뉸뉹뉺뉻뉼뉽뉾뉿늀늁늂늃늄'; + $find = '눻'; + $result = mb_stripos($string, $find); + $expected = 26; + $this->assertEquals($expected, $result); + + $string = 'ﹰﹱﹲﹳﹴ﹵ﹶﹷﹸﹹﹺﹻﹼﹽﹾﹿﺀﺁﺂﺃﺄﺅﺆﺇﺈﺉﺊﺋﺌﺍﺎﺏﺐﺑﺒﺓﺔﺕﺖﺗﺘﺙﺚﺛﺜﺝﺞﺟﺠﺡﺢﺣﺤﺥﺦﺧﺨﺩﺪﺫﺬﺭﺮﺯﺰ'; + $find = 'ﺞ'; + $result = mb_stripos($string, $find); + $expected = 46; + $this->assertEquals($expected, $result); + + $string = 'ﺱﺲﺳﺴﺵﺶﺷﺸﺹﺺﺻﺼﺽﺾﺿﻀﻁﻂﻃﻄﻅﻆﻇﻈﻉﻊﻋﻌﻍﻎﻏﻐﻑﻒﻓﻔﻕﻖﻗﻘﻙﻚﻛﻜﻝﻞﻟﻠﻡﻢﻣﻤﻥﻦﻧﻨﻩﻪﻫﻬﻭﻮﻯﻰﻱﻲﻳﻴﻵﻶﻷﻸﻹﻺﻻﻼ'; + $find = 'ﻞ'; + $result = mb_stripos($string, $find); + $expected = 45; + $this->assertEquals($expected, $result); + + $string = 'abcdefghijklmnopqrstuvwxyz'; + $find = 'k'; + $result = mb_stripos($string, $find); + $expected = 10; + $this->assertEquals($expected, $result); + + $string = 'abcdefghijklmnopqrstuvwxyz'; + $find = 'K'; + $result = mb_stripos($string, $find); + $expected = 10; + $this->assertEquals($expected, $result); + + $string = '。「」、・ヲァィゥェォャュョッーアイウエオカキク'; + $find = 'ア'; + $result = mb_stripos($string, $find); + $expected = 16; + $this->assertEquals($expected, $result); + + $string = 'ケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン゙'; + $find = 'ハ'; + $result = mb_stripos($string, $find); + $expected = 17; + $this->assertEquals($expected, $result); + + $string = 'Ĥēĺļŏ, Ŵőřļď!'; + $find = 'ő'; + $result = mb_stripos($string, $find); + $expected = 8; + $this->assertEquals($expected, $result); + + $string = 'Ĥēĺļŏ, Ŵőřļď!'; + $find = 'Ő'; + $result = mb_stripos($string, $find); + $expected = 8; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'O'; + $result = mb_stripos($string, $find); + $expected = 4; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'o'; + $result = mb_stripos($string, $find); + $expected = 4; + $this->assertEquals($expected, $result); + + $string = 'čini'; + $find = 'n'; + $result = mb_stripos($string, $find); + $expected = 2; + $this->assertEquals($expected, $result); + + $string = 'čini'; + $find = 'N'; + $result = mb_stripos($string, $find); + $expected = 2; + $this->assertEquals($expected, $result); + + $string = 'moći'; + $find = 'ć'; + $result = mb_stripos($string, $find); + $expected = 2; + $this->assertEquals($expected, $result); + + $string = 'moći'; + $find = 'Ć'; + $result = mb_stripos($string, $find); + $expected = 2; + $this->assertEquals($expected, $result); + + $string = 'državni'; + $find = 'ž'; + $result = mb_stripos($string, $find); + $expected = 2; + $this->assertEquals($expected, $result); + + $string = 'državni'; + $find = 'Ž'; + $result = mb_stripos($string, $find); + $expected = 2; + $this->assertEquals($expected, $result); + + $string = '把百度设为首页'; + $find = '设'; + $result = mb_stripos($string, $find); + $expected = 3; + $this->assertEquals($expected, $result); + + $string = '一二三周永龍'; + $find = '周'; + $result = mb_stripos($string, $find); + $expected = 3; + $this->assertEquals($expected, $result); + + $string = 'državni'; + $find = 'DŽ'; + $result = mb_stripos($string, $find); + $expected = false; + $this->assertEquals($expected, $result); + } + +/** + * testMultibyteStripos method + * + * @return void + */ + public function testMultibyteStripos() { + $string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; + $find = 'f'; + $result = Multibyte::stripos($string, $find); + $expected = 5; + $this->assertEquals($expected, $result); + + $string = 'ABCDEFGHIJKLMNOPQFRSTUVWXYZ0123456789'; + $find = 'f'; + $result = Multibyte::stripos($string, $find, 6); + $expected = 17; + $this->assertEquals($expected, $result); + + $string = 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ'; + $find = 'å'; + $result = Multibyte::stripos($string, $find); + $expected = 5; + $this->assertEquals($expected, $result); + + $string = 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÅÙÚÛÜÝÞ'; + $find = 'å'; + $result = Multibyte::stripos($string, $find, 6); + $expected = 24; + $this->assertEquals($expected, $result); + + $string = 'ĀĂĄĆĈĊČĎĐĒĔĖĘĚĜĞĠĢĤĦĨĪĬĮIJĴĶĹĻĽĿŁŃŅŇŊŌŎŐŒŔŖŘŚŜŞŠŢŤŦŨŪŬŮŰŲŴŶŹŻŽ'; + $find = 'ċ'; + $result = Multibyte::stripos($string, $find); + $expected = 5; + $this->assertEquals($expected, $result); + + $string = 'ĀĂĄĆĈĊČĎĐĒĔĖĘĚĜĞĠĢĤĦĨĪĬĮIJĴĶĹĻĽĿŁĊŃŅŇŊŌŎŐŒŔŖŘŚŜŞŠŢŤŦŨŪŬŮŰŲŴŶŹŻŽ'; + $find = 'ċ'; + $result = Multibyte::stripos($string, $find, 6); + $expected = 32; + $this->assertEquals($expected, $result); + + $string = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'; + $find = 'f'; + $result = Multibyte::stripos($string, $find); + $expected = 37; + $this->assertEquals($expected, $result); + + $string = '¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈ'; + $find = 'Μ'; + $result = Multibyte::stripos($string, $find); + $expected = 20; + $this->assertEquals($expected, $result); + + $string = 'ÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬ'; + $find = 'É'; + $result = Multibyte::stripos($string, $find, 6); + $expected = 32; + $this->assertEquals($expected, $result); + + $string = 'ĭĮįİıIJijĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏƐ'; + $find = 'Ņ'; + $result = Multibyte::stripos($string, $find); + $expected = 24; + $this->assertEquals($expected, $result); + + $string = 'ƑƒƓƔƕƖƗƘƙƚƛƜƝƞƟƠơƢƣƤƥƦƧƨƩƪƫƬƭƮƯưƱƲƳƴƵƶƷƸƹƺƻƼƽƾƿǀǁǂǃDŽDždžLJLjljNJNjnjǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰDZDzdzǴ'; + $find = 'Ƹ'; + $result = Multibyte::stripos($string, $find); + $expected = 39; + $this->assertEquals($expected, $result); + + $string = 'ƑƒƓƔƕƖƗƘƙƚƛƜƝƞƟƠơƢƣƤƥƦƧƨƩƪƫƬƭƮƯưƱƲƳƴƵƶƷƸƹƺƻƼƽƾƿǀǁǂǃDŽDždžLJLjljNJNjnjǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰDZDzdzǴ'; + $find = 'Ƹ'; + $result = Multibyte::stripos($string, $find, 40); + $expected = 40; + $this->assertEquals($expected, $result); + + $string = 'əɚɛɜɝɞɟɠɡɢɣɤɥɦɧɨɩɪɫɬɭɮɯɰɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿʀʁʂʃʄʅʆʇʈʉʊʋʌʍʎʏʐʑʒʓʔʕʖʗʘʙʚʛʜʝʞʟʠʡʢʣʤʥʦʧʨʩʪʫʬʭʮʯʰʱʲʳʴʵʶʷʸʹʺʻʼ'; + $find = 'Ʀ'; + $result = Multibyte::stripos($string, $find); + $expected = 39; + $this->assertEquals($expected, $result); + + $string = 'ЀЁЂЃЄЅІЇЈЉЊЋЌЍЎЏАБВГДЕЖЗИЙКЛ'; + $find = 'ї'; + $result = Multibyte::stripos($string, $find); + $expected = 7; + $this->assertEquals($expected, $result); + + $string = 'МНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыь'; + $find = 'Р'; + $result = Multibyte::stripos($string, $find); + $expected = 4; + $this->assertEquals($expected, $result); + + $string = 'МНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыь'; + $find = 'Р'; + $result = Multibyte::stripos($string, $find, 5); + $expected = 36; + $this->assertEquals($expected, $result); + + $string = 'فقكلمنهوىيًٌٍَُ'; + $find = 'ن'; + $result = Multibyte::stripos($string, $find); + $expected = 5; + $this->assertEquals($expected, $result); + + $string = '✰✱✲✳✴✵✶✷✸✹✺✻✼✽✾✿❀❁❂❃❄❅❆❇❈❉❊❋❌❍❎❏❐❑❒❓❔❕❖❗❘❙❚❛❜❝❞'; + $find = '✿'; + $result = Multibyte::stripos($string, $find); + $expected = 15; + $this->assertEquals($expected, $result); + + $string = '⺀⺁⺂⺃⺄⺅⺆⺇⺈⺉⺊⺋⺌⺍⺎⺏⺐⺑⺒⺓⺔⺕⺖⺗⺘⺙⺛⺜⺝⺞⺟⺠⺡⺢⺣⺤⺥⺦⺧⺨⺩⺪⺫⺬⺭⺮⺯⺰⺱⺲⺳⺴⺵⺶⺷⺸⺹⺺⺻⺼⺽⺾⺿⻀⻁⻂⻃⻄⻅⻆⻇⻈⻉⻊⻋⻌⻍⻎⻏⻐⻑⻒⻓⻔⻕⻖⻗⻘⻙⻚⻛⻜⻝⻞⻟⻠'; + $find = '⺐'; + $result = Multibyte::stripos($string, $find); + $expected = 16; + $this->assertEquals($expected, $result); + + $string = '⽅⽆⽇⽈⽉⽊⽋⽌⽍⽎⽏⽐⽑⽒⽓⽔⽕⽖⽗⽘⽙⽚⽛⽜⽝⽞⽟⽠⽡⽢⽣⽤⽥⽦⽧⽨⽩⽪⽫⽬⽭⽮⽯⽰⽱⽲⽳⽴⽵⽶⽷⽸⽹⽺⽻⽼⽽⽾⽿'; + $find = '⽤'; + $result = Multibyte::stripos($string, $find); + $expected = 31; + $this->assertEquals($expected, $result); + + $string = '눡눢눣눤눥눦눧눨눩눪눫눬눭눮눯눰눱눲눳눴눵눶눷눸눹눺눻눼눽눾눿뉀뉁뉂뉃뉄뉅뉆뉇뉈뉉뉊뉋뉌뉍뉎뉏뉐뉑뉒뉓뉔뉕뉖뉗뉘뉙뉚뉛뉜뉝뉞뉟뉠뉡뉢뉣뉤뉥뉦뉧뉨뉩뉪뉫뉬뉭뉮뉯뉰뉱뉲뉳뉴뉵뉶뉷뉸뉹뉺뉻뉼뉽뉾뉿늀늁늂늃늄'; + $find = '눻'; + $result = Multibyte::stripos($string, $find); + $expected = 26; + $this->assertEquals($expected, $result); + + $string = 'ﹰﹱﹲﹳﹴ﹵ﹶﹷﹸﹹﹺﹻﹼﹽﹾﹿﺀﺁﺂﺃﺄﺅﺆﺇﺈﺉﺊﺋﺌﺍﺎﺏﺐﺑﺒﺓﺔﺕﺖﺗﺘﺙﺚﺛﺜﺝﺞﺟﺠﺡﺢﺣﺤﺥﺦﺧﺨﺩﺪﺫﺬﺭﺮﺯﺰ'; + $find = 'ﺞ'; + $result = Multibyte::stripos($string, $find); + $expected = 46; + $this->assertEquals($expected, $result); + + $string = 'ﺱﺲﺳﺴﺵﺶﺷﺸﺹﺺﺻﺼﺽﺾﺿﻀﻁﻂﻃﻄﻅﻆﻇﻈﻉﻊﻋﻌﻍﻎﻏﻐﻑﻒﻓﻔﻕﻖﻗﻘﻙﻚﻛﻜﻝﻞﻟﻠﻡﻢﻣﻤﻥﻦﻧﻨﻩﻪﻫﻬﻭﻮﻯﻰﻱﻲﻳﻴﻵﻶﻷﻸﻹﻺﻻﻼ'; + $find = 'ﻞ'; + $result = Multibyte::stripos($string, $find); + $expected = 45; + $this->assertEquals($expected, $result); + + $string = 'abcdefghijklmnopqrstuvwxyz'; + $find = 'k'; + $result = Multibyte::stripos($string, $find); + $expected = 10; + $this->assertEquals($expected, $result); + + $string = 'abcdefghijklmnopqrstuvwxyz'; + $find = 'K'; + $result = Multibyte::stripos($string, $find); + $expected = 10; + $this->assertEquals($expected, $result); + + $string = '。「」、・ヲァィゥェォャュョッーアイウエオカキク'; + $find = 'ア'; + $result = Multibyte::stripos($string, $find); + $expected = 16; + $this->assertEquals($expected, $result); + + $string = 'ケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン゙'; + $find = 'ハ'; + $result = Multibyte::stripos($string, $find); + $expected = 17; + $this->assertEquals($expected, $result); + + $string = 'Ĥēĺļŏ, Ŵőřļď!'; + $find = 'ő'; + $result = Multibyte::stripos($string, $find); + $expected = 8; + $this->assertEquals($expected, $result); + + $string = 'Ĥēĺļŏ, Ŵőřļď!'; + $find = 'Ő'; + $result = Multibyte::stripos($string, $find); + $expected = 8; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'O'; + $result = Multibyte::stripos($string, $find); + $expected = 4; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'o'; + $result = Multibyte::stripos($string, $find); + $expected = 4; + $this->assertEquals($expected, $result); + + $string = 'čini'; + $find = 'n'; + $result = Multibyte::stripos($string, $find); + $expected = 2; + $this->assertEquals($expected, $result); + + $string = 'čini'; + $find = 'N'; + $result = Multibyte::stripos($string, $find); + $expected = 2; + $this->assertEquals($expected, $result); + + $string = 'moći'; + $find = 'ć'; + $result = Multibyte::stripos($string, $find); + $expected = 2; + $this->assertEquals($expected, $result); + + $string = 'moći'; + $find = 'Ć'; + $result = Multibyte::stripos($string, $find); + $expected = 2; + $this->assertEquals($expected, $result); + + $string = 'državni'; + $find = 'ž'; + $result = Multibyte::stripos($string, $find); + $expected = 2; + $this->assertEquals($expected, $result); + + $string = 'državni'; + $find = 'Ž'; + $result = Multibyte::stripos($string, $find); + $expected = 2; + $this->assertEquals($expected, $result); + + $string = '把百度设为首页'; + $find = '设'; + $result = Multibyte::stripos($string, $find); + $expected = 3; + $this->assertEquals($expected, $result); + + $string = '一二三周永龍'; + $find = '周'; + $result = Multibyte::stripos($string, $find); + $expected = 3; + $this->assertEquals($expected, $result); + + $string = 'državni'; + $find = 'DŽ'; + $result = Multibyte::stripos($string, $find); + $expected = false; + $this->assertEquals($expected, $result); + } + +/** + * testUsingMbStristr method + * + * @return void + */ + public function testUsingMbStristr() { + $string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; + $find = 'f'; + $result = mb_stristr($string, $find); + $expected = 'FGHIJKLMNOPQRSTUVWXYZ0123456789'; + $this->assertEquals($expected, $result); + + $string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; + $find = 'f'; + $result = mb_stristr($string, $find, true); + $expected = 'ABCDE'; + $this->assertEquals($expected, $result); + + $string = 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ'; + $find = 'å'; + $result = mb_stristr($string, $find); + $expected = 'ÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ'; + $this->assertEquals($expected, $result); + + $string = 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ'; + $find = 'å'; + $result = mb_stristr($string, $find, true); + $expected = 'ÀÁÂÃÄ'; + $this->assertEquals($expected, $result); + + $string = 'ĀĂĄĆĈĊČĎĐĒĔĖĘĚĜĞĠĢĤĦĨĪĬĮIJĴĶĹĻĽĿŁŃŅŇŊŌŎŐŒŔŖŘŚŜŞŠŢŤŦŨŪŬŮŰŲŴŶŹŻŽ'; + $find = 'ċ'; + $result = mb_stristr($string, $find); + $expected = 'ĊČĎĐĒĔĖĘĚĜĞĠĢĤĦĨĪĬĮIJĴĶĹĻĽĿŁŃŅŇŊŌŎŐŒŔŖŘŚŜŞŠŢŤŦŨŪŬŮŰŲŴŶŹŻŽ'; + $this->assertEquals($expected, $result); + + $string = 'ĀĂĄĆĈĊČĎĐĒĔĖĘĚĜĞĠĢĤĦĨĪĬĮIJĴĶĹĻĽĿŁŃŅŇŊŌŎŐŒŔŖŘŚŜŞŠŢŤŦŨŪŬŮŰŲŴŶŹŻŽ'; + $find = 'ċ'; + $result = mb_stristr($string, $find, true); + $expected = 'ĀĂĄĆĈ'; + $this->assertEquals($expected, $result); + + $string = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'; + $find = 'f'; + $result = mb_stristr($string, $find); + $expected = 'FGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'; + $this->assertEquals($expected, $result); + + $string = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'; + $find = 'f'; + $result = mb_stristr($string, $find, true); + $expected = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDE'; + $this->assertEquals($expected, $result); + + $string = '¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈ'; + $find = 'Μ'; + $result = mb_stristr($string, $find); + $expected = 'µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈ'; + $this->assertEquals($expected, $result); + + $string = '¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈ'; + $find = 'Μ'; + $result = mb_stristr($string, $find, true); + $expected = '¡¢£¤¥¦§¨©ª«¬­®¯°±²³´'; + $this->assertEquals($expected, $result); + + $string = 'ÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬ'; + $find = 'þ'; + $result = mb_stristr($string, $find); + $expected = 'Þßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬ'; + $this->assertEquals($expected, $result); + + $string = 'ÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬ'; + $find = 'þ'; + $result = mb_stristr($string, $find, true); + $expected = 'ÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝ'; + $this->assertEquals($expected, $result); + + $string = 'ĭĮįİıIJijĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏƐ'; + $find = 'Ņ'; + $result = mb_stristr($string, $find); + $expected = 'ŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏƐ'; + $this->assertEquals($expected, $result); + + $string = 'ĭĮįİıIJijĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏƐ'; + $find = 'Ņ'; + $result = mb_stristr($string, $find, true); + $expected = 'ĭĮįİıIJijĴĵĶķĸĹĺĻļĽľĿŀŁłŃń'; + $this->assertEquals($expected, $result); + + $string = 'ƑƒƓƔƕƖƗƘƙƚƛƜƝƞƟƠơƢƣƤƥƦƧƨƩƪƫƬƭƮƯưƱƲƳƴƵƶƷƸƹƺƻƼƽƾƿǀǁǂǃDŽDždžLJLjljNJNjnjǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰDZDzdzǴ'; + $find = 'Ƹ'; + $result = mb_stristr($string, $find); + $expected = 'ƸƹƺƻƼƽƾƿǀǁǂǃDŽDždžLJLjljNJNjnjǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰDZDzdzǴ'; + $this->assertEquals($expected, $result); + + $find = 'Ƹ'; + $result = mb_stristr($string, $find, true); + $expected = 'ƑƒƓƔƕƖƗƘƙƚƛƜƝƞƟƠơƢƣƤƥƦƧƨƩƪƫƬƭƮƯưƱƲƳƴƵƶƷ'; + $this->assertEquals($expected, $result); + + $string = 'əɚɛɜɝɞɟɠɡɢɣɤɥɦɧɨɩɪɫɬɭɮɯɰɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿʀʁʂʃʄʅʆʇʈʉʊʋʌʍʎʏʐʑʒʓʔʕʖʗʘʙʚʛʜʝʞʟʠʡʢʣʤʥʦʧʨʩʪʫʬʭʮʯʰʱʲʳʴʵʶʷʸʹʺʻʼ'; + $find = 'Ʀ'; + $result = mb_stristr($string, $find); + $expected = 'ʀʁʂʃʄʅʆʇʈʉʊʋʌʍʎʏʐʑʒʓʔʕʖʗʘʙʚʛʜʝʞʟʠʡʢʣʤʥʦʧʨʩʪʫʬʭʮʯʰʱʲʳʴʵʶʷʸʹʺʻʼ'; + $this->assertEquals($expected, $result); + + $string = 'əɚɛɜɝɞɟɠɡɢɣɤɥɦɧɨɩɪɫɬɭɮɯɰɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿʀʁʂʃʄʅʆʇʈʉʊʋʌʍʎʏʐʑʒʓʔʕʖʗʘʙʚʛʜʝʞʟʠʡʢʣʤʥʦʧʨʩʪʫʬʭʮʯʰʱʲʳʴʵʶʷʸʹʺʻʼ'; + $find = 'Ʀ'; + $result = mb_stristr($string, $find, true); + $expected = 'əɚɛɜɝɞɟɠɡɢɣɤɥɦɧɨɩɪɫɬɭɮɯɰɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿ'; + $this->assertEquals($expected, $result); + + $string = 'ЀЁЂЃЄЅІЇЈЉЊЋЌЍЎЏАБВГДЕЖЗИЙКЛ'; + $find = 'ї'; + $result = mb_stristr($string, $find); + $expected = 'ЇЈЉЊЋЌЍЎЏАБВГДЕЖЗИЙКЛ'; + $this->assertEquals($expected, $result); + + $string = 'ЀЁЂЃЄЅІЇЈЉЊЋЌЍЎЏАБВГДЕЖЗИЙКЛ'; + $find = 'ї'; + $result = mb_stristr($string, $find, true); + $expected = 'ЀЁЂЃЄЅІ'; + $this->assertEquals($expected, $result); + + $string = 'МНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыь'; + $find = 'Р'; + $result = mb_stristr($string, $find); + $expected = 'РСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыь'; + $this->assertEquals($expected, $result); + + $string = 'МНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыь'; + $find = 'Р'; + $result = mb_stristr($string, $find, true); + $expected = 'МНОП'; + $this->assertEquals($expected, $result); + + $string = 'فقكلمنهوىيًٌٍَُ'; + $find = 'ن'; + $result = mb_stristr($string, $find); + $expected = 'نهوىيًٌٍَُ'; + $this->assertEquals($expected, $result); + + $string = 'فقكلمنهوىيًٌٍَُ'; + $find = 'ن'; + $result = mb_stristr($string, $find, true); + $expected = 'فقكلم'; + $this->assertEquals($expected, $result); + + $string = '✰✱✲✳✴✵✶✷✸✹✺✻✼✽✾✿❀❁❂❃❄❅❆❇❈❉❊❋❌❍❎❏❐❑❒❓❔❕❖❗❘❙❚❛❜❝❞'; + $find = '✿'; + $result = mb_stristr($string, $find); + $expected = '✿❀❁❂❃❄❅❆❇❈❉❊❋❌❍❎❏❐❑❒❓❔❕❖❗❘❙❚❛❜❝❞'; + $this->assertEquals($expected, $result); + + $string = '✰✱✲✳✴✵✶✷✸✹✺✻✼✽✾✿❀❁❂❃❄❅❆❇❈❉❊❋❌❍❎❏❐❑❒❓❔❕❖❗❘❙❚❛❜❝❞'; + $find = '✿'; + $result = mb_stristr($string, $find, true); + $expected = '✰✱✲✳✴✵✶✷✸✹✺✻✼✽✾'; + $this->assertEquals($expected, $result); + + $string = '⺀⺁⺂⺃⺄⺅⺆⺇⺈⺉⺊⺋⺌⺍⺎⺏⺐⺑⺒⺓⺔⺕⺖⺗⺘⺙⺛⺜⺝⺞⺟⺠⺡⺢⺣⺤⺥⺦⺧⺨⺩⺪⺫⺬⺭⺮⺯⺰⺱⺲⺳⺴⺵⺶⺷⺸⺹⺺⺻⺼⺽⺾⺿⻀⻁⻂⻃⻄⻅⻆⻇⻈⻉⻊⻋⻌⻍⻎⻏⻐⻑⻒⻓⻔⻕⻖⻗⻘⻙⻚⻛⻜⻝⻞⻟⻠'; + $find = '⺐'; + $result = mb_stristr($string, $find); + $expected = '⺐⺑⺒⺓⺔⺕⺖⺗⺘⺙⺛⺜⺝⺞⺟⺠⺡⺢⺣⺤⺥⺦⺧⺨⺩⺪⺫⺬⺭⺮⺯⺰⺱⺲⺳⺴⺵⺶⺷⺸⺹⺺⺻⺼⺽⺾⺿⻀⻁⻂⻃⻄⻅⻆⻇⻈⻉⻊⻋⻌⻍⻎⻏⻐⻑⻒⻓⻔⻕⻖⻗⻘⻙⻚⻛⻜⻝⻞⻟⻠'; + $this->assertEquals($expected, $result); + + $string = '⺀⺁⺂⺃⺄⺅⺆⺇⺈⺉⺊⺋⺌⺍⺎⺏⺐⺑⺒⺓⺔⺕⺖⺗⺘⺙⺛⺜⺝⺞⺟⺠⺡⺢⺣⺤⺥⺦⺧⺨⺩⺪⺫⺬⺭⺮⺯⺰⺱⺲⺳⺴⺵⺶⺷⺸⺹⺺⺻⺼⺽⺾⺿⻀⻁⻂⻃⻄⻅⻆⻇⻈⻉⻊⻋⻌⻍⻎⻏⻐⻑⻒⻓⻔⻕⻖⻗⻘⻙⻚⻛⻜⻝⻞⻟⻠'; + $find = '⺐'; + $result = mb_stristr($string, $find, true); + $expected = '⺀⺁⺂⺃⺄⺅⺆⺇⺈⺉⺊⺋⺌⺍⺎⺏'; + $this->assertEquals($expected, $result); + + $string = '⽅⽆⽇⽈⽉⽊⽋⽌⽍⽎⽏⽐⽑⽒⽓⽔⽕⽖⽗⽘⽙⽚⽛⽜⽝⽞⽟⽠⽡⽢⽣⽤⽥⽦⽧⽨⽩⽪⽫⽬⽭⽮⽯⽰⽱⽲⽳⽴⽵⽶⽷⽸⽹⽺⽻⽼⽽⽾⽿'; + $find = '⽤'; + $result = mb_stristr($string, $find); + $expected = '⽤⽥⽦⽧⽨⽩⽪⽫⽬⽭⽮⽯⽰⽱⽲⽳⽴⽵⽶⽷⽸⽹⽺⽻⽼⽽⽾⽿'; + $this->assertEquals($expected, $result); + + $string = '⽅⽆⽇⽈⽉⽊⽋⽌⽍⽎⽏⽐⽑⽒⽓⽔⽕⽖⽗⽘⽙⽚⽛⽜⽝⽞⽟⽠⽡⽢⽣⽤⽥⽦⽧⽨⽩⽪⽫⽬⽭⽮⽯⽰⽱⽲⽳⽴⽵⽶⽷⽸⽹⽺⽻⽼⽽⽾⽿'; + $find = '⽤'; + $result = mb_stristr($string, $find, true); + $expected = '⽅⽆⽇⽈⽉⽊⽋⽌⽍⽎⽏⽐⽑⽒⽓⽔⽕⽖⽗⽘⽙⽚⽛⽜⽝⽞⽟⽠⽡⽢⽣'; + $this->assertEquals($expected, $result); + + $string = '눡눢눣눤눥눦눧눨눩눪눫눬눭눮눯눰눱눲눳눴눵눶눷눸눹눺눻눼눽눾눿뉀뉁뉂뉃뉄뉅뉆뉇뉈뉉뉊뉋뉌뉍뉎뉏뉐뉑뉒뉓뉔뉕뉖뉗뉘뉙뉚뉛뉜뉝뉞뉟뉠뉡뉢뉣뉤뉥뉦뉧뉨뉩뉪뉫뉬뉭뉮뉯뉰뉱뉲뉳뉴뉵뉶뉷뉸뉹뉺뉻뉼뉽뉾뉿늀늁늂늃늄'; + $find = '눻'; + $result = mb_stristr($string, $find); + $expected = '눻눼눽눾눿뉀뉁뉂뉃뉄뉅뉆뉇뉈뉉뉊뉋뉌뉍뉎뉏뉐뉑뉒뉓뉔뉕뉖뉗뉘뉙뉚뉛뉜뉝뉞뉟뉠뉡뉢뉣뉤뉥뉦뉧뉨뉩뉪뉫뉬뉭뉮뉯뉰뉱뉲뉳뉴뉵뉶뉷뉸뉹뉺뉻뉼뉽뉾뉿늀늁늂늃늄'; + $this->assertEquals($expected, $result); + + $string = '눡눢눣눤눥눦눧눨눩눪눫눬눭눮눯눰눱눲눳눴눵눶눷눸눹눺눻눼눽눾눿뉀뉁뉂뉃뉄뉅뉆뉇뉈뉉뉊뉋뉌뉍뉎뉏뉐뉑뉒뉓뉔뉕뉖뉗뉘뉙뉚뉛뉜뉝뉞뉟뉠뉡뉢뉣뉤뉥뉦뉧뉨뉩뉪뉫뉬뉭뉮뉯뉰뉱뉲뉳뉴뉵뉶뉷뉸뉹뉺뉻뉼뉽뉾뉿늀늁늂늃늄'; + $find = '눻'; + $result = mb_stristr($string, $find, true); + $expected = '눡눢눣눤눥눦눧눨눩눪눫눬눭눮눯눰눱눲눳눴눵눶눷눸눹눺'; + $this->assertEquals($expected, $result); + + $string = 'ﹰﹱﹲﹳﹴ﹵ﹶﹷﹸﹹﹺﹻﹼﹽﹾﹿﺀﺁﺂﺃﺄﺅﺆﺇﺈﺉﺊﺋﺌﺍﺎﺏﺐﺑﺒﺓﺔﺕﺖﺗﺘﺙﺚﺛﺜﺝﺞﺟﺠﺡﺢﺣﺤﺥﺦﺧﺨﺩﺪﺫﺬﺭﺮﺯﺰ'; + $find = 'ﺞ'; + $result = mb_stristr($string, $find); + $expected = 'ﺞﺟﺠﺡﺢﺣﺤﺥﺦﺧﺨﺩﺪﺫﺬﺭﺮﺯﺰ'; + $this->assertEquals($expected, $result); + + $string = 'ﹰﹱﹲﹳﹴ﹵ﹶﹷﹸﹹﹺﹻﹼﹽﹾﹿﺀﺁﺂﺃﺄﺅﺆﺇﺈﺉﺊﺋﺌﺍﺎﺏﺐﺑﺒﺓﺔﺕﺖﺗﺘﺙﺚﺛﺜﺝﺞﺟﺠﺡﺢﺣﺤﺥﺦﺧﺨﺩﺪﺫﺬﺭﺮﺯﺰ'; + $find = 'ﺞ'; + $result = mb_stristr($string, $find, true); + $expected = 'ﹰﹱﹲﹳﹴ﹵ﹶﹷﹸﹹﹺﹻﹼﹽﹾﹿﺀﺁﺂﺃﺄﺅﺆﺇﺈﺉﺊﺋﺌﺍﺎﺏﺐﺑﺒﺓﺔﺕﺖﺗﺘﺙﺚﺛﺜﺝ'; + $this->assertEquals($expected, $result); + + $string = 'ﺱﺲﺳﺴﺵﺶﺷﺸﺹﺺﺻﺼﺽﺾﺿﻀﻁﻂﻃﻄﻅﻆﻇﻈﻉﻊﻋﻌﻍﻎﻏﻐﻑﻒﻓﻔﻕﻖﻗﻘﻙﻚﻛﻜﻝﻞﻟﻠﻡﻢﻣﻤﻥﻦﻧﻨﻩﻪﻫﻬﻭﻮﻯﻰﻱﻲﻳﻴﻵﻶﻷﻸﻹﻺﻻﻼ'; + $find = 'ﻞ'; + $result = mb_stristr($string, $find); + $expected = 'ﻞﻟﻠﻡﻢﻣﻤﻥﻦﻧﻨﻩﻪﻫﻬﻭﻮﻯﻰﻱﻲﻳﻴﻵﻶﻷﻸﻹﻺﻻﻼ'; + $this->assertEquals($expected, $result); + + $string = 'ﺱﺲﺳﺴﺵﺶﺷﺸﺹﺺﺻﺼﺽﺾﺿﻀﻁﻂﻃﻄﻅﻆﻇﻈﻉﻊﻋﻌﻍﻎﻏﻐﻑﻒﻓﻔﻕﻖﻗﻘﻙﻚﻛﻜﻝﻞﻟﻠﻡﻢﻣﻤﻥﻦﻧﻨﻩﻪﻫﻬﻭﻮﻯﻰﻱﻲﻳﻴﻵﻶﻷﻸﻹﻺﻻﻼ'; + $find = 'ﻞ'; + $result = mb_stristr($string, $find, true); + $expected = 'ﺱﺲﺳﺴﺵﺶﺷﺸﺹﺺﺻﺼﺽﺾﺿﻀﻁﻂﻃﻄﻅﻆﻇﻈﻉﻊﻋﻌﻍﻎﻏﻐﻑﻒﻓﻔﻕﻖﻗﻘﻙﻚﻛﻜﻝ'; + $this->assertEquals($expected, $result); + + $string = 'abcdefghijklmnopqrstuvwxyz'; + $find = 'K'; + $result = mb_stristr($string, $find); + $expected = 'klmnopqrstuvwxyz'; + $this->assertEquals($expected, $result); + + $string = 'abcdefghijklmnopqrstuvwxyz'; + $find = 'K'; + $result = mb_stristr($string, $find, true); + $expected = 'abcdefghij'; + $this->assertEquals($expected, $result); + + $string = '。「」、・ヲァィゥェォャュョッーアイウエオカキク'; + $find = 'ア'; + $result = mb_stristr($string, $find); + $expected = 'アイウエオカキク'; + $this->assertEquals($expected, $result); + + $string = '。「」、・ヲァィゥェォャュョッーアイウエオカキク'; + $find = 'ア'; + $result = mb_stristr($string, $find, true); + $expected = '。「」、・ヲァィゥェォャュョッー'; + $this->assertEquals($expected, $result); + + $string = 'ケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン゙'; + $find = 'ハ'; + $result = mb_stristr($string, $find); + $expected = 'ハヒフヘホマミムメモヤユヨラリルレロワン゙'; + $this->assertEquals($expected, $result); + + $string = 'ケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン゙'; + $find = 'ハ'; + $result = mb_stristr($string, $find, true); + $expected = 'ケコサシスセソタチツテトナニヌネノ'; + $this->assertEquals($expected, $result); + + $string = 'Ĥēĺļŏ, Ŵőřļď!'; + $find = 'Ő'; + $result = mb_stristr($string, $find); + $expected = 'őřļď!'; + $this->assertEquals($expected, $result); + + $string = 'Ĥēĺļŏ, Ŵőřļď!'; + $find = 'Ő'; + $result = mb_stristr($string, $find, true); + $expected = 'Ĥēĺļŏ, Ŵ'; + $this->assertEquals($expected, $result); + + $string = 'Ĥēĺļŏ, Ŵőřļď!'; + $find = 'ĺļ'; + $result = mb_stristr($string, $find, true); + $expected = 'Ĥē'; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'O'; + $result = mb_stristr($string, $find); + $expected = 'o, World!'; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'O'; + $result = mb_stristr($string, $find, true); + $expected = 'Hell'; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'Wo'; + $result = mb_stristr($string, $find); + $expected = 'World!'; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'Wo'; + $result = mb_stristr($string, $find, true); + $expected = 'Hello, '; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'll'; + $result = mb_stristr($string, $find); + $expected = 'llo, World!'; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'll'; + $result = mb_stristr($string, $find, true); + $expected = 'He'; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'rld'; + $result = mb_stristr($string, $find); + $expected = 'rld!'; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'rld'; + $result = mb_stristr($string, $find, true); + $expected = 'Hello, Wo'; + $this->assertEquals($expected, $result); + + $string = 'čini'; + $find = 'N'; + $result = mb_stristr($string, $find); + $expected = 'ni'; + $this->assertEquals($expected, $result); + + $string = 'čini'; + $find = 'N'; + $result = mb_stristr($string, $find, true); + $expected = 'či'; + $this->assertEquals($expected, $result); + + $string = 'moći'; + $find = 'Ć'; + $result = mb_stristr($string, $find); + $expected = 'ći'; + $this->assertEquals($expected, $result); + + $string = 'moći'; + $find = 'Ć'; + $result = mb_stristr($string, $find, true); + $expected = 'mo'; + $this->assertEquals($expected, $result); + + $string = 'državni'; + $find = 'Ž'; + $result = mb_stristr($string, $find); + $expected = 'žavni'; + $this->assertEquals($expected, $result); + + $string = 'državni'; + $find = 'Ž'; + $result = mb_stristr($string, $find, true); + $expected = 'dr'; + $this->assertEquals($expected, $result); + + $string = '把百度设为首页'; + $find = '设'; + $result = mb_stristr($string, $find); + $expected = '设为首页'; + $this->assertEquals($expected, $result); + + $string = '把百度设为首页'; + $find = '设'; + $result = mb_stristr($string, $find, true); + $expected = '把百度'; + $this->assertEquals($expected, $result); + + $string = '一二三周永龍'; + $find = '周'; + $result = mb_stristr($string, $find); + $expected = '周永龍'; + $this->assertEquals($expected, $result); + + $string = '一二三周永龍'; + $find = '周'; + $result = mb_stristr($string, $find, true); + $expected = '一二三'; + $this->assertEquals($expected, $result); + + $string = '一二三周永龍'; + $find = '二周'; + $result = mb_stristr($string, $find); + $expected = false; + $this->assertEquals($expected, $result); + } + +/** + * testMultibyteStristr method + * + * @return void + */ + public function testMultibyteStristr() { + $string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; + $find = 'f'; + $result = Multibyte::stristr($string, $find); + $expected = 'FGHIJKLMNOPQRSTUVWXYZ0123456789'; + $this->assertEquals($expected, $result); + + $string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; + $find = 'f'; + $result = Multibyte::stristr($string, $find, true); + $expected = 'ABCDE'; + $this->assertEquals($expected, $result); + + $string = 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ'; + $find = 'å'; + $result = Multibyte::stristr($string, $find); + $expected = 'ÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ'; + $this->assertEquals($expected, $result); + + $string = 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ'; + $find = 'å'; + $result = Multibyte::stristr($string, $find, true); + $expected = 'ÀÁÂÃÄ'; + $this->assertEquals($expected, $result); + + $string = 'ĀĂĄĆĈĊČĎĐĒĔĖĘĚĜĞĠĢĤĦĨĪĬĮIJĴĶĹĻĽĿŁŃŅŇŊŌŎŐŒŔŖŘŚŜŞŠŢŤŦŨŪŬŮŰŲŴŶŹŻŽ'; + $find = 'ċ'; + $result = Multibyte::stristr($string, $find); + $expected = 'ĊČĎĐĒĔĖĘĚĜĞĠĢĤĦĨĪĬĮIJĴĶĹĻĽĿŁŃŅŇŊŌŎŐŒŔŖŘŚŜŞŠŢŤŦŨŪŬŮŰŲŴŶŹŻŽ'; + $this->assertEquals($expected, $result); + + $string = 'ĀĂĄĆĈĊČĎĐĒĔĖĘĚĜĞĠĢĤĦĨĪĬĮIJĴĶĹĻĽĿŁŃŅŇŊŌŎŐŒŔŖŘŚŜŞŠŢŤŦŨŪŬŮŰŲŴŶŹŻŽ'; + $find = 'ċ'; + $result = Multibyte::stristr($string, $find, true); + $expected = 'ĀĂĄĆĈ'; + $this->assertEquals($expected, $result); + + $string = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'; + $find = 'f'; + $result = Multibyte::stristr($string, $find); + $expected = 'FGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'; + $this->assertEquals($expected, $result); + + $string = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'; + $find = 'f'; + $result = Multibyte::stristr($string, $find, true); + $expected = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDE'; + $this->assertEquals($expected, $result); + + $string = '¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈ'; + $find = 'Μ'; + $result = Multibyte::stristr($string, $find); + $expected = 'µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈ'; + $this->assertEquals($expected, $result); + + $string = '¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈ'; + $find = 'Μ'; + $result = Multibyte::stristr($string, $find, true); + $expected = '¡¢£¤¥¦§¨©ª«¬­®¯°±²³´'; + $this->assertEquals($expected, $result); + + $string = 'ÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬ'; + $find = 'þ'; + $result = Multibyte::stristr($string, $find); + $expected = 'Þßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬ'; + $this->assertEquals($expected, $result); + + $string = 'ÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬ'; + $find = 'þ'; + $result = Multibyte::stristr($string, $find, true); + $expected = 'ÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝ'; + $this->assertEquals($expected, $result); + + $string = 'ĭĮįİıIJijĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏƐ'; + $find = 'Ņ'; + $result = Multibyte::stristr($string, $find); + $expected = 'ŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏƐ'; + $this->assertEquals($expected, $result); + + $string = 'ĭĮįİıIJijĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏƐ'; + $find = 'Ņ'; + $result = Multibyte::stristr($string, $find, true); + $expected = 'ĭĮįİıIJijĴĵĶķĸĹĺĻļĽľĿŀŁłŃń'; + $this->assertEquals($expected, $result); + + $string = 'ƑƒƓƔƕƖƗƘƙƚƛƜƝƞƟƠơƢƣƤƥƦƧƨƩƪƫƬƭƮƯưƱƲƳƴƵƶƷƸƹƺƻƼƽƾƿǀǁǂǃDŽDždžLJLjljNJNjnjǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰDZDzdzǴ'; + $find = 'Ƹ'; + $result = Multibyte::stristr($string, $find); + $expected = 'ƸƹƺƻƼƽƾƿǀǁǂǃDŽDždžLJLjljNJNjnjǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰDZDzdzǴ'; + $this->assertEquals($expected, $result); + + $find = 'Ƹ'; + $result = Multibyte::stristr($string, $find, true); + $expected = 'ƑƒƓƔƕƖƗƘƙƚƛƜƝƞƟƠơƢƣƤƥƦƧƨƩƪƫƬƭƮƯưƱƲƳƴƵƶƷ'; + $this->assertEquals($expected, $result); + + $string = 'əɚɛɜɝɞɟɠɡɢɣɤɥɦɧɨɩɪɫɬɭɮɯɰɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿʀʁʂʃʄʅʆʇʈʉʊʋʌʍʎʏʐʑʒʓʔʕʖʗʘʙʚʛʜʝʞʟʠʡʢʣʤʥʦʧʨʩʪʫʬʭʮʯʰʱʲʳʴʵʶʷʸʹʺʻʼ'; + $find = 'Ʀ'; + $result = Multibyte::stristr($string, $find); + $expected = 'ʀʁʂʃʄʅʆʇʈʉʊʋʌʍʎʏʐʑʒʓʔʕʖʗʘʙʚʛʜʝʞʟʠʡʢʣʤʥʦʧʨʩʪʫʬʭʮʯʰʱʲʳʴʵʶʷʸʹʺʻʼ'; + $this->assertEquals($expected, $result); + + $string = 'əɚɛɜɝɞɟɠɡɢɣɤɥɦɧɨɩɪɫɬɭɮɯɰɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿʀʁʂʃʄʅʆʇʈʉʊʋʌʍʎʏʐʑʒʓʔʕʖʗʘʙʚʛʜʝʞʟʠʡʢʣʤʥʦʧʨʩʪʫʬʭʮʯʰʱʲʳʴʵʶʷʸʹʺʻʼ'; + $find = 'Ʀ'; + $result = Multibyte::stristr($string, $find, true); + $expected = 'əɚɛɜɝɞɟɠɡɢɣɤɥɦɧɨɩɪɫɬɭɮɯɰɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿ'; + $this->assertEquals($expected, $result); + + $string = 'ЀЁЂЃЄЅІЇЈЉЊЋЌЍЎЏАБВГДЕЖЗИЙКЛ'; + $find = 'ї'; + $result = Multibyte::stristr($string, $find); + $expected = 'ЇЈЉЊЋЌЍЎЏАБВГДЕЖЗИЙКЛ'; + $this->assertEquals($expected, $result); + + $string = 'ЀЁЂЃЄЅІЇЈЉЊЋЌЍЎЏАБВГДЕЖЗИЙКЛ'; + $find = 'ї'; + $result = Multibyte::stristr($string, $find, true); + $expected = 'ЀЁЂЃЄЅІ'; + $this->assertEquals($expected, $result); + + $string = 'МНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыь'; + $find = 'Р'; + $result = Multibyte::stristr($string, $find); + $expected = 'РСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыь'; + $this->assertEquals($expected, $result); + + $string = 'МНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыь'; + $find = 'Р'; + $result = Multibyte::stristr($string, $find, true); + $expected = 'МНОП'; + $this->assertEquals($expected, $result); + + $string = 'فقكلمنهوىيًٌٍَُ'; + $find = 'ن'; + $result = Multibyte::stristr($string, $find); + $expected = 'نهوىيًٌٍَُ'; + $this->assertEquals($expected, $result); + + $string = 'فقكلمنهوىيًٌٍَُ'; + $find = 'ن'; + $result = Multibyte::stristr($string, $find, true); + $expected = 'فقكلم'; + $this->assertEquals($expected, $result); + + $string = '✰✱✲✳✴✵✶✷✸✹✺✻✼✽✾✿❀❁❂❃❄❅❆❇❈❉❊❋❌❍❎❏❐❑❒❓❔❕❖❗❘❙❚❛❜❝❞'; + $find = '✿'; + $result = Multibyte::stristr($string, $find); + $expected = '✿❀❁❂❃❄❅❆❇❈❉❊❋❌❍❎❏❐❑❒❓❔❕❖❗❘❙❚❛❜❝❞'; + $this->assertEquals($expected, $result); + + $string = '✰✱✲✳✴✵✶✷✸✹✺✻✼✽✾✿❀❁❂❃❄❅❆❇❈❉❊❋❌❍❎❏❐❑❒❓❔❕❖❗❘❙❚❛❜❝❞'; + $find = '✿'; + $result = Multibyte::stristr($string, $find, true); + $expected = '✰✱✲✳✴✵✶✷✸✹✺✻✼✽✾'; + $this->assertEquals($expected, $result); + + $string = '⺀⺁⺂⺃⺄⺅⺆⺇⺈⺉⺊⺋⺌⺍⺎⺏⺐⺑⺒⺓⺔⺕⺖⺗⺘⺙⺛⺜⺝⺞⺟⺠⺡⺢⺣⺤⺥⺦⺧⺨⺩⺪⺫⺬⺭⺮⺯⺰⺱⺲⺳⺴⺵⺶⺷⺸⺹⺺⺻⺼⺽⺾⺿⻀⻁⻂⻃⻄⻅⻆⻇⻈⻉⻊⻋⻌⻍⻎⻏⻐⻑⻒⻓⻔⻕⻖⻗⻘⻙⻚⻛⻜⻝⻞⻟⻠'; + $find = '⺐'; + $result = Multibyte::stristr($string, $find); + $expected = '⺐⺑⺒⺓⺔⺕⺖⺗⺘⺙⺛⺜⺝⺞⺟⺠⺡⺢⺣⺤⺥⺦⺧⺨⺩⺪⺫⺬⺭⺮⺯⺰⺱⺲⺳⺴⺵⺶⺷⺸⺹⺺⺻⺼⺽⺾⺿⻀⻁⻂⻃⻄⻅⻆⻇⻈⻉⻊⻋⻌⻍⻎⻏⻐⻑⻒⻓⻔⻕⻖⻗⻘⻙⻚⻛⻜⻝⻞⻟⻠'; + $this->assertEquals($expected, $result); + + $string = '⺀⺁⺂⺃⺄⺅⺆⺇⺈⺉⺊⺋⺌⺍⺎⺏⺐⺑⺒⺓⺔⺕⺖⺗⺘⺙⺛⺜⺝⺞⺟⺠⺡⺢⺣⺤⺥⺦⺧⺨⺩⺪⺫⺬⺭⺮⺯⺰⺱⺲⺳⺴⺵⺶⺷⺸⺹⺺⺻⺼⺽⺾⺿⻀⻁⻂⻃⻄⻅⻆⻇⻈⻉⻊⻋⻌⻍⻎⻏⻐⻑⻒⻓⻔⻕⻖⻗⻘⻙⻚⻛⻜⻝⻞⻟⻠'; + $find = '⺐'; + $result = Multibyte::stristr($string, $find, true); + $expected = '⺀⺁⺂⺃⺄⺅⺆⺇⺈⺉⺊⺋⺌⺍⺎⺏'; + $this->assertEquals($expected, $result); + + $string = '⽅⽆⽇⽈⽉⽊⽋⽌⽍⽎⽏⽐⽑⽒⽓⽔⽕⽖⽗⽘⽙⽚⽛⽜⽝⽞⽟⽠⽡⽢⽣⽤⽥⽦⽧⽨⽩⽪⽫⽬⽭⽮⽯⽰⽱⽲⽳⽴⽵⽶⽷⽸⽹⽺⽻⽼⽽⽾⽿'; + $find = '⽤'; + $result = Multibyte::stristr($string, $find); + $expected = '⽤⽥⽦⽧⽨⽩⽪⽫⽬⽭⽮⽯⽰⽱⽲⽳⽴⽵⽶⽷⽸⽹⽺⽻⽼⽽⽾⽿'; + $this->assertEquals($expected, $result); + + $string = '⽅⽆⽇⽈⽉⽊⽋⽌⽍⽎⽏⽐⽑⽒⽓⽔⽕⽖⽗⽘⽙⽚⽛⽜⽝⽞⽟⽠⽡⽢⽣⽤⽥⽦⽧⽨⽩⽪⽫⽬⽭⽮⽯⽰⽱⽲⽳⽴⽵⽶⽷⽸⽹⽺⽻⽼⽽⽾⽿'; + $find = '⽤'; + $result = Multibyte::stristr($string, $find, true); + $expected = '⽅⽆⽇⽈⽉⽊⽋⽌⽍⽎⽏⽐⽑⽒⽓⽔⽕⽖⽗⽘⽙⽚⽛⽜⽝⽞⽟⽠⽡⽢⽣'; + $this->assertEquals($expected, $result); + + $string = '눡눢눣눤눥눦눧눨눩눪눫눬눭눮눯눰눱눲눳눴눵눶눷눸눹눺눻눼눽눾눿뉀뉁뉂뉃뉄뉅뉆뉇뉈뉉뉊뉋뉌뉍뉎뉏뉐뉑뉒뉓뉔뉕뉖뉗뉘뉙뉚뉛뉜뉝뉞뉟뉠뉡뉢뉣뉤뉥뉦뉧뉨뉩뉪뉫뉬뉭뉮뉯뉰뉱뉲뉳뉴뉵뉶뉷뉸뉹뉺뉻뉼뉽뉾뉿늀늁늂늃늄'; + $find = '눻'; + $result = Multibyte::stristr($string, $find); + $expected = '눻눼눽눾눿뉀뉁뉂뉃뉄뉅뉆뉇뉈뉉뉊뉋뉌뉍뉎뉏뉐뉑뉒뉓뉔뉕뉖뉗뉘뉙뉚뉛뉜뉝뉞뉟뉠뉡뉢뉣뉤뉥뉦뉧뉨뉩뉪뉫뉬뉭뉮뉯뉰뉱뉲뉳뉴뉵뉶뉷뉸뉹뉺뉻뉼뉽뉾뉿늀늁늂늃늄'; + $this->assertEquals($expected, $result); + + $string = '눡눢눣눤눥눦눧눨눩눪눫눬눭눮눯눰눱눲눳눴눵눶눷눸눹눺눻눼눽눾눿뉀뉁뉂뉃뉄뉅뉆뉇뉈뉉뉊뉋뉌뉍뉎뉏뉐뉑뉒뉓뉔뉕뉖뉗뉘뉙뉚뉛뉜뉝뉞뉟뉠뉡뉢뉣뉤뉥뉦뉧뉨뉩뉪뉫뉬뉭뉮뉯뉰뉱뉲뉳뉴뉵뉶뉷뉸뉹뉺뉻뉼뉽뉾뉿늀늁늂늃늄'; + $find = '눻'; + $result = Multibyte::stristr($string, $find, true); + $expected = '눡눢눣눤눥눦눧눨눩눪눫눬눭눮눯눰눱눲눳눴눵눶눷눸눹눺'; + $this->assertEquals($expected, $result); + + $string = 'ﹰﹱﹲﹳﹴ﹵ﹶﹷﹸﹹﹺﹻﹼﹽﹾﹿﺀﺁﺂﺃﺄﺅﺆﺇﺈﺉﺊﺋﺌﺍﺎﺏﺐﺑﺒﺓﺔﺕﺖﺗﺘﺙﺚﺛﺜﺝﺞﺟﺠﺡﺢﺣﺤﺥﺦﺧﺨﺩﺪﺫﺬﺭﺮﺯﺰ'; + $find = 'ﺞ'; + $result = Multibyte::stristr($string, $find); + $expected = 'ﺞﺟﺠﺡﺢﺣﺤﺥﺦﺧﺨﺩﺪﺫﺬﺭﺮﺯﺰ'; + $this->assertEquals($expected, $result); + + $string = 'ﹰﹱﹲﹳﹴ﹵ﹶﹷﹸﹹﹺﹻﹼﹽﹾﹿﺀﺁﺂﺃﺄﺅﺆﺇﺈﺉﺊﺋﺌﺍﺎﺏﺐﺑﺒﺓﺔﺕﺖﺗﺘﺙﺚﺛﺜﺝﺞﺟﺠﺡﺢﺣﺤﺥﺦﺧﺨﺩﺪﺫﺬﺭﺮﺯﺰ'; + $find = 'ﺞ'; + $result = Multibyte::stristr($string, $find, true); + $expected = 'ﹰﹱﹲﹳﹴ﹵ﹶﹷﹸﹹﹺﹻﹼﹽﹾﹿﺀﺁﺂﺃﺄﺅﺆﺇﺈﺉﺊﺋﺌﺍﺎﺏﺐﺑﺒﺓﺔﺕﺖﺗﺘﺙﺚﺛﺜﺝ'; + $this->assertEquals($expected, $result); + + $string = 'ﺱﺲﺳﺴﺵﺶﺷﺸﺹﺺﺻﺼﺽﺾﺿﻀﻁﻂﻃﻄﻅﻆﻇﻈﻉﻊﻋﻌﻍﻎﻏﻐﻑﻒﻓﻔﻕﻖﻗﻘﻙﻚﻛﻜﻝﻞﻟﻠﻡﻢﻣﻤﻥﻦﻧﻨﻩﻪﻫﻬﻭﻮﻯﻰﻱﻲﻳﻴﻵﻶﻷﻸﻹﻺﻻﻼ'; + $find = 'ﻞ'; + $result = Multibyte::stristr($string, $find); + $expected = 'ﻞﻟﻠﻡﻢﻣﻤﻥﻦﻧﻨﻩﻪﻫﻬﻭﻮﻯﻰﻱﻲﻳﻴﻵﻶﻷﻸﻹﻺﻻﻼ'; + $this->assertEquals($expected, $result); + + $string = 'ﺱﺲﺳﺴﺵﺶﺷﺸﺹﺺﺻﺼﺽﺾﺿﻀﻁﻂﻃﻄﻅﻆﻇﻈﻉﻊﻋﻌﻍﻎﻏﻐﻑﻒﻓﻔﻕﻖﻗﻘﻙﻚﻛﻜﻝﻞﻟﻠﻡﻢﻣﻤﻥﻦﻧﻨﻩﻪﻫﻬﻭﻮﻯﻰﻱﻲﻳﻴﻵﻶﻷﻸﻹﻺﻻﻼ'; + $find = 'ﻞ'; + $result = Multibyte::stristr($string, $find, true); + $expected = 'ﺱﺲﺳﺴﺵﺶﺷﺸﺹﺺﺻﺼﺽﺾﺿﻀﻁﻂﻃﻄﻅﻆﻇﻈﻉﻊﻋﻌﻍﻎﻏﻐﻑﻒﻓﻔﻕﻖﻗﻘﻙﻚﻛﻜﻝ'; + $this->assertEquals($expected, $result); + + $string = 'abcdefghijklmnopqrstuvwxyz'; + $find = 'K'; + $result = Multibyte::stristr($string, $find); + $expected = 'klmnopqrstuvwxyz'; + $this->assertEquals($expected, $result); + + $string = 'abcdefghijklmnopqrstuvwxyz'; + $find = 'K'; + $result = Multibyte::stristr($string, $find, true); + $expected = 'abcdefghij'; + $this->assertEquals($expected, $result); + + $string = '。「」、・ヲァィゥェォャュョッーアイウエオカキク'; + $find = 'ア'; + $result = Multibyte::stristr($string, $find); + $expected = 'アイウエオカキク'; + $this->assertEquals($expected, $result); + + $string = '。「」、・ヲァィゥェォャュョッーアイウエオカキク'; + $find = 'ア'; + $result = Multibyte::stristr($string, $find, true); + $expected = '。「」、・ヲァィゥェォャュョッー'; + $this->assertEquals($expected, $result); + + $string = 'ケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン゙'; + $find = 'ハ'; + $result = Multibyte::stristr($string, $find); + $expected = 'ハヒフヘホマミムメモヤユヨラリルレロワン゙'; + $this->assertEquals($expected, $result); + + $string = 'ケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン゙'; + $find = 'ハ'; + $result = Multibyte::stristr($string, $find, true); + $expected = 'ケコサシスセソタチツテトナニヌネノ'; + $this->assertEquals($expected, $result); + + $string = 'Ĥēĺļŏ, Ŵőřļď!'; + $find = 'Ő'; + $result = Multibyte::stristr($string, $find); + $expected = 'őřļď!'; + $this->assertEquals($expected, $result); + + $string = 'Ĥēĺļŏ, Ŵőřļď!'; + $find = 'Ő'; + $result = Multibyte::stristr($string, $find, true); + $expected = 'Ĥēĺļŏ, Ŵ'; + $this->assertEquals($expected, $result); + + $string = 'Ĥēĺļŏ, Ŵőřļď!'; + $find = 'ĺļ'; + $result = Multibyte::stristr($string, $find, true); + $expected = 'Ĥē'; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'O'; + $result = Multibyte::stristr($string, $find); + $expected = 'o, World!'; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'O'; + $result = Multibyte::stristr($string, $find, true); + $expected = 'Hell'; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'Wo'; + $result = Multibyte::stristr($string, $find); + $expected = 'World!'; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'Wo'; + $result = Multibyte::stristr($string, $find, true); + $expected = 'Hello, '; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'll'; + $result = Multibyte::stristr($string, $find); + $expected = 'llo, World!'; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'll'; + $result = Multibyte::stristr($string, $find, true); + $expected = 'He'; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'rld'; + $result = Multibyte::stristr($string, $find); + $expected = 'rld!'; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'rld'; + $result = Multibyte::stristr($string, $find, true); + $expected = 'Hello, Wo'; + $this->assertEquals($expected, $result); + + $string = 'čini'; + $find = 'N'; + $result = Multibyte::stristr($string, $find); + $expected = 'ni'; + $this->assertEquals($expected, $result); + + $string = 'čini'; + $find = 'N'; + $result = Multibyte::stristr($string, $find, true); + $expected = 'či'; + $this->assertEquals($expected, $result); + + $string = 'moći'; + $find = 'Ć'; + $result = Multibyte::stristr($string, $find); + $expected = 'ći'; + $this->assertEquals($expected, $result); + + $string = 'moći'; + $find = 'Ć'; + $result = Multibyte::stristr($string, $find, true); + $expected = 'mo'; + $this->assertEquals($expected, $result); + + $string = 'državni'; + $find = 'Ž'; + $result = Multibyte::stristr($string, $find); + $expected = 'žavni'; + $this->assertEquals($expected, $result); + + $string = 'državni'; + $find = 'Ž'; + $result = Multibyte::stristr($string, $find, true); + $expected = 'dr'; + $this->assertEquals($expected, $result); + + $string = '把百度设为首页'; + $find = '设'; + $result = Multibyte::stristr($string, $find); + $expected = '设为首页'; + $this->assertEquals($expected, $result); + + $string = '把百度设为首页'; + $find = '设'; + $result = Multibyte::stristr($string, $find, true); + $expected = '把百度'; + $this->assertEquals($expected, $result); + + $string = '一二三周永龍'; + $find = '周'; + $result = Multibyte::stristr($string, $find); + $expected = '周永龍'; + $this->assertEquals($expected, $result); + + $string = '一二三周永龍'; + $find = '周'; + $result = Multibyte::stristr($string, $find, true); + $expected = '一二三'; + $this->assertEquals($expected, $result); + + $string = '一二三周永龍'; + $find = '二周'; + $result = Multibyte::stristr($string, $find); + $expected = false; + $this->assertEquals($expected, $result); + } + +/** + * testUsingMbStrlen method + * + * @return void + */ + public function testUsingMbStrlen() { + $string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; + $result = mb_strlen($string); + $expected = 36; + $this->assertEquals($expected, $result); + + $string = 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ'; + $result = mb_strlen($string); + $expected = 30; + $this->assertEquals($expected, $result); + + $string = 'ĀĂĄĆĈĊČĎĐĒĔĖĘĚĜĞĠĢĤĦĨĪĬĮIJĴĶĹĻĽĿŁŃŅŇŊŌŎŐŒŔŖŘŚŜŞŠŢŤŦŨŪŬŮŰŲŴŶŹŻŽ'; + $result = mb_strlen($string); + $expected = 61; + $this->assertEquals($expected, $result); + + $string = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'; + $result = mb_strlen($string); + $expected = 94; + $this->assertEquals($expected, $result); + + $string = '¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈ'; + $result = mb_strlen($string); + $expected = 40; + $this->assertEquals($expected, $result); + + $string = 'ÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬ'; + $result = mb_strlen($string); + $expected = 100; + $this->assertEquals($expected, $result); + + $string = 'ĭĮįİıIJijĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏƐ'; + $result = mb_strlen($string); + $expected = 100; + $this->assertEquals($expected, $result); + + $string = 'ƑƒƓƔƕƖƗƘƙƚƛƜƝƞƟƠơƢƣƤƥƦƧƨƩƪƫƬƭƮƯưƱƲƳƴƵƶƷƸƹƺƻƼƽƾƿǀǁǂǃDŽDždžLJLjljNJNjnjǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰDZDzdzǴ'; + $result = mb_strlen($string); + $expected = 100; + $this->assertEquals($expected, $result); + + $string = 'əɚɛɜɝɞɟɠɡɢɣɤɥɦɧɨɩɪɫɬɭɮɯɰɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿʀʁʂʃʄʅʆʇʈʉʊʋʌʍʎʏʐʑʒʓʔʕʖʗʘʙʚʛʜʝʞʟʠʡʢʣʤʥʦʧʨʩʪʫʬʭʮʯʰʱʲʳʴʵʶʷʸʹʺʻʼ'; + $result = mb_strlen($string); + $expected = 100; + $this->assertEquals($expected, $result); + + $string = 'ЀЁЂЃЄЅІЇЈЉЊЋЌЍЎЏАБВГДЕЖЗИЙКЛ'; + $result = mb_strlen($string); + $expected = 28; + $this->assertEquals($expected, $result); + + $string = 'МНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыь'; + $result = mb_strlen($string); + $expected = 49; + $this->assertEquals($expected, $result); + + $string = 'فقكلمنهوىيًٌٍَُ'; + $result = mb_strlen($string); + $expected = 15; + $this->assertEquals($expected, $result); + + $string = '✰✱✲✳✴✵✶✷✸✹✺✻✼✽✾✿❀❁❂❃❄❅❆❇❈❉❊❋❌❍❎❏❐❑❒❓❔❕❖❗❘❙❚❛❜❝❞'; + $result = mb_strlen($string); + $expected = 47; + $this->assertEquals($expected, $result); + + $string = '⺀⺁⺂⺃⺄⺅⺆⺇⺈⺉⺊⺋⺌⺍⺎⺏⺐⺑⺒⺓⺔⺕⺖⺗⺘⺙⺛⺜⺝⺞⺟⺠⺡⺢⺣⺤⺥⺦⺧⺨⺩⺪⺫⺬⺭⺮⺯⺰⺱⺲⺳⺴⺵⺶⺷⺸⺹⺺⺻⺼⺽⺾⺿⻀⻁⻂⻃⻄⻅⻆⻇⻈⻉⻊⻋⻌⻍⻎⻏⻐⻑⻒⻓⻔⻕⻖⻗⻘⻙⻚⻛⻜⻝⻞⻟⻠'; + $result = mb_strlen($string); + $expected = 96; + $this->assertEquals($expected, $result); + + $string = '⽅⽆⽇⽈⽉⽊⽋⽌⽍⽎⽏⽐⽑⽒⽓⽔⽕⽖⽗⽘⽙⽚⽛⽜⽝⽞⽟⽠⽡⽢⽣⽤⽥⽦⽧⽨⽩⽪⽫⽬⽭⽮⽯⽰⽱⽲⽳⽴⽵⽶⽷⽸⽹⽺⽻⽼⽽⽾⽿'; + $result = mb_strlen($string); + $expected = 59; + $this->assertEquals($expected, $result); + + $string = '눡눢눣눤눥눦눧눨눩눪눫눬눭눮눯눰눱눲눳눴눵눶눷눸눹눺눻눼눽눾눿뉀뉁뉂뉃뉄뉅뉆뉇뉈뉉뉊뉋뉌뉍뉎뉏뉐뉑뉒뉓뉔뉕뉖뉗뉘뉙뉚뉛뉜뉝뉞뉟뉠뉡뉢뉣뉤뉥뉦뉧뉨뉩뉪뉫뉬뉭뉮뉯뉰뉱뉲뉳뉴뉵뉶뉷뉸뉹뉺뉻뉼뉽뉾뉿늀늁늂늃늄'; + $result = mb_strlen($string); + $expected = 100; + $this->assertEquals($expected, $result); + + $string = 'ﹰﹱﹲﹳﹴ﹵ﹶﹷﹸﹹﹺﹻﹼﹽﹾﹿﺀﺁﺂﺃﺄﺅﺆﺇﺈﺉﺊﺋﺌﺍﺎﺏﺐﺑﺒﺓﺔﺕﺖﺗﺘﺙﺚﺛﺜﺝﺞﺟﺠﺡﺢﺣﺤﺥﺦﺧﺨﺩﺪﺫﺬﺭﺮﺯﺰ'; + $result = mb_strlen($string); + $expected = 65; + $this->assertEquals($expected, $result); + + $string = 'ﺱﺲﺳﺴﺵﺶﺷﺸﺹﺺﺻﺼﺽﺾﺿﻀﻁﻂﻃﻄﻅﻆﻇﻈﻉﻊﻋﻌﻍﻎﻏﻐﻑﻒﻓﻔﻕﻖﻗﻘﻙﻚﻛﻜﻝﻞﻟﻠﻡﻢﻣﻤﻥﻦﻧﻨﻩﻪﻫﻬﻭﻮﻯﻰﻱﻲﻳﻴﻵﻶﻷﻸﻹﻺﻻﻼ'; + $result = mb_strlen($string); + $expected = 76; + $this->assertEquals($expected, $result); + + $string = 'abcdefghijklmnopqrstuvwxyz'; + $result = mb_strlen($string); + $expected = 26; + $this->assertEquals($expected, $result); + + $string = '。「」、・ヲァィゥェォャュョッーアイウエオカキク'; + $result = mb_strlen($string); + $expected = 24; + $this->assertEquals($expected, $result); + + $string = 'ケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン゙'; + $result = mb_strlen($string); + $expected = 38; + $this->assertEquals($expected, $result); + + $string = 'Ĥēĺļŏ, Ŵőřļď!'; + $result = mb_strlen($string); + $expected = 13; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $result = mb_strlen($string); + $expected = 13; + $this->assertEquals($expected, $result); + + $string = 'čini'; + $result = mb_strlen($string); + $expected = 4; + $this->assertEquals($expected, $result); + + $string = 'moći'; + $result = mb_strlen($string); + $expected = 4; + $this->assertEquals($expected, $result); + + $string = 'državni'; + $result = mb_strlen($string); + $expected = 7; + $this->assertEquals($expected, $result); + + $string = '把百度设为首页'; + $result = mb_strlen($string); + $expected = 7; + $this->assertEquals($expected, $result); + + $string = '一二三周永龍'; + $result = mb_strlen($string); + $expected = 6; + $this->assertEquals($expected, $result); + } + +/** + * testMultibyteStrlen method + * + * @return void + */ + public function testMultibyteStrlen() { + $string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; + $result = Multibyte::strlen($string); + $expected = 36; + $this->assertEquals($expected, $result); + + $string = 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ'; + $result = Multibyte::strlen($string); + $expected = 30; + $this->assertEquals($expected, $result); + + $string = 'ĀĂĄĆĈĊČĎĐĒĔĖĘĚĜĞĠĢĤĦĨĪĬĮIJĴĶĹĻĽĿŁŃŅŇŊŌŎŐŒŔŖŘŚŜŞŠŢŤŦŨŪŬŮŰŲŴŶŹŻŽ'; + $result = Multibyte::strlen($string); + $expected = 61; + $this->assertEquals($expected, $result); + + $string = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'; + $result = Multibyte::strlen($string); + $expected = 94; + $this->assertEquals($expected, $result); + + $string = '¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈ'; + $result = Multibyte::strlen($string); + $expected = 40; + $this->assertEquals($expected, $result); + + $string = 'ÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬ'; + $result = Multibyte::strlen($string); + $expected = 100; + $this->assertEquals($expected, $result); + + $string = 'ĭĮįİıIJijĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏƐ'; + $result = Multibyte::strlen($string); + $expected = 100; + $this->assertEquals($expected, $result); + + $string = 'ƑƒƓƔƕƖƗƘƙƚƛƜƝƞƟƠơƢƣƤƥƦƧƨƩƪƫƬƭƮƯưƱƲƳƴƵƶƷƸƹƺƻƼƽƾƿǀǁǂǃDŽDždžLJLjljNJNjnjǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰDZDzdzǴ'; + $result = Multibyte::strlen($string); + $expected = 100; + $this->assertEquals($expected, $result); + + $string = 'əɚɛɜɝɞɟɠɡɢɣɤɥɦɧɨɩɪɫɬɭɮɯɰɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿʀʁʂʃʄʅʆʇʈʉʊʋʌʍʎʏʐʑʒʓʔʕʖʗʘʙʚʛʜʝʞʟʠʡʢʣʤʥʦʧʨʩʪʫʬʭʮʯʰʱʲʳʴʵʶʷʸʹʺʻʼ'; + $result = Multibyte::strlen($string); + $expected = 100; + $this->assertEquals($expected, $result); + + $string = 'ЀЁЂЃЄЅІЇЈЉЊЋЌЍЎЏАБВГДЕЖЗИЙКЛ'; + $result = Multibyte::strlen($string); + $expected = 28; + $this->assertEquals($expected, $result); + + $string = 'МНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыь'; + $result = Multibyte::strlen($string); + $expected = 49; + $this->assertEquals($expected, $result); + + $string = 'فقكلمنهوىيًٌٍَُ'; + $result = Multibyte::strlen($string); + $expected = 15; + $this->assertEquals($expected, $result); + + $string = '✰✱✲✳✴✵✶✷✸✹✺✻✼✽✾✿❀❁❂❃❄❅❆❇❈❉❊❋❌❍❎❏❐❑❒❓❔❕❖❗❘❙❚❛❜❝❞'; + $result = Multibyte::strlen($string); + $expected = 47; + $this->assertEquals($expected, $result); + + $string = '⺀⺁⺂⺃⺄⺅⺆⺇⺈⺉⺊⺋⺌⺍⺎⺏⺐⺑⺒⺓⺔⺕⺖⺗⺘⺙⺛⺜⺝⺞⺟⺠⺡⺢⺣⺤⺥⺦⺧⺨⺩⺪⺫⺬⺭⺮⺯⺰⺱⺲⺳⺴⺵⺶⺷⺸⺹⺺⺻⺼⺽⺾⺿⻀⻁⻂⻃⻄⻅⻆⻇⻈⻉⻊⻋⻌⻍⻎⻏⻐⻑⻒⻓⻔⻕⻖⻗⻘⻙⻚⻛⻜⻝⻞⻟⻠'; + $result = Multibyte::strlen($string); + $expected = 96; + $this->assertEquals($expected, $result); + + $string = '⽅⽆⽇⽈⽉⽊⽋⽌⽍⽎⽏⽐⽑⽒⽓⽔⽕⽖⽗⽘⽙⽚⽛⽜⽝⽞⽟⽠⽡⽢⽣⽤⽥⽦⽧⽨⽩⽪⽫⽬⽭⽮⽯⽰⽱⽲⽳⽴⽵⽶⽷⽸⽹⽺⽻⽼⽽⽾⽿'; + $result = Multibyte::strlen($string); + $expected = 59; + $this->assertEquals($expected, $result); + + $string = '눡눢눣눤눥눦눧눨눩눪눫눬눭눮눯눰눱눲눳눴눵눶눷눸눹눺눻눼눽눾눿뉀뉁뉂뉃뉄뉅뉆뉇뉈뉉뉊뉋뉌뉍뉎뉏뉐뉑뉒뉓뉔뉕뉖뉗뉘뉙뉚뉛뉜뉝뉞뉟뉠뉡뉢뉣뉤뉥뉦뉧뉨뉩뉪뉫뉬뉭뉮뉯뉰뉱뉲뉳뉴뉵뉶뉷뉸뉹뉺뉻뉼뉽뉾뉿늀늁늂늃늄'; + $result = Multibyte::strlen($string); + $expected = 100; + $this->assertEquals($expected, $result); + + $string = 'ﹰﹱﹲﹳﹴ﹵ﹶﹷﹸﹹﹺﹻﹼﹽﹾﹿﺀﺁﺂﺃﺄﺅﺆﺇﺈﺉﺊﺋﺌﺍﺎﺏﺐﺑﺒﺓﺔﺕﺖﺗﺘﺙﺚﺛﺜﺝﺞﺟﺠﺡﺢﺣﺤﺥﺦﺧﺨﺩﺪﺫﺬﺭﺮﺯﺰ'; + $result = Multibyte::strlen($string); + $expected = 65; + $this->assertEquals($expected, $result); + + $string = 'ﺱﺲﺳﺴﺵﺶﺷﺸﺹﺺﺻﺼﺽﺾﺿﻀﻁﻂﻃﻄﻅﻆﻇﻈﻉﻊﻋﻌﻍﻎﻏﻐﻑﻒﻓﻔﻕﻖﻗﻘﻙﻚﻛﻜﻝﻞﻟﻠﻡﻢﻣﻤﻥﻦﻧﻨﻩﻪﻫﻬﻭﻮﻯﻰﻱﻲﻳﻴﻵﻶﻷﻸﻹﻺﻻﻼ'; + $result = Multibyte::strlen($string); + $expected = 76; + $this->assertEquals($expected, $result); + + $string = 'abcdefghijklmnopqrstuvwxyz'; + $result = Multibyte::strlen($string); + $expected = 26; + $this->assertEquals($expected, $result); + + $string = '。「」、・ヲァィゥェォャュョッーアイウエオカキク'; + $result = Multibyte::strlen($string); + $expected = 24; + $this->assertEquals($expected, $result); + + $string = 'ケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン゙'; + $result = Multibyte::strlen($string); + $expected = 38; + $this->assertEquals($expected, $result); + + $string = 'Ĥēĺļŏ, Ŵőřļď!'; + $result = Multibyte::strlen($string); + $expected = 13; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $result = Multibyte::strlen($string); + $expected = 13; + $this->assertEquals($expected, $result); + + $string = 'čini'; + $result = Multibyte::strlen($string); + $expected = 4; + $this->assertEquals($expected, $result); + + $string = 'moći'; + $result = Multibyte::strlen($string); + $expected = 4; + $this->assertEquals($expected, $result); + + $string = 'državni'; + $result = Multibyte::strlen($string); + $expected = 7; + $this->assertEquals($expected, $result); + + $string = '把百度设为首页'; + $result = Multibyte::strlen($string); + $expected = 7; + $this->assertEquals($expected, $result); + + $string = '一二三周永龍'; + $result = Multibyte::strlen($string); + $expected = 6; + $this->assertEquals($expected, $result); + } + +/** + * testUsingMbStrpos method + * + * @return void + */ + public function testUsingMbStrpos() { + $string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; + $find = 'F'; + $result = mb_strpos($string, $find); + $expected = 5; + $this->assertEquals($expected, $result); + + $string = 'ABCDEFGHIJKLMNOPQFRSTUVWXYZ0123456789'; + $find = 'F'; + $result = mb_strpos($string, $find, 6); + $expected = 17; + $this->assertEquals($expected, $result); + + $string = 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ'; + $find = 'Å'; + $result = mb_strpos($string, $find); + $expected = 5; + $this->assertEquals($expected, $result); + + $string = 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÅÙÚÛÜÝÞ'; + $find = 'Å'; + $result = mb_strpos($string, $find, 6); + $expected = 24; + $this->assertEquals($expected, $result); + + $string = 'ĀĂĄĆĈĊČĎĐĒĔĖĘĚĜĞĠĢĤĦĨĪĬĮIJĴĶĹĻĽĿŁŃŅŇŊŌŎŐŒŔŖŘŚŜŞŠŢŤŦŨŪŬŮŰŲŴŶŹŻŽ'; + $find = 'Ċ'; + $result = mb_strpos($string, $find); + $expected = 5; + $this->assertEquals($expected, $result); + + $string = 'ĀĂĄĆĈĊČĎĐĒĔĖĘĚĜĞĠĢĤĦĨĪĬĮIJĴĶĹĻĽĿŁĊŃŅŇŊŌŎŐŒŔŖŘŚŜŞŠŢŤŦŨŪŬŮŰŲŴŶŹŻŽ'; + $find = 'Ċ'; + $result = mb_strpos($string, $find, 6); + $expected = 32; + $this->assertEquals($expected, $result); + + $string = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'; + $find = 'F'; + $result = mb_strpos($string, $find); + $expected = 37; + $this->assertEquals($expected, $result); + + $string = '¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈ'; + $find = 'µ'; + $result = mb_strpos($string, $find); + $expected = 20; + $this->assertEquals($expected, $result); + + $string = 'ÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬ'; + $find = 'é'; + $result = mb_strpos($string, $find); + $expected = 32; + $this->assertEquals($expected, $result); + + $string = 'ĭĮįİıIJijĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏƐ'; + $find = 'Ņ'; + $result = mb_strpos($string, $find); + $expected = 24; + $this->assertEquals($expected, $result); + + $string = 'ƑƒƓƔƕƖƗƘƙƚƛƜƝƞƟƠơƢƣƤƥƦƧƨƩƪƫƬƭƮƯưƱƲƳƴƵƶƷƸƹƺƻƼƽƾƿǀǁǂǃDŽDždžLJLjljNJNjnjǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰDZDzdzǴ'; + $find = 'Ƹ'; + $result = mb_strpos($string, $find); + $expected = 39; + $this->assertEquals($expected, $result); + + $string = 'ƑƒƓƔƕƖƗƘƙƚƛƜƝƞƟƠơƢƣƤƥƦƧƨƩƪƫƬƭƮƯưƱƲƳƴƵƶƷƸƹƺƻƼƽƾƿǀǁǂǃDŽDždžLJLjljNJNjnjǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰDZDzdzǴ'; + $find = 'ƹ'; + $result = mb_strpos($string, $find); + $expected = 40; + $this->assertEquals($expected, $result); + + $string = 'əɚɛɜɝɞɟɠɡɢɣɤɥɦɧɨɩɪɫɬɭɮɯɰɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿʀʁʂʃʄʅʆʇʈʉʊʋʌʍʎʏʐʑʒʓʔʕʖʗʘʙʚʛʜʝʞʟʠʡʢʣʤʥʦʧʨʩʪʫʬʭʮʯʰʱʲʳʴʵʶʷʸʹʺʻʼ'; + $find = 'ʀ'; + $result = mb_strpos($string, $find); + $expected = 39; + $this->assertEquals($expected, $result); + + $string = 'ЀЁЂЃЄЅІЇЈЉЊЋЌЍЎЏАБВГДЕЖЗИЙКЛ'; + $find = 'Ї'; + $result = mb_strpos($string, $find); + $expected = 7; + $this->assertEquals($expected, $result); + + $string = 'МНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыь'; + $find = 'Р'; + $result = mb_strpos($string, $find); + $expected = 4; + $this->assertEquals($expected, $result); + + $string = 'МНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыь'; + $find = 'р'; + $result = mb_strpos($string, $find, 5); + $expected = 36; + $this->assertEquals($expected, $result); + + $string = 'فقكلمنهوىيًٌٍَُ'; + $find = 'ن'; + $result = mb_strpos($string, $find); + $expected = 5; + $this->assertEquals($expected, $result); + + $string = '✰✱✲✳✴✵✶✷✸✹✺✻✼✽✾✿❀❁❂❃❄❅❆❇❈❉❊❋❌❍❎❏❐❑❒❓❔❕❖❗❘❙❚❛❜❝❞'; + $find = '✿'; + $result = mb_strpos($string, $find); + $expected = 15; + $this->assertEquals($expected, $result); + + $string = '⺀⺁⺂⺃⺄⺅⺆⺇⺈⺉⺊⺋⺌⺍⺎⺏⺐⺑⺒⺓⺔⺕⺖⺗⺘⺙⺛⺜⺝⺞⺟⺠⺡⺢⺣⺤⺥⺦⺧⺨⺩⺪⺫⺬⺭⺮⺯⺰⺱⺲⺳⺴⺵⺶⺷⺸⺹⺺⺻⺼⺽⺾⺿⻀⻁⻂⻃⻄⻅⻆⻇⻈⻉⻊⻋⻌⻍⻎⻏⻐⻑⻒⻓⻔⻕⻖⻗⻘⻙⻚⻛⻜⻝⻞⻟⻠'; + $find = '⺐'; + $result = mb_strpos($string, $find); + $expected = 16; + $this->assertEquals($expected, $result); + + $string = '⽅⽆⽇⽈⽉⽊⽋⽌⽍⽎⽏⽐⽑⽒⽓⽔⽕⽖⽗⽘⽙⽚⽛⽜⽝⽞⽟⽠⽡⽢⽣⽤⽥⽦⽧⽨⽩⽪⽫⽬⽭⽮⽯⽰⽱⽲⽳⽴⽵⽶⽷⽸⽹⽺⽻⽼⽽⽾⽿'; + $find = '⽤'; + $result = mb_strpos($string, $find); + $expected = 31; + $this->assertEquals($expected, $result); + + $string = '눡눢눣눤눥눦눧눨눩눪눫눬눭눮눯눰눱눲눳눴눵눶눷눸눹눺눻눼눽눾눿뉀뉁뉂뉃뉄뉅뉆뉇뉈뉉뉊뉋뉌뉍뉎뉏뉐뉑뉒뉓뉔뉕뉖뉗뉘뉙뉚뉛뉜뉝뉞뉟뉠뉡뉢뉣뉤뉥뉦뉧뉨뉩뉪뉫뉬뉭뉮뉯뉰뉱뉲뉳뉴뉵뉶뉷뉸뉹뉺뉻뉼뉽뉾뉿늀늁늂늃늄'; + $find = '눻'; + $result = mb_strpos($string, $find); + $expected = 26; + $this->assertEquals($expected, $result); + + $string = 'ﹰﹱﹲﹳﹴ﹵ﹶﹷﹸﹹﹺﹻﹼﹽﹾﹿﺀﺁﺂﺃﺄﺅﺆﺇﺈﺉﺊﺋﺌﺍﺎﺏﺐﺑﺒﺓﺔﺕﺖﺗﺘﺙﺚﺛﺜﺝﺞﺟﺠﺡﺢﺣﺤﺥﺦﺧﺨﺩﺪﺫﺬﺭﺮﺯﺰ'; + $find = 'ﺞ'; + $result = mb_strpos($string, $find); + $expected = 46; + $this->assertEquals($expected, $result); + + $string = 'ﺱﺲﺳﺴﺵﺶﺷﺸﺹﺺﺻﺼﺽﺾﺿﻀﻁﻂﻃﻄﻅﻆﻇﻈﻉﻊﻋﻌﻍﻎﻏﻐﻑﻒﻓﻔﻕﻖﻗﻘﻙﻚﻛﻜﻝﻞﻟﻠﻡﻢﻣﻤﻥﻦﻧﻨﻩﻪﻫﻬﻭﻮﻯﻰﻱﻲﻳﻴﻵﻶﻷﻸﻹﻺﻻﻼ'; + $find = 'ﻞ'; + $result = mb_strpos($string, $find); + $expected = 45; + $this->assertEquals($expected, $result); + + $string = 'abcdefghijklmnopqrstuvwxyz'; + $find = 'k'; + $result = mb_strpos($string, $find); + $expected = 10; + $this->assertEquals($expected, $result); + + $string = 'abcdefghijklmnopqrstuvwxyz'; + $find = 'k'; + $result = mb_strpos($string, $find); + $expected = 10; + $this->assertEquals($expected, $result); + + $string = '。「」、・ヲァィゥェォャュョッーアイウエオカキク'; + $find = 'ア'; + $result = mb_strpos($string, $find); + $expected = 16; + $this->assertEquals($expected, $result); + + $string = 'ケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン゙'; + $find = 'ハ'; + $result = mb_strpos($string, $find); + $expected = 17; + $this->assertEquals($expected, $result); + + $string = 'Ĥēĺļŏ, Ŵőřļď!'; + $find = 'ő'; + $result = mb_strpos($string, $find); + $expected = 8; + $this->assertEquals($expected, $result); + + $string = 'Ĥēĺļŏ, Ŵőřļď!'; + $find = 'ő'; + $result = mb_strpos($string, $find); + $expected = 8; + $this->assertEquals($expected, $result); + + $string = 'Ĥēĺļŏ, Ŵőřļď!'; + $find = 'őř'; + $result = mb_strpos($string, $find); + $expected = 8; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'o'; + $result = mb_strpos($string, $find); + $expected = 4; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'o'; + $result = mb_strpos($string, $find, 5); + $expected = 8; + $this->assertEquals($expected, $result); + + $string = 'čini'; + $find = 'n'; + $result = mb_strpos($string, $find); + $expected = 2; + $this->assertEquals($expected, $result); + + $string = 'čini'; + $find = 'n'; + $result = mb_strpos($string, $find); + $expected = 2; + $this->assertEquals($expected, $result); + + $string = 'moći'; + $find = 'ć'; + $result = mb_strpos($string, $find); + $expected = 2; + $this->assertEquals($expected, $result); + + $string = 'moći'; + $find = 'ć'; + $result = mb_strpos($string, $find); + $expected = 2; + $this->assertEquals($expected, $result); + + $string = 'državni'; + $find = 'ž'; + $result = mb_strpos($string, $find); + $expected = 2; + $this->assertEquals($expected, $result); + + $string = '把百度设为首页'; + $find = '设'; + $result = mb_strpos($string, $find); + $expected = 3; + $this->assertEquals($expected, $result); + + $string = '一二三周永龍'; + $find = '周'; + $result = mb_strpos($string, $find); + $expected = 3; + $this->assertEquals($expected, $result); + + $string = '一二三周永龍'; + $find = '一周'; + $result = mb_strpos($string, $find); + $expected = false; + $this->assertEquals($expected, $result); + } + +/** + * testMultibyteStrpos method + * + * @return void + */ + public function testMultibyteStrpos() { + $string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; + $find = 'F'; + $result = Multibyte::strpos($string, $find); + $expected = 5; + $this->assertEquals($expected, $result); + + $string = 'ABCDEFGHIJKLMNOPQFRSTUVWXYZ0123456789'; + $find = 'F'; + $result = Multibyte::strpos($string, $find, 6); + $expected = 17; + $this->assertEquals($expected, $result); + + $string = 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ'; + $find = 'Å'; + $result = Multibyte::strpos($string, $find); + $expected = 5; + $this->assertEquals($expected, $result); + + $string = 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÅÙÚÛÜÝÞ'; + $find = 'Å'; + $result = Multibyte::strpos($string, $find, 6); + $expected = 24; + $this->assertEquals($expected, $result); + + $string = 'ĀĂĄĆĈĊČĎĐĒĔĖĘĚĜĞĠĢĤĦĨĪĬĮIJĴĶĹĻĽĿŁŃŅŇŊŌŎŐŒŔŖŘŚŜŞŠŢŤŦŨŪŬŮŰŲŴŶŹŻŽ'; + $find = 'Ċ'; + $result = Multibyte::strpos($string, $find); + $expected = 5; + $this->assertEquals($expected, $result); + + $string = 'ĀĂĄĆĈĊČĎĐĒĔĖĘĚĜĞĠĢĤĦĨĪĬĮIJĴĶĹĻĽĿŁĊŃŅŇŊŌŎŐŒŔŖŘŚŜŞŠŢŤŦŨŪŬŮŰŲŴŶŹŻŽ'; + $find = 'Ċ'; + $result = Multibyte::strpos($string, $find, 6); + $expected = 32; + $this->assertEquals($expected, $result); + + $string = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'; + $find = 'F'; + $result = Multibyte::strpos($string, $find); + $expected = 37; + $this->assertEquals($expected, $result); + + $string = '¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈ'; + $find = 'µ'; + $result = Multibyte::strpos($string, $find); + $expected = 20; + $this->assertEquals($expected, $result); + + $string = 'ÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬ'; + $find = 'é'; + $result = Multibyte::strpos($string, $find); + $expected = 32; + $this->assertEquals($expected, $result); + + $string = 'ĭĮįİıIJijĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏƐ'; + $find = 'Ņ'; + $result = Multibyte::strpos($string, $find); + $expected = 24; + $this->assertEquals($expected, $result); + + $string = 'ƑƒƓƔƕƖƗƘƙƚƛƜƝƞƟƠơƢƣƤƥƦƧƨƩƪƫƬƭƮƯưƱƲƳƴƵƶƷƸƹƺƻƼƽƾƿǀǁǂǃDŽDždžLJLjljNJNjnjǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰDZDzdzǴ'; + $find = 'Ƹ'; + $result = Multibyte::strpos($string, $find); + $expected = 39; + $this->assertEquals($expected, $result); + + $string = 'ƑƒƓƔƕƖƗƘƙƚƛƜƝƞƟƠơƢƣƤƥƦƧƨƩƪƫƬƭƮƯưƱƲƳƴƵƶƷƸƹƺƻƼƽƾƿǀǁǂǃDŽDždžLJLjljNJNjnjǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰDZDzdzǴ'; + $find = 'ƹ'; + $result = Multibyte::strpos($string, $find); + $expected = 40; + $this->assertEquals($expected, $result); + + $string = 'əɚɛɜɝɞɟɠɡɢɣɤɥɦɧɨɩɪɫɬɭɮɯɰɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿʀʁʂʃʄʅʆʇʈʉʊʋʌʍʎʏʐʑʒʓʔʕʖʗʘʙʚʛʜʝʞʟʠʡʢʣʤʥʦʧʨʩʪʫʬʭʮʯʰʱʲʳʴʵʶʷʸʹʺʻʼ'; + $find = 'ʀ'; + $result = Multibyte::strpos($string, $find); + $expected = 39; + $this->assertEquals($expected, $result); + + $string = 'ЀЁЂЃЄЅІЇЈЉЊЋЌЍЎЏАБВГДЕЖЗИЙКЛ'; + $find = 'Ї'; + $result = Multibyte::strpos($string, $find); + $expected = 7; + $this->assertEquals($expected, $result); + + $string = 'МНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыь'; + $find = 'Р'; + $result = Multibyte::strpos($string, $find); + $expected = 4; + $this->assertEquals($expected, $result); + + $string = 'МНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыь'; + $find = 'р'; + $result = Multibyte::strpos($string, $find, 5); + $expected = 36; + $this->assertEquals($expected, $result); + + $string = 'فقكلمنهوىيًٌٍَُ'; + $find = 'ن'; + $result = Multibyte::strpos($string, $find); + $expected = 5; + $this->assertEquals($expected, $result); + + $string = '✰✱✲✳✴✵✶✷✸✹✺✻✼✽✾✿❀❁❂❃❄❅❆❇❈❉❊❋❌❍❎❏❐❑❒❓❔❕❖❗❘❙❚❛❜❝❞'; + $find = '✿'; + $result = Multibyte::strpos($string, $find); + $expected = 15; + $this->assertEquals($expected, $result); + + $string = '⺀⺁⺂⺃⺄⺅⺆⺇⺈⺉⺊⺋⺌⺍⺎⺏⺐⺑⺒⺓⺔⺕⺖⺗⺘⺙⺛⺜⺝⺞⺟⺠⺡⺢⺣⺤⺥⺦⺧⺨⺩⺪⺫⺬⺭⺮⺯⺰⺱⺲⺳⺴⺵⺶⺷⺸⺹⺺⺻⺼⺽⺾⺿⻀⻁⻂⻃⻄⻅⻆⻇⻈⻉⻊⻋⻌⻍⻎⻏⻐⻑⻒⻓⻔⻕⻖⻗⻘⻙⻚⻛⻜⻝⻞⻟⻠'; + $find = '⺐'; + $result = Multibyte::strpos($string, $find); + $expected = 16; + $this->assertEquals($expected, $result); + + $string = '⽅⽆⽇⽈⽉⽊⽋⽌⽍⽎⽏⽐⽑⽒⽓⽔⽕⽖⽗⽘⽙⽚⽛⽜⽝⽞⽟⽠⽡⽢⽣⽤⽥⽦⽧⽨⽩⽪⽫⽬⽭⽮⽯⽰⽱⽲⽳⽴⽵⽶⽷⽸⽹⽺⽻⽼⽽⽾⽿'; + $find = '⽤'; + $result = Multibyte::strpos($string, $find); + $expected = 31; + $this->assertEquals($expected, $result); + + $string = '눡눢눣눤눥눦눧눨눩눪눫눬눭눮눯눰눱눲눳눴눵눶눷눸눹눺눻눼눽눾눿뉀뉁뉂뉃뉄뉅뉆뉇뉈뉉뉊뉋뉌뉍뉎뉏뉐뉑뉒뉓뉔뉕뉖뉗뉘뉙뉚뉛뉜뉝뉞뉟뉠뉡뉢뉣뉤뉥뉦뉧뉨뉩뉪뉫뉬뉭뉮뉯뉰뉱뉲뉳뉴뉵뉶뉷뉸뉹뉺뉻뉼뉽뉾뉿늀늁늂늃늄'; + $find = '눻'; + $result = Multibyte::strpos($string, $find); + $expected = 26; + $this->assertEquals($expected, $result); + + $string = 'ﹰﹱﹲﹳﹴ﹵ﹶﹷﹸﹹﹺﹻﹼﹽﹾﹿﺀﺁﺂﺃﺄﺅﺆﺇﺈﺉﺊﺋﺌﺍﺎﺏﺐﺑﺒﺓﺔﺕﺖﺗﺘﺙﺚﺛﺜﺝﺞﺟﺠﺡﺢﺣﺤﺥﺦﺧﺨﺩﺪﺫﺬﺭﺮﺯﺰ'; + $find = 'ﺞ'; + $result = Multibyte::strpos($string, $find); + $expected = 46; + $this->assertEquals($expected, $result); + + $string = 'ﺱﺲﺳﺴﺵﺶﺷﺸﺹﺺﺻﺼﺽﺾﺿﻀﻁﻂﻃﻄﻅﻆﻇﻈﻉﻊﻋﻌﻍﻎﻏﻐﻑﻒﻓﻔﻕﻖﻗﻘﻙﻚﻛﻜﻝﻞﻟﻠﻡﻢﻣﻤﻥﻦﻧﻨﻩﻪﻫﻬﻭﻮﻯﻰﻱﻲﻳﻴﻵﻶﻷﻸﻹﻺﻻﻼ'; + $find = 'ﻞ'; + $result = Multibyte::strpos($string, $find); + $expected = 45; + $this->assertEquals($expected, $result); + + $string = 'abcdefghijklmnopqrstuvwxyz'; + $find = 'k'; + $result = Multibyte::strpos($string, $find); + $expected = 10; + $this->assertEquals($expected, $result); + + $string = 'abcdefghijklmnopqrstuvwxyz'; + $find = 'k'; + $result = Multibyte::strpos($string, $find); + $expected = 10; + $this->assertEquals($expected, $result); + + $string = '。「」、・ヲァィゥェォャュョッーアイウエオカキク'; + $find = 'ア'; + $result = Multibyte::strpos($string, $find); + $expected = 16; + $this->assertEquals($expected, $result); + + $string = 'ケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン゙'; + $find = 'ハ'; + $result = Multibyte::strpos($string, $find); + $expected = 17; + $this->assertEquals($expected, $result); + + $string = 'Ĥēĺļŏ, Ŵőřļď!'; + $find = 'ő'; + $result = Multibyte::strpos($string, $find); + $expected = 8; + $this->assertEquals($expected, $result); + + $string = 'Ĥēĺļŏ, Ŵőřļď!'; + $find = 'ő'; + $result = Multibyte::strpos($string, $find); + $expected = 8; + $this->assertEquals($expected, $result); + + $string = 'Ĥēĺļŏ, Ŵőřļď!'; + $find = 'őř'; + $result = Multibyte::strpos($string, $find); + $expected = 8; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'o'; + $result = Multibyte::strpos($string, $find); + $expected = 4; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'o'; + $result = Multibyte::strpos($string, $find, 5); + $expected = 8; + $this->assertEquals($expected, $result); + + $string = 'čini'; + $find = 'n'; + $result = Multibyte::strpos($string, $find); + $expected = 2; + $this->assertEquals($expected, $result); + + $string = 'čini'; + $find = 'n'; + $result = Multibyte::strpos($string, $find); + $expected = 2; + $this->assertEquals($expected, $result); + + $string = 'moći'; + $find = 'ć'; + $result = Multibyte::strpos($string, $find); + $expected = 2; + $this->assertEquals($expected, $result); + + $string = 'moći'; + $find = 'ć'; + $result = Multibyte::strpos($string, $find); + $expected = 2; + $this->assertEquals($expected, $result); + + $string = 'državni'; + $find = 'ž'; + $result = Multibyte::strpos($string, $find); + $expected = 2; + $this->assertEquals($expected, $result); + + $string = '把百度设为首页'; + $find = '设'; + $result = Multibyte::strpos($string, $find); + $expected = 3; + $this->assertEquals($expected, $result); + + $string = '一二三周永龍'; + $find = '周'; + $result = Multibyte::strpos($string, $find); + $expected = 3; + $this->assertEquals($expected, $result); + + $string = '一二三周永龍'; + $find = '一周'; + $result = Multibyte::strpos($string, $find); + $expected = false; + $this->assertEquals($expected, $result); + } + +/** + * testUsingMbStrrchr method + * + * @return void + */ + public function testUsingMbStrrchr() { + $string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; + $find = 'F'; + $result = mb_strrchr($string, $find); + $expected = 'FGHIJKLMNOPQRSTUVWXYZ0123456789'; + $this->assertEquals($expected, $result); + + $string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; + $find = 'F'; + $result = mb_strrchr($string, $find, true); + $expected = 'ABCDE'; + $this->assertEquals($expected, $result); + + $string = 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ'; + $find = 'Å'; + $result = mb_strrchr($string, $find); + $expected = 'ÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ'; + $this->assertEquals($expected, $result); + + $string = 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ'; + $find = 'Å'; + $result = mb_strrchr($string, $find, true); + $expected = 'ÀÁÂÃÄ'; + $this->assertEquals($expected, $result); + + $string = 'ĀĂĄĆĈĊČĎĐĒĔĖĘĚĜĞĠĢĤĦĨĪĬĮIJĴĶĹĻĽĿŁŃŅŇŊŌŎŐŒŔŖŘŚŜŞŠŢŤŦŨŪŬŮŰŲŴŶŹŻŽ'; + $find = 'Ċ'; + $result = mb_strrchr($string, $find); + $expected = 'ĊČĎĐĒĔĖĘĚĜĞĠĢĤĦĨĪĬĮIJĴĶĹĻĽĿŁŃŅŇŊŌŎŐŒŔŖŘŚŜŞŠŢŤŦŨŪŬŮŰŲŴŶŹŻŽ'; + $this->assertEquals($expected, $result); + + $string = 'ĀĂĄĆĈĊČĎĐĒĔĖĘĚĜĞĠĢĤĦĨĪĬĮIJĴĶĹĻĽĿŁŃŅŇŊŌŎŐŒŔŖŘŚŜŞŠŢŤŦŨŪŬŮŰŲŴŶŹŻŽ'; + $find = 'Ċ'; + $result = mb_strrchr($string, $find, true); + $expected = 'ĀĂĄĆĈ'; + $this->assertEquals($expected, $result); + + $string = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'; + $find = 'F'; + $result = mb_strrchr($string, $find); + $expected = 'FGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'; + $this->assertEquals($expected, $result); + + $string = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'; + $find = 'F'; + $result = mb_strrchr($string, $find, true); + $expected = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDE'; + $this->assertEquals($expected, $result); + + $string = '¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈ'; + $find = 'µ'; + $result = mb_strrchr($string, $find); + $expected = 'µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈ'; + $this->assertEquals($expected, $result); + + $string = '¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈ'; + $find = 'µ'; + $result = mb_strrchr($string, $find, true); + $expected = '¡¢£¤¥¦§¨©ª«¬­®¯°±²³´'; + $this->assertEquals($expected, $result); + + $string = 'ÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬ'; + $find = 'Þ'; + $result = mb_strrchr($string, $find); + $expected = 'Þßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬ'; + $this->assertEquals($expected, $result); + + $string = 'ÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬ'; + $find = 'Þ'; + $result = mb_strrchr($string, $find, true); + $expected = 'ÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝ'; + $this->assertEquals($expected, $result); + + $string = 'ĭĮįİıIJijĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏƐ'; + $find = 'Ņ'; + $result = mb_strrchr($string, $find); + $expected = 'ŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏƐ'; + $this->assertEquals($expected, $result); + + $string = 'ĭĮįİıIJijĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏƐ'; + $find = 'Ņ'; + $result = mb_strrchr($string, $find, true); + $expected = 'ĭĮįİıIJijĴĵĶķĸĹĺĻļĽľĿŀŁłŃń'; + $this->assertEquals($expected, $result); + + $string = 'ƑƒƓƔƕƖƗƘƙƚƛƜƝƞƟƠơƢƣƤƥƦƧƨƩƪƫƬƭƮƯưƱƲƳƴƵƶƷƸƹƺƻƼƽƾƿǀǁǂǃDŽDždžLJLjljNJNjnjǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰDZDzdzǴ'; + $find = 'Ƹ'; + $result = mb_strrchr($string, $find); + $expected = 'ƸƹƺƻƼƽƾƿǀǁǂǃDŽDždžLJLjljNJNjnjǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰDZDzdzǴ'; + $this->assertEquals($expected, $result); + + $find = 'Ƹ'; + $result = mb_strrchr($string, $find, true); + $expected = 'ƑƒƓƔƕƖƗƘƙƚƛƜƝƞƟƠơƢƣƤƥƦƧƨƩƪƫƬƭƮƯưƱƲƳƴƵƶƷ'; + $this->assertEquals($expected, $result); + + $string = 'əɚɛɜɝɞɟɠɡɢɣɤɥɦɧɨɩɪɫɬɭɮɯɰɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿʀʁʂʃʄʅʆʇʈʉʊʋʌʍʎʏʐʑʒʓʔʕʖʗʘʙʚʛʜʝʞʟʠʡʢʣʤʥʦʧʨʩʪʫʬʭʮʯʰʱʲʳʴʵʶʷʸʹʺʻʼ'; + $find = 'ʀ'; + $result = mb_strrchr($string, $find); + $expected = 'ʀʁʂʃʄʅʆʇʈʉʊʋʌʍʎʏʐʑʒʓʔʕʖʗʘʙʚʛʜʝʞʟʠʡʢʣʤʥʦʧʨʩʪʫʬʭʮʯʰʱʲʳʴʵʶʷʸʹʺʻʼ'; + $this->assertEquals($expected, $result); + + $string = 'əɚɛɜɝɞɟɠɡɢɣɤɥɦɧɨɩɪɫɬɭɮɯɰɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿʀʁʂʃʄʅʆʇʈʉʊʋʌʍʎʏʐʑʒʓʔʕʖʗʘʙʚʛʜʝʞʟʠʡʢʣʤʥʦʧʨʩʪʫʬʭʮʯʰʱʲʳʴʵʶʷʸʹʺʻʼ'; + $find = 'ʀ'; + $result = mb_strrchr($string, $find, true); + $expected = 'əɚɛɜɝɞɟɠɡɢɣɤɥɦɧɨɩɪɫɬɭɮɯɰɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿ'; + $this->assertEquals($expected, $result); + + $string = 'ЀЁЂЃЄЅІЇЈЉЊЋЌЍЎЏАБВГДЕЖЗИЙКЛ'; + $find = 'Ї'; + $result = mb_strrchr($string, $find); + $expected = 'ЇЈЉЊЋЌЍЎЏАБВГДЕЖЗИЙКЛ'; + $this->assertEquals($expected, $result); + + $string = 'ЀЁЂЃЄЅІЇЈЉЊЋЌЍЎЏАБВГДЕЖЗИЙКЛ'; + $find = 'Ї'; + $result = mb_strrchr($string, $find, true); + $expected = 'ЀЁЂЃЄЅІ'; + $this->assertEquals($expected, $result); + + $string = 'МНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыь'; + $find = 'Р'; + $result = mb_strrchr($string, $find); + $expected = 'РСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыь'; + $this->assertEquals($expected, $result); + + $string = 'МНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыь'; + $find = 'Р'; + $result = mb_strrchr($string, $find, true); + $expected = 'МНОП'; + $this->assertEquals($expected, $result); + + $string = 'فقكلمنهوىيًٌٍَُ'; + $find = 'ن'; + $result = mb_strrchr($string, $find); + $expected = 'نهوىيًٌٍَُ'; + $this->assertEquals($expected, $result); + + $string = 'فقكلمنهوىيًٌٍَُ'; + $find = 'ن'; + $result = mb_strrchr($string, $find, true); + $expected = 'فقكلم'; + $this->assertEquals($expected, $result); + + $string = '✰✱✲✳✴✵✶✷✸✹✺✻✼✽✾✿❀❁❂❃❄❅❆❇❈❉❊❋❌❍❎❏❐❑❒❓❔❕❖❗❘❙❚❛❜❝❞'; + $find = '✿'; + $result = mb_strrchr($string, $find); + $expected = '✿❀❁❂❃❄❅❆❇❈❉❊❋❌❍❎❏❐❑❒❓❔❕❖❗❘❙❚❛❜❝❞'; + $this->assertEquals($expected, $result); + + $string = '✰✱✲✳✴✵✶✷✸✹✺✻✼✽✾✿❀❁❂❃❄❅❆❇❈❉❊❋❌❍❎❏❐❑❒❓❔❕❖❗❘❙❚❛❜❝❞'; + $find = '✿'; + $result = mb_strrchr($string, $find, true); + $expected = '✰✱✲✳✴✵✶✷✸✹✺✻✼✽✾'; + $this->assertEquals($expected, $result); + + $string = '⺀⺁⺂⺃⺄⺅⺆⺇⺈⺉⺊⺋⺌⺍⺎⺏⺐⺑⺒⺓⺔⺕⺖⺗⺘⺙⺛⺜⺝⺞⺟⺠⺡⺢⺣⺤⺥⺦⺧⺨⺩⺪⺫⺬⺭⺮⺯⺰⺱⺲⺳⺴⺵⺶⺷⺸⺹⺺⺻⺼⺽⺾⺿⻀⻁⻂⻃⻄⻅⻆⻇⻈⻉⻊⻋⻌⻍⻎⻏⻐⻑⻒⻓⻔⻕⻖⻗⻘⻙⻚⻛⻜⻝⻞⻟⻠'; + $find = '⺐'; + $result = mb_strrchr($string, $find); + $expected = '⺐⺑⺒⺓⺔⺕⺖⺗⺘⺙⺛⺜⺝⺞⺟⺠⺡⺢⺣⺤⺥⺦⺧⺨⺩⺪⺫⺬⺭⺮⺯⺰⺱⺲⺳⺴⺵⺶⺷⺸⺹⺺⺻⺼⺽⺾⺿⻀⻁⻂⻃⻄⻅⻆⻇⻈⻉⻊⻋⻌⻍⻎⻏⻐⻑⻒⻓⻔⻕⻖⻗⻘⻙⻚⻛⻜⻝⻞⻟⻠'; + $this->assertEquals($expected, $result); + + $string = '⺀⺁⺂⺃⺄⺅⺆⺇⺈⺉⺊⺋⺌⺍⺎⺏⺐⺑⺒⺓⺔⺕⺖⺗⺘⺙⺛⺜⺝⺞⺟⺠⺡⺢⺣⺤⺥⺦⺧⺨⺩⺪⺫⺬⺭⺮⺯⺰⺱⺲⺳⺴⺵⺶⺷⺸⺹⺺⺻⺼⺽⺾⺿⻀⻁⻂⻃⻄⻅⻆⻇⻈⻉⻊⻋⻌⻍⻎⻏⻐⻑⻒⻓⻔⻕⻖⻗⻘⻙⻚⻛⻜⻝⻞⻟⻠'; + $find = '⺐'; + $result = mb_strrchr($string, $find, true); + $expected = '⺀⺁⺂⺃⺄⺅⺆⺇⺈⺉⺊⺋⺌⺍⺎⺏'; + $this->assertEquals($expected, $result); + + $string = '⽅⽆⽇⽈⽉⽊⽋⽌⽍⽎⽏⽐⽑⽒⽓⽔⽕⽖⽗⽘⽙⽚⽛⽜⽝⽞⽟⽠⽡⽢⽣⽤⽥⽦⽧⽨⽩⽪⽫⽬⽭⽮⽯⽰⽱⽲⽳⽴⽵⽶⽷⽸⽹⽺⽻⽼⽽⽾⽿'; + $find = '⽤'; + $result = mb_strrchr($string, $find); + $expected = '⽤⽥⽦⽧⽨⽩⽪⽫⽬⽭⽮⽯⽰⽱⽲⽳⽴⽵⽶⽷⽸⽹⽺⽻⽼⽽⽾⽿'; + $this->assertEquals($expected, $result); + + $string = '⽅⽆⽇⽈⽉⽊⽋⽌⽍⽎⽏⽐⽑⽒⽓⽔⽕⽖⽗⽘⽙⽚⽛⽜⽝⽞⽟⽠⽡⽢⽣⽤⽥⽦⽧⽨⽩⽪⽫⽬⽭⽮⽯⽰⽱⽲⽳⽴⽵⽶⽷⽸⽹⽺⽻⽼⽽⽾⽿'; + $find = '⽤'; + $result = mb_strrchr($string, $find, true); + $expected = '⽅⽆⽇⽈⽉⽊⽋⽌⽍⽎⽏⽐⽑⽒⽓⽔⽕⽖⽗⽘⽙⽚⽛⽜⽝⽞⽟⽠⽡⽢⽣'; + $this->assertEquals($expected, $result); + + $string = '눡눢눣눤눥눦눧눨눩눪눫눬눭눮눯눰눱눲눳눴눵눶눷눸눹눺눻눼눽눾눿뉀뉁뉂뉃뉄뉅뉆뉇뉈뉉뉊뉋뉌뉍뉎뉏뉐뉑뉒뉓뉔뉕뉖뉗뉘뉙뉚뉛뉜뉝뉞뉟뉠뉡뉢뉣뉤뉥뉦뉧뉨뉩뉪뉫뉬뉭뉮뉯뉰뉱뉲뉳뉴뉵뉶뉷뉸뉹뉺뉻뉼뉽뉾뉿늀늁늂늃늄'; + $find = '눻'; + $result = mb_strrchr($string, $find); + $expected = '눻눼눽눾눿뉀뉁뉂뉃뉄뉅뉆뉇뉈뉉뉊뉋뉌뉍뉎뉏뉐뉑뉒뉓뉔뉕뉖뉗뉘뉙뉚뉛뉜뉝뉞뉟뉠뉡뉢뉣뉤뉥뉦뉧뉨뉩뉪뉫뉬뉭뉮뉯뉰뉱뉲뉳뉴뉵뉶뉷뉸뉹뉺뉻뉼뉽뉾뉿늀늁늂늃늄'; + $this->assertEquals($expected, $result); + + $string = '눡눢눣눤눥눦눧눨눩눪눫눬눭눮눯눰눱눲눳눴눵눶눷눸눹눺눻눼눽눾눿뉀뉁뉂뉃뉄뉅뉆뉇뉈뉉뉊뉋뉌뉍뉎뉏뉐뉑뉒뉓뉔뉕뉖뉗뉘뉙뉚뉛뉜뉝뉞뉟뉠뉡뉢뉣뉤뉥뉦뉧뉨뉩뉪뉫뉬뉭뉮뉯뉰뉱뉲뉳뉴뉵뉶뉷뉸뉹뉺뉻뉼뉽뉾뉿늀늁늂늃늄'; + $find = '눻'; + $result = mb_strrchr($string, $find, true); + $expected = '눡눢눣눤눥눦눧눨눩눪눫눬눭눮눯눰눱눲눳눴눵눶눷눸눹눺'; + $this->assertEquals($expected, $result); + + $string = 'ﹰﹱﹲﹳﹴ﹵ﹶﹷﹸﹹﹺﹻﹼﹽﹾﹿﺀﺁﺂﺃﺄﺅﺆﺇﺈﺉﺊﺋﺌﺍﺎﺏﺐﺑﺒﺓﺔﺕﺖﺗﺘﺙﺚﺛﺜﺝﺞﺟﺠﺡﺢﺣﺤﺥﺦﺧﺨﺩﺪﺫﺬﺭﺮﺯﺰ'; + $find = 'ﺞ'; + $result = mb_strrchr($string, $find); + $expected = 'ﺞﺟﺠﺡﺢﺣﺤﺥﺦﺧﺨﺩﺪﺫﺬﺭﺮﺯﺰ'; + $this->assertEquals($expected, $result); + + $string = 'ﹰﹱﹲﹳﹴ﹵ﹶﹷﹸﹹﹺﹻﹼﹽﹾﹿﺀﺁﺂﺃﺄﺅﺆﺇﺈﺉﺊﺋﺌﺍﺎﺏﺐﺑﺒﺓﺔﺕﺖﺗﺘﺙﺚﺛﺜﺝﺞﺟﺠﺡﺢﺣﺤﺥﺦﺧﺨﺩﺪﺫﺬﺭﺮﺯﺰ'; + $find = 'ﺞ'; + $result = mb_strrchr($string, $find, true); + $expected = 'ﹰﹱﹲﹳﹴ﹵ﹶﹷﹸﹹﹺﹻﹼﹽﹾﹿﺀﺁﺂﺃﺄﺅﺆﺇﺈﺉﺊﺋﺌﺍﺎﺏﺐﺑﺒﺓﺔﺕﺖﺗﺘﺙﺚﺛﺜﺝ'; + $this->assertEquals($expected, $result); + + $string = 'ﺱﺲﺳﺴﺵﺶﺷﺸﺹﺺﺻﺼﺽﺾﺿﻀﻁﻂﻃﻄﻅﻆﻇﻈﻉﻊﻋﻌﻍﻎﻏﻐﻑﻒﻓﻔﻕﻖﻗﻘﻙﻚﻛﻜﻝﻞﻟﻠﻡﻢﻣﻤﻥﻦﻧﻨﻩﻪﻫﻬﻭﻮﻯﻰﻱﻲﻳﻴﻵﻶﻷﻸﻹﻺﻻﻼ'; + $find = 'ﻞ'; + $result = mb_strrchr($string, $find); + $expected = 'ﻞﻟﻠﻡﻢﻣﻤﻥﻦﻧﻨﻩﻪﻫﻬﻭﻮﻯﻰﻱﻲﻳﻴﻵﻶﻷﻸﻹﻺﻻﻼ'; + $this->assertEquals($expected, $result); + + $string = 'ﺱﺲﺳﺴﺵﺶﺷﺸﺹﺺﺻﺼﺽﺾﺿﻀﻁﻂﻃﻄﻅﻆﻇﻈﻉﻊﻋﻌﻍﻎﻏﻐﻑﻒﻓﻔﻕﻖﻗﻘﻙﻚﻛﻜﻝﻞﻟﻠﻡﻢﻣﻤﻥﻦﻧﻨﻩﻪﻫﻬﻭﻮﻯﻰﻱﻲﻳﻴﻵﻶﻷﻸﻹﻺﻻﻼ'; + $find = 'ﻞ'; + $result = mb_strrchr($string, $find, true); + $expected = 'ﺱﺲﺳﺴﺵﺶﺷﺸﺹﺺﺻﺼﺽﺾﺿﻀﻁﻂﻃﻄﻅﻆﻇﻈﻉﻊﻋﻌﻍﻎﻏﻐﻑﻒﻓﻔﻕﻖﻗﻘﻙﻚﻛﻜﻝ'; + $this->assertEquals($expected, $result); + + $string = 'abcdefghijklmnopqrstuvwxyz'; + $find = 'k'; + $result = mb_strrchr($string, $find); + $expected = 'klmnopqrstuvwxyz'; + $this->assertEquals($expected, $result); + + $string = 'abcdefghijklmnopqrstuvwxyz'; + $find = 'k'; + $result = mb_strrchr($string, $find, true); + $expected = 'abcdefghij'; + $this->assertEquals($expected, $result); + + $string = '。「」、・ヲァィゥェォャュョッーアイウエオカキク'; + $find = 'ア'; + $result = mb_strrchr($string, $find); + $expected = 'アイウエオカキク'; + $this->assertEquals($expected, $result); + + $string = '。「」、・ヲァィゥェォャュョッーアイウエオカキク'; + $find = 'ア'; + $result = mb_strrchr($string, $find, true); + $expected = '。「」、・ヲァィゥェォャュョッー'; + $this->assertEquals($expected, $result); + + $string = 'ケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン゙'; + $find = 'ハ'; + $result = mb_strrchr($string, $find); + $expected = 'ハヒフヘホマミムメモヤユヨラリルレロワン゙'; + $this->assertEquals($expected, $result); + + $string = 'ケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン゙'; + $find = 'ハ'; + $result = mb_strrchr($string, $find, true); + $expected = 'ケコサシスセソタチツテトナニヌネノ'; + $this->assertEquals($expected, $result); + + $string = 'Ĥēĺļŏ, Ŵőřļď!'; + $find = 'ő'; + $result = mb_strrchr($string, $find); + $expected = 'őřļď!'; + $this->assertEquals($expected, $result); + + $string = 'Ĥēĺļŏ, Ŵőřļď!'; + $find = 'ő'; + $result = mb_strrchr($string, $find, true); + $expected = 'Ĥēĺļŏ, Ŵ'; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'o'; + $result = mb_strrchr($string, $find); + $expected = 'orld!'; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'o'; + $result = mb_strrchr($string, $find, true); + $expected = 'Hello, W'; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'Wo'; + $result = mb_strrchr($string, $find); + $expected = 'World!'; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'Wo'; + $result = mb_strrchr($string, $find, true); + $expected = 'Hello, '; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'll'; + $result = mb_strrchr($string, $find); + $expected = 'llo, World!'; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'll'; + $result = mb_strrchr($string, $find, true); + $expected = 'He'; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'rld'; + $result = mb_strrchr($string, $find); + $expected = 'rld!'; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'rld'; + $result = mb_strrchr($string, $find, true); + $expected = 'Hello, Wo'; + $this->assertEquals($expected, $result); + + $string = 'čini'; + $find = 'n'; + $result = mb_strrchr($string, $find); + $expected = 'ni'; + $this->assertEquals($expected, $result); + + $string = 'čini'; + $find = 'n'; + $result = mb_strrchr($string, $find, true); + $expected = 'či'; + $this->assertEquals($expected, $result); + + $string = 'moći'; + $find = 'ć'; + $result = mb_strrchr($string, $find); + $expected = 'ći'; + $this->assertEquals($expected, $result); + + $string = 'moći'; + $find = 'ć'; + $result = mb_strrchr($string, $find, true); + $expected = 'mo'; + $this->assertEquals($expected, $result); + + $string = 'državni'; + $find = 'ž'; + $result = mb_strrchr($string, $find); + $expected = 'žavni'; + $this->assertEquals($expected, $result); + + $string = 'državni'; + $find = 'ž'; + $result = mb_strrchr($string, $find, true); + $expected = 'dr'; + $this->assertEquals($expected, $result); + + $string = '把百度设为首页'; + $find = '设'; + $result = mb_strrchr($string, $find); + $expected = '设为首页'; + $this->assertEquals($expected, $result); + + $string = '把百度设为首页'; + $find = '设'; + $result = mb_strrchr($string, $find, true); + $expected = '把百度'; + $this->assertEquals($expected, $result); + + $string = '一二三周永龍'; + $find = '周'; + $result = mb_strrchr($string, $find); + $expected = '周永龍'; + $this->assertEquals($expected, $result); + + $string = '一二三周永龍'; + $find = '周'; + $result = mb_strrchr($string, $find, true); + $expected = '一二三'; + $this->assertEquals($expected, $result); + + $string = '一二三周永龍'; + $find = '周龍'; + $result = mb_strrchr($string, $find, true); + $expected = false; + $this->assertEquals($expected, $result); + } + +/** + * testMultibyteStrrchr method + * + * @return void + */ + public function testMultibyteStrrchr() { + $string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; + $find = 'F'; + $result = Multibyte::strrchr($string, $find); + $expected = 'FGHIJKLMNOPQRSTUVWXYZ0123456789'; + $this->assertEquals($expected, $result); + + $string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; + $find = 'F'; + $result = Multibyte::strrchr($string, $find, true); + $expected = 'ABCDE'; + $this->assertEquals($expected, $result); + + $string = 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ'; + $find = 'Å'; + $result = Multibyte::strrchr($string, $find); + $expected = 'ÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ'; + $this->assertEquals($expected, $result); + + $string = 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ'; + $find = 'Å'; + $result = Multibyte::strrchr($string, $find, true); + $expected = 'ÀÁÂÃÄ'; + $this->assertEquals($expected, $result); + + $string = 'ĀĂĄĆĈĊČĎĐĒĔĖĘĚĜĞĠĢĤĦĨĪĬĮIJĴĶĹĻĽĿŁŃŅŇŊŌŎŐŒŔŖŘŚŜŞŠŢŤŦŨŪŬŮŰŲŴŶŹŻŽ'; + $find = 'Ċ'; + $result = Multibyte::strrchr($string, $find); + $expected = 'ĊČĎĐĒĔĖĘĚĜĞĠĢĤĦĨĪĬĮIJĴĶĹĻĽĿŁŃŅŇŊŌŎŐŒŔŖŘŚŜŞŠŢŤŦŨŪŬŮŰŲŴŶŹŻŽ'; + $this->assertEquals($expected, $result); + + $string = 'ĀĂĄĆĈĊČĎĐĒĔĖĘĚĜĞĠĢĤĦĨĪĬĮIJĴĶĹĻĽĿŁŃŅŇŊŌŎŐŒŔŖŘŚŜŞŠŢŤŦŨŪŬŮŰŲŴŶŹŻŽ'; + $find = 'Ċ'; + $result = Multibyte::strrchr($string, $find, true); + $expected = 'ĀĂĄĆĈ'; + $this->assertEquals($expected, $result); + + $string = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'; + $find = 'F'; + $result = Multibyte::strrchr($string, $find); + $expected = 'FGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'; + $this->assertEquals($expected, $result); + + $string = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'; + $find = 'F'; + $result = Multibyte::strrchr($string, $find, true); + $expected = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDE'; + $this->assertEquals($expected, $result); + + $string = '¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈ'; + $find = 'µ'; + $result = Multibyte::strrchr($string, $find); + $expected = 'µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈ'; + $this->assertEquals($expected, $result); + + $string = '¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈ'; + $find = 'µ'; + $result = Multibyte::strrchr($string, $find, true); + $expected = '¡¢£¤¥¦§¨©ª«¬­®¯°±²³´'; + $this->assertEquals($expected, $result); + + $string = 'ÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬ'; + $find = 'Þ'; + $result = Multibyte::strrchr($string, $find); + $expected = 'Þßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬ'; + $this->assertEquals($expected, $result); + + $string = 'ÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬ'; + $find = 'Þ'; + $result = Multibyte::strrchr($string, $find, true); + $expected = 'ÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝ'; + $this->assertEquals($expected, $result); + + $string = 'ĭĮįİıIJijĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏƐ'; + $find = 'Ņ'; + $result = Multibyte::strrchr($string, $find); + $expected = 'ŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏƐ'; + $this->assertEquals($expected, $result); + + $string = 'ĭĮįİıIJijĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏƐ'; + $find = 'Ņ'; + $result = Multibyte::strrchr($string, $find, true); + $expected = 'ĭĮįİıIJijĴĵĶķĸĹĺĻļĽľĿŀŁłŃń'; + $this->assertEquals($expected, $result); + + $string = 'ƑƒƓƔƕƖƗƘƙƚƛƜƝƞƟƠơƢƣƤƥƦƧƨƩƪƫƬƭƮƯưƱƲƳƴƵƶƷƸƹƺƻƼƽƾƿǀǁǂǃDŽDždžLJLjljNJNjnjǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰDZDzdzǴ'; + $find = 'Ƹ'; + $result = Multibyte::strrchr($string, $find); + $expected = 'ƸƹƺƻƼƽƾƿǀǁǂǃDŽDždžLJLjljNJNjnjǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰDZDzdzǴ'; + $this->assertEquals($expected, $result); + + $find = 'Ƹ'; + $result = Multibyte::strrchr($string, $find, true); + $expected = 'ƑƒƓƔƕƖƗƘƙƚƛƜƝƞƟƠơƢƣƤƥƦƧƨƩƪƫƬƭƮƯưƱƲƳƴƵƶƷ'; + $this->assertEquals($expected, $result); + + $string = 'əɚɛɜɝɞɟɠɡɢɣɤɥɦɧɨɩɪɫɬɭɮɯɰɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿʀʁʂʃʄʅʆʇʈʉʊʋʌʍʎʏʐʑʒʓʔʕʖʗʘʙʚʛʜʝʞʟʠʡʢʣʤʥʦʧʨʩʪʫʬʭʮʯʰʱʲʳʴʵʶʷʸʹʺʻʼ'; + $find = 'ʀ'; + $result = Multibyte::strrchr($string, $find); + $expected = 'ʀʁʂʃʄʅʆʇʈʉʊʋʌʍʎʏʐʑʒʓʔʕʖʗʘʙʚʛʜʝʞʟʠʡʢʣʤʥʦʧʨʩʪʫʬʭʮʯʰʱʲʳʴʵʶʷʸʹʺʻʼ'; + $this->assertEquals($expected, $result); + + $string = 'əɚɛɜɝɞɟɠɡɢɣɤɥɦɧɨɩɪɫɬɭɮɯɰɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿʀʁʂʃʄʅʆʇʈʉʊʋʌʍʎʏʐʑʒʓʔʕʖʗʘʙʚʛʜʝʞʟʠʡʢʣʤʥʦʧʨʩʪʫʬʭʮʯʰʱʲʳʴʵʶʷʸʹʺʻʼ'; + $find = 'ʀ'; + $result = Multibyte::strrchr($string, $find, true); + $expected = 'əɚɛɜɝɞɟɠɡɢɣɤɥɦɧɨɩɪɫɬɭɮɯɰɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿ'; + $this->assertEquals($expected, $result); + + $string = 'ЀЁЂЃЄЅІЇЈЉЊЋЌЍЎЏАБВГДЕЖЗИЙКЛ'; + $find = 'Ї'; + $result = Multibyte::strrchr($string, $find); + $expected = 'ЇЈЉЊЋЌЍЎЏАБВГДЕЖЗИЙКЛ'; + $this->assertEquals($expected, $result); + + $string = 'ЀЁЂЃЄЅІЇЈЉЊЋЌЍЎЏАБВГДЕЖЗИЙКЛ'; + $find = 'Ї'; + $result = Multibyte::strrchr($string, $find, true); + $expected = 'ЀЁЂЃЄЅІ'; + $this->assertEquals($expected, $result); + + $string = 'МНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыь'; + $find = 'Р'; + $result = Multibyte::strrchr($string, $find); + $expected = 'РСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыь'; + $this->assertEquals($expected, $result); + + $string = 'МНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыь'; + $find = 'Р'; + $result = Multibyte::strrchr($string, $find, true); + $expected = 'МНОП'; + $this->assertEquals($expected, $result); + + $string = 'فقكلمنهوىيًٌٍَُ'; + $find = 'ن'; + $result = Multibyte::strrchr($string, $find); + $expected = 'نهوىيًٌٍَُ'; + $this->assertEquals($expected, $result); + + $string = 'فقكلمنهوىيًٌٍَُ'; + $find = 'ن'; + $result = Multibyte::strrchr($string, $find, true); + $expected = 'فقكلم'; + $this->assertEquals($expected, $result); + + $string = '✰✱✲✳✴✵✶✷✸✹✺✻✼✽✾✿❀❁❂❃❄❅❆❇❈❉❊❋❌❍❎❏❐❑❒❓❔❕❖❗❘❙❚❛❜❝❞'; + $find = '✿'; + $result = Multibyte::strrchr($string, $find); + $expected = '✿❀❁❂❃❄❅❆❇❈❉❊❋❌❍❎❏❐❑❒❓❔❕❖❗❘❙❚❛❜❝❞'; + $this->assertEquals($expected, $result); + + $string = '✰✱✲✳✴✵✶✷✸✹✺✻✼✽✾✿❀❁❂❃❄❅❆❇❈❉❊❋❌❍❎❏❐❑❒❓❔❕❖❗❘❙❚❛❜❝❞'; + $find = '✿'; + $result = Multibyte::strrchr($string, $find, true); + $expected = '✰✱✲✳✴✵✶✷✸✹✺✻✼✽✾'; + $this->assertEquals($expected, $result); + + $string = '⺀⺁⺂⺃⺄⺅⺆⺇⺈⺉⺊⺋⺌⺍⺎⺏⺐⺑⺒⺓⺔⺕⺖⺗⺘⺙⺛⺜⺝⺞⺟⺠⺡⺢⺣⺤⺥⺦⺧⺨⺩⺪⺫⺬⺭⺮⺯⺰⺱⺲⺳⺴⺵⺶⺷⺸⺹⺺⺻⺼⺽⺾⺿⻀⻁⻂⻃⻄⻅⻆⻇⻈⻉⻊⻋⻌⻍⻎⻏⻐⻑⻒⻓⻔⻕⻖⻗⻘⻙⻚⻛⻜⻝⻞⻟⻠'; + $find = '⺐'; + $result = Multibyte::strrchr($string, $find); + $expected = '⺐⺑⺒⺓⺔⺕⺖⺗⺘⺙⺛⺜⺝⺞⺟⺠⺡⺢⺣⺤⺥⺦⺧⺨⺩⺪⺫⺬⺭⺮⺯⺰⺱⺲⺳⺴⺵⺶⺷⺸⺹⺺⺻⺼⺽⺾⺿⻀⻁⻂⻃⻄⻅⻆⻇⻈⻉⻊⻋⻌⻍⻎⻏⻐⻑⻒⻓⻔⻕⻖⻗⻘⻙⻚⻛⻜⻝⻞⻟⻠'; + $this->assertEquals($expected, $result); + + $string = '⺀⺁⺂⺃⺄⺅⺆⺇⺈⺉⺊⺋⺌⺍⺎⺏⺐⺑⺒⺓⺔⺕⺖⺗⺘⺙⺛⺜⺝⺞⺟⺠⺡⺢⺣⺤⺥⺦⺧⺨⺩⺪⺫⺬⺭⺮⺯⺰⺱⺲⺳⺴⺵⺶⺷⺸⺹⺺⺻⺼⺽⺾⺿⻀⻁⻂⻃⻄⻅⻆⻇⻈⻉⻊⻋⻌⻍⻎⻏⻐⻑⻒⻓⻔⻕⻖⻗⻘⻙⻚⻛⻜⻝⻞⻟⻠'; + $find = '⺐'; + $result = Multibyte::strrchr($string, $find, true); + $expected = '⺀⺁⺂⺃⺄⺅⺆⺇⺈⺉⺊⺋⺌⺍⺎⺏'; + $this->assertEquals($expected, $result); + + $string = '⽅⽆⽇⽈⽉⽊⽋⽌⽍⽎⽏⽐⽑⽒⽓⽔⽕⽖⽗⽘⽙⽚⽛⽜⽝⽞⽟⽠⽡⽢⽣⽤⽥⽦⽧⽨⽩⽪⽫⽬⽭⽮⽯⽰⽱⽲⽳⽴⽵⽶⽷⽸⽹⽺⽻⽼⽽⽾⽿'; + $find = '⽤'; + $result = Multibyte::strrchr($string, $find); + $expected = '⽤⽥⽦⽧⽨⽩⽪⽫⽬⽭⽮⽯⽰⽱⽲⽳⽴⽵⽶⽷⽸⽹⽺⽻⽼⽽⽾⽿'; + $this->assertEquals($expected, $result); + + $string = '⽅⽆⽇⽈⽉⽊⽋⽌⽍⽎⽏⽐⽑⽒⽓⽔⽕⽖⽗⽘⽙⽚⽛⽜⽝⽞⽟⽠⽡⽢⽣⽤⽥⽦⽧⽨⽩⽪⽫⽬⽭⽮⽯⽰⽱⽲⽳⽴⽵⽶⽷⽸⽹⽺⽻⽼⽽⽾⽿'; + $find = '⽤'; + $result = Multibyte::strrchr($string, $find, true); + $expected = '⽅⽆⽇⽈⽉⽊⽋⽌⽍⽎⽏⽐⽑⽒⽓⽔⽕⽖⽗⽘⽙⽚⽛⽜⽝⽞⽟⽠⽡⽢⽣'; + $this->assertEquals($expected, $result); + + $string = '눡눢눣눤눥눦눧눨눩눪눫눬눭눮눯눰눱눲눳눴눵눶눷눸눹눺눻눼눽눾눿뉀뉁뉂뉃뉄뉅뉆뉇뉈뉉뉊뉋뉌뉍뉎뉏뉐뉑뉒뉓뉔뉕뉖뉗뉘뉙뉚뉛뉜뉝뉞뉟뉠뉡뉢뉣뉤뉥뉦뉧뉨뉩뉪뉫뉬뉭뉮뉯뉰뉱뉲뉳뉴뉵뉶뉷뉸뉹뉺뉻뉼뉽뉾뉿늀늁늂늃늄'; + $find = '눻'; + $result = Multibyte::strrchr($string, $find); + $expected = '눻눼눽눾눿뉀뉁뉂뉃뉄뉅뉆뉇뉈뉉뉊뉋뉌뉍뉎뉏뉐뉑뉒뉓뉔뉕뉖뉗뉘뉙뉚뉛뉜뉝뉞뉟뉠뉡뉢뉣뉤뉥뉦뉧뉨뉩뉪뉫뉬뉭뉮뉯뉰뉱뉲뉳뉴뉵뉶뉷뉸뉹뉺뉻뉼뉽뉾뉿늀늁늂늃늄'; + $this->assertEquals($expected, $result); + + $string = '눡눢눣눤눥눦눧눨눩눪눫눬눭눮눯눰눱눲눳눴눵눶눷눸눹눺눻눼눽눾눿뉀뉁뉂뉃뉄뉅뉆뉇뉈뉉뉊뉋뉌뉍뉎뉏뉐뉑뉒뉓뉔뉕뉖뉗뉘뉙뉚뉛뉜뉝뉞뉟뉠뉡뉢뉣뉤뉥뉦뉧뉨뉩뉪뉫뉬뉭뉮뉯뉰뉱뉲뉳뉴뉵뉶뉷뉸뉹뉺뉻뉼뉽뉾뉿늀늁늂늃늄'; + $find = '눻'; + $result = Multibyte::strrchr($string, $find, true); + $expected = '눡눢눣눤눥눦눧눨눩눪눫눬눭눮눯눰눱눲눳눴눵눶눷눸눹눺'; + $this->assertEquals($expected, $result); + + $string = 'ﹰﹱﹲﹳﹴ﹵ﹶﹷﹸﹹﹺﹻﹼﹽﹾﹿﺀﺁﺂﺃﺄﺅﺆﺇﺈﺉﺊﺋﺌﺍﺎﺏﺐﺑﺒﺓﺔﺕﺖﺗﺘﺙﺚﺛﺜﺝﺞﺟﺠﺡﺢﺣﺤﺥﺦﺧﺨﺩﺪﺫﺬﺭﺮﺯﺰ'; + $find = 'ﺞ'; + $result = Multibyte::strrchr($string, $find); + $expected = 'ﺞﺟﺠﺡﺢﺣﺤﺥﺦﺧﺨﺩﺪﺫﺬﺭﺮﺯﺰ'; + $this->assertEquals($expected, $result); + + $string = 'ﹰﹱﹲﹳﹴ﹵ﹶﹷﹸﹹﹺﹻﹼﹽﹾﹿﺀﺁﺂﺃﺄﺅﺆﺇﺈﺉﺊﺋﺌﺍﺎﺏﺐﺑﺒﺓﺔﺕﺖﺗﺘﺙﺚﺛﺜﺝﺞﺟﺠﺡﺢﺣﺤﺥﺦﺧﺨﺩﺪﺫﺬﺭﺮﺯﺰ'; + $find = 'ﺞ'; + $result = Multibyte::strrchr($string, $find, true); + $expected = 'ﹰﹱﹲﹳﹴ﹵ﹶﹷﹸﹹﹺﹻﹼﹽﹾﹿﺀﺁﺂﺃﺄﺅﺆﺇﺈﺉﺊﺋﺌﺍﺎﺏﺐﺑﺒﺓﺔﺕﺖﺗﺘﺙﺚﺛﺜﺝ'; + $this->assertEquals($expected, $result); + + $string = 'ﺱﺲﺳﺴﺵﺶﺷﺸﺹﺺﺻﺼﺽﺾﺿﻀﻁﻂﻃﻄﻅﻆﻇﻈﻉﻊﻋﻌﻍﻎﻏﻐﻑﻒﻓﻔﻕﻖﻗﻘﻙﻚﻛﻜﻝﻞﻟﻠﻡﻢﻣﻤﻥﻦﻧﻨﻩﻪﻫﻬﻭﻮﻯﻰﻱﻲﻳﻴﻵﻶﻷﻸﻹﻺﻻﻼ'; + $find = 'ﻞ'; + $result = Multibyte::strrchr($string, $find); + $expected = 'ﻞﻟﻠﻡﻢﻣﻤﻥﻦﻧﻨﻩﻪﻫﻬﻭﻮﻯﻰﻱﻲﻳﻴﻵﻶﻷﻸﻹﻺﻻﻼ'; + $this->assertEquals($expected, $result); + + $string = 'ﺱﺲﺳﺴﺵﺶﺷﺸﺹﺺﺻﺼﺽﺾﺿﻀﻁﻂﻃﻄﻅﻆﻇﻈﻉﻊﻋﻌﻍﻎﻏﻐﻑﻒﻓﻔﻕﻖﻗﻘﻙﻚﻛﻜﻝﻞﻟﻠﻡﻢﻣﻤﻥﻦﻧﻨﻩﻪﻫﻬﻭﻮﻯﻰﻱﻲﻳﻴﻵﻶﻷﻸﻹﻺﻻﻼ'; + $find = 'ﻞ'; + $result = Multibyte::strrchr($string, $find, true); + $expected = 'ﺱﺲﺳﺴﺵﺶﺷﺸﺹﺺﺻﺼﺽﺾﺿﻀﻁﻂﻃﻄﻅﻆﻇﻈﻉﻊﻋﻌﻍﻎﻏﻐﻑﻒﻓﻔﻕﻖﻗﻘﻙﻚﻛﻜﻝ'; + $this->assertEquals($expected, $result); + + $string = 'abcdefghijklmnopqrstuvwxyz'; + $find = 'k'; + $result = Multibyte::strrchr($string, $find); + $expected = 'klmnopqrstuvwxyz'; + $this->assertEquals($expected, $result); + + $string = 'abcdefghijklmnopqrstuvwxyz'; + $find = 'k'; + $result = Multibyte::strrchr($string, $find, true); + $expected = 'abcdefghij'; + $this->assertEquals($expected, $result); + + $string = '。「」、・ヲァィゥェォャュョッーアイウエオカキク'; + $find = 'ア'; + $result = Multibyte::strrchr($string, $find); + $expected = 'アイウエオカキク'; + $this->assertEquals($expected, $result); + + $string = '。「」、・ヲァィゥェォャュョッーアイウエオカキク'; + $find = 'ア'; + $result = Multibyte::strrchr($string, $find, true); + $expected = '。「」、・ヲァィゥェォャュョッー'; + $this->assertEquals($expected, $result); + + $string = 'ケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン゙'; + $find = 'ハ'; + $result = Multibyte::strrchr($string, $find); + $expected = 'ハヒフヘホマミムメモヤユヨラリルレロワン゙'; + $this->assertEquals($expected, $result); + + $string = 'ケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン゙'; + $find = 'ハ'; + $result = Multibyte::strrchr($string, $find, true); + $expected = 'ケコサシスセソタチツテトナニヌネノ'; + $this->assertEquals($expected, $result); + + $string = 'Ĥēĺļŏ, Ŵőřļď!'; + $find = 'ő'; + $result = Multibyte::strrchr($string, $find); + $expected = 'őřļď!'; + $this->assertEquals($expected, $result); + + $string = 'Ĥēĺļŏ, Ŵőřļď!'; + $find = 'ő'; + $result = Multibyte::strrchr($string, $find, true); + $expected = 'Ĥēĺļŏ, Ŵ'; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'o'; + $result = Multibyte::strrchr($string, $find); + $expected = 'orld!'; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'o'; + $result = Multibyte::strrchr($string, $find, true); + $expected = 'Hello, W'; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'Wo'; + $result = Multibyte::strrchr($string, $find); + $expected = 'World!'; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'Wo'; + $result = Multibyte::strrchr($string, $find, true); + $expected = 'Hello, '; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'll'; + $result = Multibyte::strrchr($string, $find); + $expected = 'llo, World!'; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'll'; + $result = Multibyte::strrchr($string, $find, true); + $expected = 'He'; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'rld'; + $result = Multibyte::strrchr($string, $find); + $expected = 'rld!'; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'rld'; + $result = Multibyte::strrchr($string, $find, true); + $expected = 'Hello, Wo'; + $this->assertEquals($expected, $result); + + $string = 'čini'; + $find = 'n'; + $result = Multibyte::strrchr($string, $find); + $expected = 'ni'; + $this->assertEquals($expected, $result); + + $string = 'čini'; + $find = 'n'; + $result = Multibyte::strrchr($string, $find, true); + $expected = 'či'; + $this->assertEquals($expected, $result); + + $string = 'moći'; + $find = 'ć'; + $result = Multibyte::strrchr($string, $find); + $expected = 'ći'; + $this->assertEquals($expected, $result); + + $string = 'moći'; + $find = 'ć'; + $result = Multibyte::strrchr($string, $find, true); + $expected = 'mo'; + $this->assertEquals($expected, $result); + + $string = 'državni'; + $find = 'ž'; + $result = Multibyte::strrchr($string, $find); + $expected = 'žavni'; + $this->assertEquals($expected, $result); + + $string = 'državni'; + $find = 'ž'; + $result = Multibyte::strrchr($string, $find, true); + $expected = 'dr'; + $this->assertEquals($expected, $result); + + $string = '把百度设为首页'; + $find = '设'; + $result = Multibyte::strrchr($string, $find); + $expected = '设为首页'; + $this->assertEquals($expected, $result); + + $string = '把百度设为首页'; + $find = '设'; + $result = Multibyte::strrchr($string, $find, true); + $expected = '把百度'; + $this->assertEquals($expected, $result); + + $string = '一二三周永龍'; + $find = '周'; + $result = Multibyte::strrchr($string, $find); + $expected = '周永龍'; + $this->assertEquals($expected, $result); + + $string = '一二三周永龍'; + $find = '周'; + $result = Multibyte::strrchr($string, $find, true); + $expected = '一二三'; + $this->assertEquals($expected, $result); + + $string = '一二三周永龍'; + $find = '周龍'; + $result = Multibyte::strrchr($string, $find, true); + $expected = false; + $this->assertEquals($expected, $result); + } + +/** + * testUsingMbStrrichr method + * + * @return void + */ + public function testUsingMbStrrichr() { + $string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; + $find = 'F'; + $result = mb_strrichr($string, $find); + $expected = 'FGHIJKLMNOPQRSTUVWXYZ0123456789'; + $this->assertEquals($expected, $result); + + $string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; + $find = 'F'; + $result = mb_strrichr($string, $find, true); + $expected = 'ABCDE'; + $this->assertEquals($expected, $result); + + $string = 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ'; + $find = 'Å'; + $result = mb_strrichr($string, $find); + $expected = 'ÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ'; + $this->assertEquals($expected, $result); + + $string = 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ'; + $find = 'Å'; + $result = mb_strrichr($string, $find, true); + $expected = 'ÀÁÂÃÄ'; + $this->assertEquals($expected, $result); + + $string = 'ĀĂĄĆĈĊČĎĐĒĔĖĘĚĜĞĠĢĤĦĨĪĬĮIJĴĶĹĻĽĿŁŃŅŇŊŌŎŐŒŔŖŘŚŜŞŠŢŤŦŨŪŬŮŰŲŴŶŹŻŽ'; + $find = 'Ċ'; + $result = mb_strrichr($string, $find); + $expected = 'ĊČĎĐĒĔĖĘĚĜĞĠĢĤĦĨĪĬĮIJĴĶĹĻĽĿŁŃŅŇŊŌŎŐŒŔŖŘŚŜŞŠŢŤŦŨŪŬŮŰŲŴŶŹŻŽ'; + $this->assertEquals($expected, $result); + + $string = 'ĀĂĄĆĈĊČĎĐĒĔĖĘĚĜĞĠĢĤĦĨĪĬĮIJĴĶĹĻĽĿŁŃŅŇŊŌŎŐŒŔŖŘŚŜŞŠŢŤŦŨŪŬŮŰŲŴŶŹŻŽ'; + $find = 'Ċ'; + $result = mb_strrichr($string, $find, true); + $expected = 'ĀĂĄĆĈ'; + $this->assertEquals($expected, $result); + + $string = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'; + $find = 'F'; + $result = mb_strrichr($string, $find); + $expected = 'fghijklmnopqrstuvwxyz{|}~'; + $this->assertEquals($expected, $result); + + $string = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'; + $find = 'F'; + $result = mb_strrichr($string, $find, true); + $expected = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcde'; + $this->assertEquals($expected, $result); + + $string = '¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈ'; + $find = 'µ'; + $result = mb_strrichr($string, $find); + $expected = 'µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈ'; + $this->assertEquals($expected, $result); + + $string = '¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈ'; + $find = 'µ'; + $result = mb_strrichr($string, $find, true); + $expected = '¡¢£¤¥¦§¨©ª«¬­®¯°±²³´'; + $this->assertEquals($expected, $result); + + $string = 'ÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬ'; + $find = 'Þ'; + $result = mb_strrichr($string, $find); + $expected = 'þÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬ'; + $this->assertEquals($expected, $result); + + $string = 'ÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬ'; + $find = 'Þ'; + $result = mb_strrichr($string, $find, true); + $expected = 'ÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüý'; + $this->assertEquals($expected, $result); + + $string = 'ĭĮįİıIJijĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏƐ'; + $find = 'Ņ'; + $result = mb_strrichr($string, $find); + $expected = 'ņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏƐ'; + $this->assertEquals($expected, $result); + + $string = 'ĭĮįİıIJijĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏƐ'; + $find = 'Ņ'; + $result = mb_strrichr($string, $find, true); + $expected = 'ĭĮįİıIJijĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅ'; + $this->assertEquals($expected, $result); + + $string = 'ƑƒƓƔƕƖƗƘƙƚƛƜƝƞƟƠơƢƣƤƥƦƧƨƩƪƫƬƭƮƯưƱƲƳƴƵƶƷƸƹƺƻƼƽƾƿǀǁǂǃDŽDždžLJLjljNJNjnjǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰDZDzdzǴ'; + $find = 'Ƹ'; + $result = mb_strrichr($string, $find); + $expected = 'ƹƺƻƼƽƾƿǀǁǂǃDŽDždžLJLjljNJNjnjǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰDZDzdzǴ'; + $this->assertEquals($expected, $result); + + $find = 'Ƹ'; + $result = mb_strrichr($string, $find, true); + $expected = 'ƑƒƓƔƕƖƗƘƙƚƛƜƝƞƟƠơƢƣƤƥƦƧƨƩƪƫƬƭƮƯưƱƲƳƴƵƶƷƸ'; + $this->assertEquals($expected, $result); + + $string = 'əɚɛɜɝɞɟɠɡɢɣɤɥɦɧɨɩɪɫɬɭɮɯɰɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿʀʁʂʃʄʅʆʇʈʉʊʋʌʍʎʏʐʑʒʓʔʕʖʗʘʙʚʛʜʝʞʟʠʡʢʣʤʥʦʧʨʩʪʫʬʭʮʯʰʱʲʳʴʵʶʷʸʹʺʻʼ'; + $find = 'ʀ'; + $result = mb_strrichr($string, $find); + $expected = 'ʀʁʂʃʄʅʆʇʈʉʊʋʌʍʎʏʐʑʒʓʔʕʖʗʘʙʚʛʜʝʞʟʠʡʢʣʤʥʦʧʨʩʪʫʬʭʮʯʰʱʲʳʴʵʶʷʸʹʺʻʼ'; + $this->assertEquals($expected, $result); + + $string = 'əɚɛɜɝɞɟɠɡɢɣɤɥɦɧɨɩɪɫɬɭɮɯɰɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿʀʁʂʃʄʅʆʇʈʉʊʋʌʍʎʏʐʑʒʓʔʕʖʗʘʙʚʛʜʝʞʟʠʡʢʣʤʥʦʧʨʩʪʫʬʭʮʯʰʱʲʳʴʵʶʷʸʹʺʻʼ'; + $find = 'ʀ'; + $result = mb_strrichr($string, $find, true); + $expected = 'əɚɛɜɝɞɟɠɡɢɣɤɥɦɧɨɩɪɫɬɭɮɯɰɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿ'; + $this->assertEquals($expected, $result); + + $string = 'ЀЁЂЃЄЅІЇЈЉЊЋЌЍЎЏАБВГДЕЖЗИЙКЛ'; + $find = 'Ї'; + $result = mb_strrichr($string, $find); + $expected = 'ЇЈЉЊЋЌЍЎЏАБВГДЕЖЗИЙКЛ'; + $this->assertEquals($expected, $result); + + $string = 'ЀЁЂЃЄЅІЇЈЉЊЋЌЍЎЏАБВГДЕЖЗИЙКЛ'; + $find = 'Ї'; + $result = mb_strrichr($string, $find, true); + $expected = 'ЀЁЂЃЄЅІ'; + $this->assertEquals($expected, $result); + + $string = 'МНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыь'; + $find = 'Р'; + $result = mb_strrichr($string, $find); + $expected = 'рстуфхцчшщъыь'; + $this->assertEquals($expected, $result); + + $string = 'МНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп'; + $find = 'Р'; + $result = mb_strrichr($string, $find, true); + $expected = 'МНОП'; + $this->assertEquals($expected, $result); + + $string = 'فقكلمنهوىيًٌٍَُ'; + $find = 'ن'; + $result = mb_strrichr($string, $find); + $expected = 'نهوىيًٌٍَُ'; + $this->assertEquals($expected, $result); + + $string = 'فقكلمنهوىيًٌٍَُ'; + $find = 'ن'; + $result = mb_strrichr($string, $find, true); + $expected = 'فقكلم'; + $this->assertEquals($expected, $result); + + $string = '✰✱✲✳✴✵✶✷✸✹✺✻✼✽✾✿❀❁❂❃❄❅❆❇❈❉❊❋❌❍❎❏❐❑❒❓❔❕❖❗❘❙❚❛❜❝❞'; + $find = '✿'; + $result = mb_strrichr($string, $find); + $expected = '✿❀❁❂❃❄❅❆❇❈❉❊❋❌❍❎❏❐❑❒❓❔❕❖❗❘❙❚❛❜❝❞'; + $this->assertEquals($expected, $result); + + $string = '✰✱✲✳✴✵✶✷✸✹✺✻✼✽✾✿❀❁❂❃❄❅❆❇❈❉❊❋❌❍❎❏❐❑❒❓❔❕❖❗❘❙❚❛❜❝❞'; + $find = '✿'; + $result = mb_strrichr($string, $find, true); + $expected = '✰✱✲✳✴✵✶✷✸✹✺✻✼✽✾'; + $this->assertEquals($expected, $result); + + $string = '⺀⺁⺂⺃⺄⺅⺆⺇⺈⺉⺊⺋⺌⺍⺎⺏⺐⺑⺒⺓⺔⺕⺖⺗⺘⺙⺛⺜⺝⺞⺟⺠⺡⺢⺣⺤⺥⺦⺧⺨⺩⺪⺫⺬⺭⺮⺯⺰⺱⺲⺳⺴⺵⺶⺷⺸⺹⺺⺻⺼⺽⺾⺿⻀⻁⻂⻃⻄⻅⻆⻇⻈⻉⻊⻋⻌⻍⻎⻏⻐⻑⻒⻓⻔⻕⻖⻗⻘⻙⻚⻛⻜⻝⻞⻟⻠'; + $find = '⺐'; + $result = mb_strrichr($string, $find); + $expected = '⺐⺑⺒⺓⺔⺕⺖⺗⺘⺙⺛⺜⺝⺞⺟⺠⺡⺢⺣⺤⺥⺦⺧⺨⺩⺪⺫⺬⺭⺮⺯⺰⺱⺲⺳⺴⺵⺶⺷⺸⺹⺺⺻⺼⺽⺾⺿⻀⻁⻂⻃⻄⻅⻆⻇⻈⻉⻊⻋⻌⻍⻎⻏⻐⻑⻒⻓⻔⻕⻖⻗⻘⻙⻚⻛⻜⻝⻞⻟⻠'; + $this->assertEquals($expected, $result); + + $string = '⺀⺁⺂⺃⺄⺅⺆⺇⺈⺉⺊⺋⺌⺍⺎⺏⺐⺑⺒⺓⺔⺕⺖⺗⺘⺙⺛⺜⺝⺞⺟⺠⺡⺢⺣⺤⺥⺦⺧⺨⺩⺪⺫⺬⺭⺮⺯⺰⺱⺲⺳⺴⺵⺶⺷⺸⺹⺺⺻⺼⺽⺾⺿⻀⻁⻂⻃⻄⻅⻆⻇⻈⻉⻊⻋⻌⻍⻎⻏⻐⻑⻒⻓⻔⻕⻖⻗⻘⻙⻚⻛⻜⻝⻞⻟⻠'; + $find = '⺐'; + $result = mb_strrichr($string, $find, true); + $expected = '⺀⺁⺂⺃⺄⺅⺆⺇⺈⺉⺊⺋⺌⺍⺎⺏'; + $this->assertEquals($expected, $result); + + $string = '⽅⽆⽇⽈⽉⽊⽋⽌⽍⽎⽏⽐⽑⽒⽓⽔⽕⽖⽗⽘⽙⽚⽛⽜⽝⽞⽟⽠⽡⽢⽣⽤⽥⽦⽧⽨⽩⽪⽫⽬⽭⽮⽯⽰⽱⽲⽳⽴⽵⽶⽷⽸⽹⽺⽻⽼⽽⽾⽿'; + $find = '⽤'; + $result = mb_strrichr($string, $find); + $expected = '⽤⽥⽦⽧⽨⽩⽪⽫⽬⽭⽮⽯⽰⽱⽲⽳⽴⽵⽶⽷⽸⽹⽺⽻⽼⽽⽾⽿'; + $this->assertEquals($expected, $result); + + $string = '⽅⽆⽇⽈⽉⽊⽋⽌⽍⽎⽏⽐⽑⽒⽓⽔⽕⽖⽗⽘⽙⽚⽛⽜⽝⽞⽟⽠⽡⽢⽣⽤⽥⽦⽧⽨⽩⽪⽫⽬⽭⽮⽯⽰⽱⽲⽳⽴⽵⽶⽷⽸⽹⽺⽻⽼⽽⽾⽿'; + $find = '⽤'; + $result = mb_strrichr($string, $find, true); + $expected = '⽅⽆⽇⽈⽉⽊⽋⽌⽍⽎⽏⽐⽑⽒⽓⽔⽕⽖⽗⽘⽙⽚⽛⽜⽝⽞⽟⽠⽡⽢⽣'; + $this->assertEquals($expected, $result); + + $string = '눡눢눣눤눥눦눧눨눩눪눫눬눭눮눯눰눱눲눳눴눵눶눷눸눹눺눻눼눽눾눿뉀뉁뉂뉃뉄뉅뉆뉇뉈뉉뉊뉋뉌뉍뉎뉏뉐뉑뉒뉓뉔뉕뉖뉗뉘뉙뉚뉛뉜뉝뉞뉟뉠뉡뉢뉣뉤뉥뉦뉧뉨뉩뉪뉫뉬뉭뉮뉯뉰뉱뉲뉳뉴뉵뉶뉷뉸뉹뉺뉻뉼뉽뉾뉿늀늁늂늃늄'; + $find = '눻'; + $result = mb_strrichr($string, $find); + $expected = '눻눼눽눾눿뉀뉁뉂뉃뉄뉅뉆뉇뉈뉉뉊뉋뉌뉍뉎뉏뉐뉑뉒뉓뉔뉕뉖뉗뉘뉙뉚뉛뉜뉝뉞뉟뉠뉡뉢뉣뉤뉥뉦뉧뉨뉩뉪뉫뉬뉭뉮뉯뉰뉱뉲뉳뉴뉵뉶뉷뉸뉹뉺뉻뉼뉽뉾뉿늀늁늂늃늄'; + $this->assertEquals($expected, $result); + + $string = '눡눢눣눤눥눦눧눨눩눪눫눬눭눮눯눰눱눲눳눴눵눶눷눸눹눺눻눼눽눾눿뉀뉁뉂뉃뉄뉅뉆뉇뉈뉉뉊뉋뉌뉍뉎뉏뉐뉑뉒뉓뉔뉕뉖뉗뉘뉙뉚뉛뉜뉝뉞뉟뉠뉡뉢뉣뉤뉥뉦뉧뉨뉩뉪뉫뉬뉭뉮뉯뉰뉱뉲뉳뉴뉵뉶뉷뉸뉹뉺뉻뉼뉽뉾뉿늀늁늂늃늄'; + $find = '눻'; + $result = mb_strrichr($string, $find, true); + $expected = '눡눢눣눤눥눦눧눨눩눪눫눬눭눮눯눰눱눲눳눴눵눶눷눸눹눺'; + $this->assertEquals($expected, $result); + + $string = 'ﹰﹱﹲﹳﹴ﹵ﹶﹷﹸﹹﹺﹻﹼﹽﹾﹿﺀﺁﺂﺃﺄﺅﺆﺇﺈﺉﺊﺋﺌﺍﺎﺏﺐﺑﺒﺓﺔﺕﺖﺗﺘﺙﺚﺛﺜﺝﺞﺟﺠﺡﺢﺣﺤﺥﺦﺧﺨﺩﺪﺫﺬﺭﺮﺯﺰ'; + $find = 'ﺞ'; + $result = mb_strrichr($string, $find); + $expected = 'ﺞﺟﺠﺡﺢﺣﺤﺥﺦﺧﺨﺩﺪﺫﺬﺭﺮﺯﺰ'; + $this->assertEquals($expected, $result); + + $string = 'ﹰﹱﹲﹳﹴ﹵ﹶﹷﹸﹹﹺﹻﹼﹽﹾﹿﺀﺁﺂﺃﺄﺅﺆﺇﺈﺉﺊﺋﺌﺍﺎﺏﺐﺑﺒﺓﺔﺕﺖﺗﺘﺙﺚﺛﺜﺝﺞﺟﺠﺡﺢﺣﺤﺥﺦﺧﺨﺩﺪﺫﺬﺭﺮﺯﺰ'; + $find = 'ﺞ'; + $result = mb_strrichr($string, $find, true); + $expected = 'ﹰﹱﹲﹳﹴ﹵ﹶﹷﹸﹹﹺﹻﹼﹽﹾﹿﺀﺁﺂﺃﺄﺅﺆﺇﺈﺉﺊﺋﺌﺍﺎﺏﺐﺑﺒﺓﺔﺕﺖﺗﺘﺙﺚﺛﺜﺝ'; + $this->assertEquals($expected, $result); + + $string = 'ﺱﺲﺳﺴﺵﺶﺷﺸﺹﺺﺻﺼﺽﺾﺿﻀﻁﻂﻃﻄﻅﻆﻇﻈﻉﻊﻋﻌﻍﻎﻏﻐﻑﻒﻓﻔﻕﻖﻗﻘﻙﻚﻛﻜﻝﻞﻟﻠﻡﻢﻣﻤﻥﻦﻧﻨﻩﻪﻫﻬﻭﻮﻯﻰﻱﻲﻳﻴﻵﻶﻷﻸﻹﻺﻻﻼ'; + $find = 'ﻞ'; + $result = mb_strrichr($string, $find); + $expected = 'ﻞﻟﻠﻡﻢﻣﻤﻥﻦﻧﻨﻩﻪﻫﻬﻭﻮﻯﻰﻱﻲﻳﻴﻵﻶﻷﻸﻹﻺﻻﻼ'; + $this->assertEquals($expected, $result); + + $string = 'ﺱﺲﺳﺴﺵﺶﺷﺸﺹﺺﺻﺼﺽﺾﺿﻀﻁﻂﻃﻄﻅﻆﻇﻈﻉﻊﻋﻌﻍﻎﻏﻐﻑﻒﻓﻔﻕﻖﻗﻘﻙﻚﻛﻜﻝﻞﻟﻠﻡﻢﻣﻤﻥﻦﻧﻨﻩﻪﻫﻬﻭﻮﻯﻰﻱﻲﻳﻴﻵﻶﻷﻸﻹﻺﻻﻼ'; + $find = 'ﻞ'; + $result = mb_strrichr($string, $find, true); + $expected = 'ﺱﺲﺳﺴﺵﺶﺷﺸﺹﺺﺻﺼﺽﺾﺿﻀﻁﻂﻃﻄﻅﻆﻇﻈﻉﻊﻋﻌﻍﻎﻏﻐﻑﻒﻓﻔﻕﻖﻗﻘﻙﻚﻛﻜﻝ'; + $this->assertEquals($expected, $result); + + $string = 'abcdefghijklmnopqrstuvwxyz'; + $find = 'k'; + $result = mb_strrichr($string, $find); + $expected = 'klmnopqrstuvwxyz'; + $this->assertEquals($expected, $result); + + $string = 'abcdefghijklmnopqrstuvwxyz'; + $find = 'k'; + $result = mb_strrichr($string, $find, true); + $expected = 'abcdefghij'; + $this->assertEquals($expected, $result); + + $string = '。「」、・ヲァィゥェォャュョッーアイウエオカキク'; + $find = 'ア'; + $result = mb_strrichr($string, $find); + $expected = 'アイウエオカキク'; + $this->assertEquals($expected, $result); + + $string = '。「」、・ヲァィゥェォャュョッーアイウエオカキク'; + $find = 'ア'; + $result = mb_strrichr($string, $find, true); + $expected = '。「」、・ヲァィゥェォャュョッー'; + $this->assertEquals($expected, $result); + + $string = 'ケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン゙'; + $find = 'ハ'; + $result = mb_strrichr($string, $find); + $expected = 'ハヒフヘホマミムメモヤユヨラリルレロワン゙'; + $this->assertEquals($expected, $result); + + $string = 'ケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン゙'; + $find = 'ハ'; + $result = mb_strrichr($string, $find, true); + $expected = 'ケコサシスセソタチツテトナニヌネノ'; + $this->assertEquals($expected, $result); + + $string = 'Ĥēĺļŏ, Ŵőřļď!'; + $find = 'ő'; + $result = mb_strrichr($string, $find); + $expected = 'őřļď!'; + $this->assertEquals($expected, $result); + + $string = 'Ĥēĺļŏ, Ŵőřļď!'; + $find = 'ő'; + $result = mb_strrichr($string, $find, true); + $expected = 'Ĥēĺļŏ, Ŵ'; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'o'; + $result = mb_strrichr($string, $find); + $expected = 'orld!'; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'o'; + $result = mb_strrichr($string, $find, true); + $expected = 'Hello, W'; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'Wo'; + $result = mb_strrichr($string, $find); + $expected = 'World!'; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'Wo'; + $result = mb_strrichr($string, $find, true); + $expected = 'Hello, '; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'll'; + $result = mb_strrichr($string, $find); + $expected = 'llo, World!'; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'll'; + $result = mb_strrichr($string, $find, true); + $expected = 'He'; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'rld'; + $result = mb_strrichr($string, $find); + $expected = 'rld!'; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'rld'; + $result = mb_strrichr($string, $find, true); + $expected = 'Hello, Wo'; + $this->assertEquals($expected, $result); + + $string = 'čini'; + $find = 'n'; + $result = mb_strrichr($string, $find); + $expected = 'ni'; + $this->assertEquals($expected, $result); + + $string = 'čini'; + $find = 'n'; + $result = mb_strrichr($string, $find, true); + $expected = 'či'; + $this->assertEquals($expected, $result); + + $string = 'moći'; + $find = 'ć'; + $result = mb_strrichr($string, $find); + $expected = 'ći'; + $this->assertEquals($expected, $result); + + $string = 'moći'; + $find = 'ć'; + $result = mb_strrichr($string, $find, true); + $expected = 'mo'; + $this->assertEquals($expected, $result); + + $string = 'državni'; + $find = 'ž'; + $result = mb_strrichr($string, $find); + $expected = 'žavni'; + $this->assertEquals($expected, $result); + + $string = 'državni'; + $find = 'ž'; + $result = mb_strrichr($string, $find, true); + $expected = 'dr'; + $this->assertEquals($expected, $result); + + $string = '把百度设为首页'; + $find = '设'; + $result = mb_strrichr($string, $find); + $expected = '设为首页'; + $this->assertEquals($expected, $result); + + $string = '把百度设为首页'; + $find = '设'; + $result = mb_strrichr($string, $find, true); + $expected = '把百度'; + $this->assertEquals($expected, $result); + + $string = '一二三周永龍'; + $find = '周'; + $result = mb_strrichr($string, $find); + $expected = '周永龍'; + $this->assertEquals($expected, $result); + + $string = '一二三周永龍'; + $find = '周'; + $result = mb_strrichr($string, $find, true); + $expected = '一二三'; + $this->assertEquals($expected, $result); + + $string = '把百度设为首页'; + $find = '百设'; + $result = mb_strrichr($string, $find, true); + $expected = false; + $this->assertEquals($expected, $result); + } + +/** + * testMultibyteStrrichr method + * + * @return void + */ + public function testMultibyteStrrichr() { + $string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; + $find = 'F'; + $result = Multibyte::strrichr($string, $find); + $expected = 'FGHIJKLMNOPQRSTUVWXYZ0123456789'; + $this->assertEquals($expected, $result); + + $string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; + $find = 'F'; + $result = Multibyte::strrichr($string, $find, true); + $expected = 'ABCDE'; + $this->assertEquals($expected, $result); + + $string = 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ'; + $find = 'Å'; + $result = Multibyte::strrichr($string, $find); + $expected = 'ÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ'; + $this->assertEquals($expected, $result); + + $string = 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ'; + $find = 'Å'; + $result = Multibyte::strrichr($string, $find, true); + $expected = 'ÀÁÂÃÄ'; + $this->assertEquals($expected, $result); + + $string = 'ĀĂĄĆĈĊČĎĐĒĔĖĘĚĜĞĠĢĤĦĨĪĬĮIJĴĶĹĻĽĿŁŃŅŇŊŌŎŐŒŔŖŘŚŜŞŠŢŤŦŨŪŬŮŰŲŴŶŹŻŽ'; + $find = 'Ċ'; + $result = Multibyte::strrichr($string, $find); + $expected = 'ĊČĎĐĒĔĖĘĚĜĞĠĢĤĦĨĪĬĮIJĴĶĹĻĽĿŁŃŅŇŊŌŎŐŒŔŖŘŚŜŞŠŢŤŦŨŪŬŮŰŲŴŶŹŻŽ'; + $this->assertEquals($expected, $result); + + $string = 'ĀĂĄĆĈĊČĎĐĒĔĖĘĚĜĞĠĢĤĦĨĪĬĮIJĴĶĹĻĽĿŁŃŅŇŊŌŎŐŒŔŖŘŚŜŞŠŢŤŦŨŪŬŮŰŲŴŶŹŻŽ'; + $find = 'Ċ'; + $result = Multibyte::strrichr($string, $find, true); + $expected = 'ĀĂĄĆĈ'; + $this->assertEquals($expected, $result); + + $string = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'; + $find = 'F'; + $result = Multibyte::strrichr($string, $find); + $expected = 'fghijklmnopqrstuvwxyz{|}~'; + $this->assertEquals($expected, $result); + + $string = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'; + $find = 'F'; + $result = Multibyte::strrichr($string, $find, true); + $expected = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcde'; + $this->assertEquals($expected, $result); + + $string = '¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈ'; + $find = 'µ'; + $result = Multibyte::strrichr($string, $find); + $expected = 'µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈ'; + $this->assertEquals($expected, $result); + + $string = '¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈ'; + $find = 'µ'; + $result = Multibyte::strrichr($string, $find, true); + $expected = '¡¢£¤¥¦§¨©ª«¬­®¯°±²³´'; + $this->assertEquals($expected, $result); + + $string = 'ÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬ'; + $find = 'Þ'; + $result = Multibyte::strrichr($string, $find); + $expected = 'þÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬ'; + $this->assertEquals($expected, $result); + + $string = 'ÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬ'; + $find = 'Þ'; + $result = Multibyte::strrichr($string, $find, true); + $expected = 'ÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüý'; + $this->assertEquals($expected, $result); + + $string = 'ĭĮįİıIJijĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏƐ'; + $find = 'Ņ'; + $result = Multibyte::strrichr($string, $find); + $expected = 'ņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏƐ'; + $this->assertEquals($expected, $result); + + $string = 'ĭĮįİıIJijĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏƐ'; + $find = 'Ņ'; + $result = Multibyte::strrichr($string, $find, true); + $expected = 'ĭĮįİıIJijĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅ'; + $this->assertEquals($expected, $result); + + $string = 'ƑƒƓƔƕƖƗƘƙƚƛƜƝƞƟƠơƢƣƤƥƦƧƨƩƪƫƬƭƮƯưƱƲƳƴƵƶƷƸƹƺƻƼƽƾƿǀǁǂǃDŽDždžLJLjljNJNjnjǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰDZDzdzǴ'; + $find = 'Ƹ'; + $result = Multibyte::strrichr($string, $find); + $expected = 'ƹƺƻƼƽƾƿǀǁǂǃDŽDždžLJLjljNJNjnjǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰDZDzdzǴ'; + $this->assertEquals($expected, $result); + + $find = 'Ƹ'; + $result = Multibyte::strrichr($string, $find, true); + $expected = 'ƑƒƓƔƕƖƗƘƙƚƛƜƝƞƟƠơƢƣƤƥƦƧƨƩƪƫƬƭƮƯưƱƲƳƴƵƶƷƸ'; + $this->assertEquals($expected, $result); + + $string = 'əɚɛɜɝɞɟɠɡɢɣɤɥɦɧɨɩɪɫɬɭɮɯɰɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿʀʁʂʃʄʅʆʇʈʉʊʋʌʍʎʏʐʑʒʓʔʕʖʗʘʙʚʛʜʝʞʟʠʡʢʣʤʥʦʧʨʩʪʫʬʭʮʯʰʱʲʳʴʵʶʷʸʹʺʻʼ'; + $find = 'ʀ'; + $result = Multibyte::strrichr($string, $find); + $expected = 'ʀʁʂʃʄʅʆʇʈʉʊʋʌʍʎʏʐʑʒʓʔʕʖʗʘʙʚʛʜʝʞʟʠʡʢʣʤʥʦʧʨʩʪʫʬʭʮʯʰʱʲʳʴʵʶʷʸʹʺʻʼ'; + $this->assertEquals($expected, $result); + + $string = 'əɚɛɜɝɞɟɠɡɢɣɤɥɦɧɨɩɪɫɬɭɮɯɰɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿʀʁʂʃʄʅʆʇʈʉʊʋʌʍʎʏʐʑʒʓʔʕʖʗʘʙʚʛʜʝʞʟʠʡʢʣʤʥʦʧʨʩʪʫʬʭʮʯʰʱʲʳʴʵʶʷʸʹʺʻʼ'; + $find = 'ʀ'; + $result = Multibyte::strrichr($string, $find, true); + $expected = 'əɚɛɜɝɞɟɠɡɢɣɤɥɦɧɨɩɪɫɬɭɮɯɰɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿ'; + $this->assertEquals($expected, $result); + + $string = 'ЀЁЂЃЄЅІЇЈЉЊЋЌЍЎЏАБВГДЕЖЗИЙКЛ'; + $find = 'Ї'; + $result = Multibyte::strrichr($string, $find); + $expected = 'ЇЈЉЊЋЌЍЎЏАБВГДЕЖЗИЙКЛ'; + $this->assertEquals($expected, $result); + + $string = 'ЀЁЂЃЄЅІЇЈЉЊЋЌЍЎЏАБВГДЕЖЗИЙКЛ'; + $find = 'Ї'; + $result = Multibyte::strrichr($string, $find, true); + $expected = 'ЀЁЂЃЄЅІ'; + $this->assertEquals($expected, $result); + + $string = 'МНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыь'; + $find = 'Р'; + $result = Multibyte::strrichr($string, $find); + $expected = 'рстуфхцчшщъыь'; + $this->assertEquals($expected, $result); + + $string = 'МНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп'; + $find = 'Р'; + $result = Multibyte::strrichr($string, $find, true); + $expected = 'МНОП'; + $this->assertEquals($expected, $result); + + $string = 'فقكلمنهوىيًٌٍَُ'; + $find = 'ن'; + $result = Multibyte::strrichr($string, $find); + $expected = 'نهوىيًٌٍَُ'; + $this->assertEquals($expected, $result); + + $string = 'فقكلمنهوىيًٌٍَُ'; + $find = 'ن'; + $result = Multibyte::strrichr($string, $find, true); + $expected = 'فقكلم'; + $this->assertEquals($expected, $result); + + $string = '✰✱✲✳✴✵✶✷✸✹✺✻✼✽✾✿❀❁❂❃❄❅❆❇❈❉❊❋❌❍❎❏❐❑❒❓❔❕❖❗❘❙❚❛❜❝❞'; + $find = '✿'; + $result = Multibyte::strrichr($string, $find); + $expected = '✿❀❁❂❃❄❅❆❇❈❉❊❋❌❍❎❏❐❑❒❓❔❕❖❗❘❙❚❛❜❝❞'; + $this->assertEquals($expected, $result); + + $string = '✰✱✲✳✴✵✶✷✸✹✺✻✼✽✾✿❀❁❂❃❄❅❆❇❈❉❊❋❌❍❎❏❐❑❒❓❔❕❖❗❘❙❚❛❜❝❞'; + $find = '✿'; + $result = Multibyte::strrichr($string, $find, true); + $expected = '✰✱✲✳✴✵✶✷✸✹✺✻✼✽✾'; + $this->assertEquals($expected, $result); + + $string = '⺀⺁⺂⺃⺄⺅⺆⺇⺈⺉⺊⺋⺌⺍⺎⺏⺐⺑⺒⺓⺔⺕⺖⺗⺘⺙⺛⺜⺝⺞⺟⺠⺡⺢⺣⺤⺥⺦⺧⺨⺩⺪⺫⺬⺭⺮⺯⺰⺱⺲⺳⺴⺵⺶⺷⺸⺹⺺⺻⺼⺽⺾⺿⻀⻁⻂⻃⻄⻅⻆⻇⻈⻉⻊⻋⻌⻍⻎⻏⻐⻑⻒⻓⻔⻕⻖⻗⻘⻙⻚⻛⻜⻝⻞⻟⻠'; + $find = '⺐'; + $result = Multibyte::strrichr($string, $find); + $expected = '⺐⺑⺒⺓⺔⺕⺖⺗⺘⺙⺛⺜⺝⺞⺟⺠⺡⺢⺣⺤⺥⺦⺧⺨⺩⺪⺫⺬⺭⺮⺯⺰⺱⺲⺳⺴⺵⺶⺷⺸⺹⺺⺻⺼⺽⺾⺿⻀⻁⻂⻃⻄⻅⻆⻇⻈⻉⻊⻋⻌⻍⻎⻏⻐⻑⻒⻓⻔⻕⻖⻗⻘⻙⻚⻛⻜⻝⻞⻟⻠'; + $this->assertEquals($expected, $result); + + $string = '⺀⺁⺂⺃⺄⺅⺆⺇⺈⺉⺊⺋⺌⺍⺎⺏⺐⺑⺒⺓⺔⺕⺖⺗⺘⺙⺛⺜⺝⺞⺟⺠⺡⺢⺣⺤⺥⺦⺧⺨⺩⺪⺫⺬⺭⺮⺯⺰⺱⺲⺳⺴⺵⺶⺷⺸⺹⺺⺻⺼⺽⺾⺿⻀⻁⻂⻃⻄⻅⻆⻇⻈⻉⻊⻋⻌⻍⻎⻏⻐⻑⻒⻓⻔⻕⻖⻗⻘⻙⻚⻛⻜⻝⻞⻟⻠'; + $find = '⺐'; + $result = Multibyte::strrichr($string, $find, true); + $expected = '⺀⺁⺂⺃⺄⺅⺆⺇⺈⺉⺊⺋⺌⺍⺎⺏'; + $this->assertEquals($expected, $result); + + $string = '⽅⽆⽇⽈⽉⽊⽋⽌⽍⽎⽏⽐⽑⽒⽓⽔⽕⽖⽗⽘⽙⽚⽛⽜⽝⽞⽟⽠⽡⽢⽣⽤⽥⽦⽧⽨⽩⽪⽫⽬⽭⽮⽯⽰⽱⽲⽳⽴⽵⽶⽷⽸⽹⽺⽻⽼⽽⽾⽿'; + $find = '⽤'; + $result = Multibyte::strrichr($string, $find); + $expected = '⽤⽥⽦⽧⽨⽩⽪⽫⽬⽭⽮⽯⽰⽱⽲⽳⽴⽵⽶⽷⽸⽹⽺⽻⽼⽽⽾⽿'; + $this->assertEquals($expected, $result); + + $string = '⽅⽆⽇⽈⽉⽊⽋⽌⽍⽎⽏⽐⽑⽒⽓⽔⽕⽖⽗⽘⽙⽚⽛⽜⽝⽞⽟⽠⽡⽢⽣⽤⽥⽦⽧⽨⽩⽪⽫⽬⽭⽮⽯⽰⽱⽲⽳⽴⽵⽶⽷⽸⽹⽺⽻⽼⽽⽾⽿'; + $find = '⽤'; + $result = Multibyte::strrichr($string, $find, true); + $expected = '⽅⽆⽇⽈⽉⽊⽋⽌⽍⽎⽏⽐⽑⽒⽓⽔⽕⽖⽗⽘⽙⽚⽛⽜⽝⽞⽟⽠⽡⽢⽣'; + $this->assertEquals($expected, $result); + + $string = '눡눢눣눤눥눦눧눨눩눪눫눬눭눮눯눰눱눲눳눴눵눶눷눸눹눺눻눼눽눾눿뉀뉁뉂뉃뉄뉅뉆뉇뉈뉉뉊뉋뉌뉍뉎뉏뉐뉑뉒뉓뉔뉕뉖뉗뉘뉙뉚뉛뉜뉝뉞뉟뉠뉡뉢뉣뉤뉥뉦뉧뉨뉩뉪뉫뉬뉭뉮뉯뉰뉱뉲뉳뉴뉵뉶뉷뉸뉹뉺뉻뉼뉽뉾뉿늀늁늂늃늄'; + $find = '눻'; + $result = Multibyte::strrichr($string, $find); + $expected = '눻눼눽눾눿뉀뉁뉂뉃뉄뉅뉆뉇뉈뉉뉊뉋뉌뉍뉎뉏뉐뉑뉒뉓뉔뉕뉖뉗뉘뉙뉚뉛뉜뉝뉞뉟뉠뉡뉢뉣뉤뉥뉦뉧뉨뉩뉪뉫뉬뉭뉮뉯뉰뉱뉲뉳뉴뉵뉶뉷뉸뉹뉺뉻뉼뉽뉾뉿늀늁늂늃늄'; + $this->assertEquals($expected, $result); + + $string = '눡눢눣눤눥눦눧눨눩눪눫눬눭눮눯눰눱눲눳눴눵눶눷눸눹눺눻눼눽눾눿뉀뉁뉂뉃뉄뉅뉆뉇뉈뉉뉊뉋뉌뉍뉎뉏뉐뉑뉒뉓뉔뉕뉖뉗뉘뉙뉚뉛뉜뉝뉞뉟뉠뉡뉢뉣뉤뉥뉦뉧뉨뉩뉪뉫뉬뉭뉮뉯뉰뉱뉲뉳뉴뉵뉶뉷뉸뉹뉺뉻뉼뉽뉾뉿늀늁늂늃늄'; + $find = '눻'; + $result = Multibyte::strrichr($string, $find, true); + $expected = '눡눢눣눤눥눦눧눨눩눪눫눬눭눮눯눰눱눲눳눴눵눶눷눸눹눺'; + $this->assertEquals($expected, $result); + + $string = 'ﹰﹱﹲﹳﹴ﹵ﹶﹷﹸﹹﹺﹻﹼﹽﹾﹿﺀﺁﺂﺃﺄﺅﺆﺇﺈﺉﺊﺋﺌﺍﺎﺏﺐﺑﺒﺓﺔﺕﺖﺗﺘﺙﺚﺛﺜﺝﺞﺟﺠﺡﺢﺣﺤﺥﺦﺧﺨﺩﺪﺫﺬﺭﺮﺯﺰ'; + $find = 'ﺞ'; + $result = Multibyte::strrichr($string, $find); + $expected = 'ﺞﺟﺠﺡﺢﺣﺤﺥﺦﺧﺨﺩﺪﺫﺬﺭﺮﺯﺰ'; + $this->assertEquals($expected, $result); + + $string = 'ﹰﹱﹲﹳﹴ﹵ﹶﹷﹸﹹﹺﹻﹼﹽﹾﹿﺀﺁﺂﺃﺄﺅﺆﺇﺈﺉﺊﺋﺌﺍﺎﺏﺐﺑﺒﺓﺔﺕﺖﺗﺘﺙﺚﺛﺜﺝﺞﺟﺠﺡﺢﺣﺤﺥﺦﺧﺨﺩﺪﺫﺬﺭﺮﺯﺰ'; + $find = 'ﺞ'; + $result = Multibyte::strrichr($string, $find, true); + $expected = 'ﹰﹱﹲﹳﹴ﹵ﹶﹷﹸﹹﹺﹻﹼﹽﹾﹿﺀﺁﺂﺃﺄﺅﺆﺇﺈﺉﺊﺋﺌﺍﺎﺏﺐﺑﺒﺓﺔﺕﺖﺗﺘﺙﺚﺛﺜﺝ'; + $this->assertEquals($expected, $result); + + $string = 'ﺱﺲﺳﺴﺵﺶﺷﺸﺹﺺﺻﺼﺽﺾﺿﻀﻁﻂﻃﻄﻅﻆﻇﻈﻉﻊﻋﻌﻍﻎﻏﻐﻑﻒﻓﻔﻕﻖﻗﻘﻙﻚﻛﻜﻝﻞﻟﻠﻡﻢﻣﻤﻥﻦﻧﻨﻩﻪﻫﻬﻭﻮﻯﻰﻱﻲﻳﻴﻵﻶﻷﻸﻹﻺﻻﻼ'; + $find = 'ﻞ'; + $result = Multibyte::strrichr($string, $find); + $expected = 'ﻞﻟﻠﻡﻢﻣﻤﻥﻦﻧﻨﻩﻪﻫﻬﻭﻮﻯﻰﻱﻲﻳﻴﻵﻶﻷﻸﻹﻺﻻﻼ'; + $this->assertEquals($expected, $result); + + $string = 'ﺱﺲﺳﺴﺵﺶﺷﺸﺹﺺﺻﺼﺽﺾﺿﻀﻁﻂﻃﻄﻅﻆﻇﻈﻉﻊﻋﻌﻍﻎﻏﻐﻑﻒﻓﻔﻕﻖﻗﻘﻙﻚﻛﻜﻝﻞﻟﻠﻡﻢﻣﻤﻥﻦﻧﻨﻩﻪﻫﻬﻭﻮﻯﻰﻱﻲﻳﻴﻵﻶﻷﻸﻹﻺﻻﻼ'; + $find = 'ﻞ'; + $result = Multibyte::strrichr($string, $find, true); + $expected = 'ﺱﺲﺳﺴﺵﺶﺷﺸﺹﺺﺻﺼﺽﺾﺿﻀﻁﻂﻃﻄﻅﻆﻇﻈﻉﻊﻋﻌﻍﻎﻏﻐﻑﻒﻓﻔﻕﻖﻗﻘﻙﻚﻛﻜﻝ'; + $this->assertEquals($expected, $result); + + $string = 'abcdefghijklmnopqrstuvwxyz'; + $find = 'k'; + $result = Multibyte::strrichr($string, $find); + $expected = 'klmnopqrstuvwxyz'; + $this->assertEquals($expected, $result); + + $string = 'abcdefghijklmnopqrstuvwxyz'; + $find = 'k'; + $result = Multibyte::strrichr($string, $find, true); + $expected = 'abcdefghij'; + $this->assertEquals($expected, $result); + + $string = '。「」、・ヲァィゥェォャュョッーアイウエオカキク'; + $find = 'ア'; + $result = Multibyte::strrichr($string, $find); + $expected = 'アイウエオカキク'; + $this->assertEquals($expected, $result); + + $string = '。「」、・ヲァィゥェォャュョッーアイウエオカキク'; + $find = 'ア'; + $result = Multibyte::strrichr($string, $find, true); + $expected = '。「」、・ヲァィゥェォャュョッー'; + $this->assertEquals($expected, $result); + + $string = 'ケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン゙'; + $find = 'ハ'; + $result = Multibyte::strrichr($string, $find); + $expected = 'ハヒフヘホマミムメモヤユヨラリルレロワン゙'; + $this->assertEquals($expected, $result); + + $string = 'ケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン゙'; + $find = 'ハ'; + $result = Multibyte::strrichr($string, $find, true); + $expected = 'ケコサシスセソタチツテトナニヌネノ'; + $this->assertEquals($expected, $result); + + $string = 'Ĥēĺļŏ, Ŵőřļď!'; + $find = 'ő'; + $result = Multibyte::strrichr($string, $find); + $expected = 'őřļď!'; + $this->assertEquals($expected, $result); + + $string = 'Ĥēĺļŏ, Ŵőřļď!'; + $find = 'ő'; + $result = Multibyte::strrichr($string, $find, true); + $expected = 'Ĥēĺļŏ, Ŵ'; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'o'; + $result = Multibyte::strrichr($string, $find); + $expected = 'orld!'; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'o'; + $result = Multibyte::strrichr($string, $find, true); + $expected = 'Hello, W'; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'Wo'; + $result = Multibyte::strrichr($string, $find); + $expected = 'World!'; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'Wo'; + $result = Multibyte::strrichr($string, $find, true); + $expected = 'Hello, '; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'll'; + $result = Multibyte::strrichr($string, $find); + $expected = 'llo, World!'; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'll'; + $result = Multibyte::strrichr($string, $find, true); + $expected = 'He'; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'rld'; + $result = Multibyte::strrichr($string, $find); + $expected = 'rld!'; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'rld'; + $result = Multibyte::strrichr($string, $find, true); + $expected = 'Hello, Wo'; + $this->assertEquals($expected, $result); + + $string = 'čini'; + $find = 'n'; + $result = Multibyte::strrichr($string, $find); + $expected = 'ni'; + $this->assertEquals($expected, $result); + + $string = 'čini'; + $find = 'n'; + $result = Multibyte::strrichr($string, $find, true); + $expected = 'či'; + $this->assertEquals($expected, $result); + + $string = 'moći'; + $find = 'ć'; + $result = Multibyte::strrichr($string, $find); + $expected = 'ći'; + $this->assertEquals($expected, $result); + + $string = 'moći'; + $find = 'ć'; + $result = Multibyte::strrichr($string, $find, true); + $expected = 'mo'; + $this->assertEquals($expected, $result); + + $string = 'državni'; + $find = 'ž'; + $result = Multibyte::strrichr($string, $find); + $expected = 'žavni'; + $this->assertEquals($expected, $result); + + $string = 'državni'; + $find = 'ž'; + $result = Multibyte::strrichr($string, $find, true); + $expected = 'dr'; + $this->assertEquals($expected, $result); + + $string = '把百度设为首页'; + $find = '设'; + $result = Multibyte::strrichr($string, $find); + $expected = '设为首页'; + $this->assertEquals($expected, $result); + + $string = '把百度设为首页'; + $find = '设'; + $result = Multibyte::strrichr($string, $find, true); + $expected = '把百度'; + $this->assertEquals($expected, $result); + + $string = '一二三周永龍'; + $find = '周'; + $result = Multibyte::strrichr($string, $find); + $expected = '周永龍'; + $this->assertEquals($expected, $result); + + $string = '一二三周永龍'; + $find = '周'; + $result = Multibyte::strrichr($string, $find, true); + $expected = '一二三'; + $this->assertEquals($expected, $result); + + $string = '把百度设为首页'; + $find = '百设'; + $result = Multibyte::strrichr($string, $find, true); + $expected = false; + $this->assertEquals($expected, $result); + } + +/** + * testUsingMbStrripos method + * + * @return void + */ + public function testUsingMbStrripos() { + $string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; + $find = 'F'; + $result = mb_strripos($string, $find); + $expected = 5; + $this->assertEquals($expected, $result); + + $string = 'ABCDEFGHIJKLMNOPQFRSTUVWXYZ0123456789'; + $find = 'F'; + $result = mb_strripos($string, $find, 6); + $expected = 17; + $this->assertEquals($expected, $result); + + $string = 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ'; + $find = 'Å'; + $result = mb_strripos($string, $find); + $expected = 5; + $this->assertEquals($expected, $result); + + $string = 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÅÙÚÛÜÝÞ'; + $find = 'Å'; + $result = mb_strripos($string, $find, 6); + $expected = 24; + $this->assertEquals($expected, $result); + + $string = 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÅÙÚÛÜÝÞ'; + $find = 'ÓÔ'; + $result = mb_strripos($string, $find); + $expected = 19; + $this->assertEquals($expected, $result); + + $string = 'ĀĂĄĆĈĊČĎĐĒĔĖĘĚĜĞĠĢĤĦĨĪĬĮIJĴĶĹĻĽĿŁŃŅŇŊŌŎŐŒŔŖŘŚŜŞŠŢŤŦŨŪŬŮŰŲŴŶŹŻŽ'; + $find = 'Ċ'; + $result = mb_strripos($string, $find); + $expected = 5; + $this->assertEquals($expected, $result); + + $string = 'ĀĂĄĆĈĊČĎĐĒĔĖĘĚĜĞĠĢĤĦĨĪĬĮIJĴĶĹĻĽĿŁĊŃŅŇŊŌŎŐŒŔŖŘŚŜŞŠŢŤŦŨŪŬŮŰŲŴŶŹŻŽ'; + $find = 'Ċ'; + $result = mb_strripos($string, $find, 6); + $expected = 32; + $this->assertEquals($expected, $result); + + $string = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'; + $find = 'F'; + $result = mb_strripos($string, $find); + $expected = 69; + $this->assertEquals($expected, $result); + + $string = '¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈ'; + $find = 'µ'; + $result = mb_strripos($string, $find); + $expected = 20; + $this->assertEquals($expected, $result); + + $string = 'ÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬ'; + $find = 'é'; + $result = mb_strripos($string, $find); + $expected = 32; + $this->assertEquals($expected, $result); + + $string = 'ĭĮįİıIJijĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏƐ'; + $find = 'Ņ'; + $result = mb_strripos($string, $find); + $expected = 25; + $this->assertEquals($expected, $result); + + $string = 'ƑƒƓƔƕƖƗƘƙƚƛƜƝƞƟƠơƢƣƤƥƦƧƨƩƪƫƬƭƮƯưƱƲƳƴƵƶƷƸƹƺƻƼƽƾƿǀǁǂǃDŽDždžLJLjljNJNjnjǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰDZDzdzǴ'; + $find = 'Ƹ'; + $result = mb_strripos($string, $find); + $expected = 40; + $this->assertEquals($expected, $result); + + $string = 'ƑƒƓƔƕƖƗƘƙƚƛƜƝƞƟƠơƢƣƤƥƦƧƨƩƪƫƬƭƮƯưƱƲƳƴƵƶƷƸƹƺƻƼƽƾƿǀǁǂǃDŽDždžLJLjljNJNjnjǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰDZDzdzǴ'; + $find = 'ƹ'; + $result = mb_strripos($string, $find); + $expected = 40; + $this->assertEquals($expected, $result); + + $string = 'əɚɛɜɝɞɟɠɡɢɣɤɥɦɧɨɩɪɫɬɭɮɯɰɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿʀʁʂʃʄʅʆʇʈʉʊʋʌʍʎʏʐʑʒʓʔʕʖʗʘʙʚʛʜʝʞʟʠʡʢʣʤʥʦʧʨʩʪʫʬʭʮʯʰʱʲʳʴʵʶʷʸʹʺʻʼ'; + $find = 'ʀ'; + $result = mb_strripos($string, $find); + $expected = 39; + $this->assertEquals($expected, $result); + + $string = 'ЀЁЂЃЄЅІЇЈЉЊЋЌЍЎЏАБВГДЕЖЗИЙКЛ'; + $find = 'Ї'; + $result = mb_strripos($string, $find); + $expected = 7; + $this->assertEquals($expected, $result); + + $string = 'МНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыь'; + $find = 'Р'; + $result = mb_strripos($string, $find); + $expected = 36; + $this->assertEquals($expected, $result); + + $string = 'МНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыь'; + $find = 'р'; + $result = mb_strripos($string, $find, 5); + $expected = 36; + $this->assertEquals($expected, $result); + + $string = 'فقكلمنهوىيًٌٍَُ'; + $find = 'ن'; + $result = mb_strripos($string, $find); + $expected = 5; + $this->assertEquals($expected, $result); + + $string = '✰✱✲✳✴✵✶✷✸✹✺✻✼✽✾✿❀❁❂❃❄❅❆❇❈❉❊❋❌❍❎❏❐❑❒❓❔❕❖❗❘❙❚❛❜❝❞'; + $find = '✿'; + $result = mb_strripos($string, $find); + $expected = 15; + $this->assertEquals($expected, $result); + + $string = '⺀⺁⺂⺃⺄⺅⺆⺇⺈⺉⺊⺋⺌⺍⺎⺏⺐⺑⺒⺓⺔⺕⺖⺗⺘⺙⺛⺜⺝⺞⺟⺠⺡⺢⺣⺤⺥⺦⺧⺨⺩⺪⺫⺬⺭⺮⺯⺰⺱⺲⺳⺴⺵⺶⺷⺸⺹⺺⺻⺼⺽⺾⺿⻀⻁⻂⻃⻄⻅⻆⻇⻈⻉⻊⻋⻌⻍⻎⻏⻐⻑⻒⻓⻔⻕⻖⻗⻘⻙⻚⻛⻜⻝⻞⻟⻠'; + $find = '⺐'; + $result = mb_strripos($string, $find); + $expected = 16; + $this->assertEquals($expected, $result); + + $string = '⽅⽆⽇⽈⽉⽊⽋⽌⽍⽎⽏⽐⽑⽒⽓⽔⽕⽖⽗⽘⽙⽚⽛⽜⽝⽞⽟⽠⽡⽢⽣⽤⽥⽦⽧⽨⽩⽪⽫⽬⽭⽮⽯⽰⽱⽲⽳⽴⽵⽶⽷⽸⽹⽺⽻⽼⽽⽾⽿'; + $find = '⽤'; + $result = mb_strripos($string, $find); + $expected = 31; + $this->assertEquals($expected, $result); + + $string = '눡눢눣눤눥눦눧눨눩눪눫눬눭눮눯눰눱눲눳눴눵눶눷눸눹눺눻눼눽눾눿뉀뉁뉂뉃뉄뉅뉆뉇뉈뉉뉊뉋뉌뉍뉎뉏뉐뉑뉒뉓뉔뉕뉖뉗뉘뉙뉚뉛뉜뉝뉞뉟뉠뉡뉢뉣뉤뉥뉦뉧뉨뉩뉪뉫뉬뉭뉮뉯뉰뉱뉲뉳뉴뉵뉶뉷뉸뉹뉺뉻뉼뉽뉾뉿늀늁늂늃늄'; + $find = '눻'; + $result = mb_strripos($string, $find); + $expected = 26; + $this->assertEquals($expected, $result); + + $string = 'ﹰﹱﹲﹳﹴ﹵ﹶﹷﹸﹹﹺﹻﹼﹽﹾﹿﺀﺁﺂﺃﺄﺅﺆﺇﺈﺉﺊﺋﺌﺍﺎﺏﺐﺑﺒﺓﺔﺕﺖﺗﺘﺙﺚﺛﺜﺝﺞﺟﺠﺡﺢﺣﺤﺥﺦﺧﺨﺩﺪﺫﺬﺭﺮﺯﺰ'; + $find = 'ﺞ'; + $result = mb_strripos($string, $find); + $expected = 46; + $this->assertEquals($expected, $result); + + $string = 'ﺱﺲﺳﺴﺵﺶﺷﺸﺹﺺﺻﺼﺽﺾﺿﻀﻁﻂﻃﻄﻅﻆﻇﻈﻉﻊﻋﻌﻍﻎﻏﻐﻑﻒﻓﻔﻕﻖﻗﻘﻙﻚﻛﻜﻝﻞﻟﻠﻡﻢﻣﻤﻥﻦﻧﻨﻩﻪﻫﻬﻭﻮﻯﻰﻱﻲﻳﻴﻵﻶﻷﻸﻹﻺﻻﻼ'; + $find = 'ﻞ'; + $result = mb_strripos($string, $find); + $expected = 45; + $this->assertEquals($expected, $result); + + $string = 'abcdefghijklmnopqrstuvwxyz'; + $find = 'k'; + $result = mb_strripos($string, $find); + $expected = 10; + $this->assertEquals($expected, $result); + + $string = 'abcdefghijklmnopqrstuvwxyz'; + $find = 'k'; + $result = mb_strripos($string, $find); + $expected = 10; + $this->assertEquals($expected, $result); + + $string = 'abcdefghijklmnoppqrstuvwxyz'; + $find = 'pp'; + $result = mb_strripos($string, $find); + $expected = 15; + $this->assertEquals($expected, $result); + + $string = '。「」、・ヲァィゥェォャュョッーアイウエオカキク'; + $find = 'ア'; + $result = mb_strripos($string, $find); + $expected = 16; + $this->assertEquals($expected, $result); + + $string = 'ケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン゙'; + $find = 'ハ'; + $result = mb_strripos($string, $find); + $expected = 17; + $this->assertEquals($expected, $result); + + $string = 'Ĥēĺļŏ, Ŵőřļď!'; + $find = 'ő'; + $result = mb_strripos($string, $find); + $expected = 8; + $this->assertEquals($expected, $result); + + $string = 'Ĥēĺļŏ, Ŵőřļď!'; + $find = 'ő'; + $result = mb_strripos($string, $find); + $expected = 8; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'o'; + $result = mb_strripos($string, $find); + $expected = 8; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'o'; + $result = mb_strripos($string, $find, 5); + $expected = 8; + $this->assertEquals($expected, $result); + + $string = 'čini'; + $find = 'n'; + $result = mb_strripos($string, $find); + $expected = 2; + $this->assertEquals($expected, $result); + + $string = 'čini'; + $find = 'n'; + $result = mb_strripos($string, $find); + $expected = 2; + $this->assertEquals($expected, $result); + + $string = 'moći'; + $find = 'ć'; + $result = mb_strripos($string, $find); + $expected = 2; + $this->assertEquals($expected, $result); + + $string = 'moći'; + $find = 'ć'; + $result = mb_strripos($string, $find); + $expected = 2; + $this->assertEquals($expected, $result); + + $string = 'državni'; + $find = 'ž'; + $result = mb_strripos($string, $find); + $expected = 2; + $this->assertEquals($expected, $result); + + $string = '把百度设为首页'; + $find = '设'; + $result = mb_strripos($string, $find); + $expected = 3; + $this->assertEquals($expected, $result); + + $string = '一二三周永龍'; + $find = '周'; + $result = mb_strripos($string, $find); + $expected = 3; + $this->assertEquals($expected, $result); + + $string = 'državni'; + $find = 'dž'; + $result = mb_strripos($string, $find); + $this->assertFalse($result); + } + +/** + * testMultibyteStrripos method + * + * @return void + */ + public function testMultibyteStrripos() { + $string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; + $find = 'F'; + $result = Multibyte::strripos($string, $find); + $expected = 5; + $this->assertEquals($expected, $result); + + $string = 'ABCDEFGHIJKLMNOPQFRSTUVWXYZ0123456789'; + $find = 'F'; + $result = Multibyte::strripos($string, $find, 6); + $expected = 17; + $this->assertEquals($expected, $result); + + $string = 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ'; + $find = 'Å'; + $result = Multibyte::strripos($string, $find); + $expected = 5; + $this->assertEquals($expected, $result); + + $string = 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÅÙÚÛÜÝÞ'; + $find = 'Å'; + $result = Multibyte::strripos($string, $find, 6); + $expected = 24; + $this->assertEquals($expected, $result); + + $string = 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÅÙÚÛÜÝÞ'; + $find = 'ÓÔ'; + $result = Multibyte::strripos($string, $find); + $expected = 19; + $this->assertEquals($expected, $result); + + $string = 'ĀĂĄĆĈĊČĎĐĒĔĖĘĚĜĞĠĢĤĦĨĪĬĮIJĴĶĹĻĽĿŁŃŅŇŊŌŎŐŒŔŖŘŚŜŞŠŢŤŦŨŪŬŮŰŲŴŶŹŻŽ'; + $find = 'Ċ'; + $result = Multibyte::strripos($string, $find); + $expected = 5; + $this->assertEquals($expected, $result); + + $string = 'ĀĂĄĆĈĊČĎĐĒĔĖĘĚĜĞĠĢĤĦĨĪĬĮIJĴĶĹĻĽĿŁĊŃŅŇŊŌŎŐŒŔŖŘŚŜŞŠŢŤŦŨŪŬŮŰŲŴŶŹŻŽ'; + $find = 'Ċ'; + $result = Multibyte::strripos($string, $find, 6); + $expected = 32; + $this->assertEquals($expected, $result); + + $string = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'; + $find = 'F'; + $result = Multibyte::strripos($string, $find); + $expected = 69; + $this->assertEquals($expected, $result); + + $string = '¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈ'; + $find = 'µ'; + $result = Multibyte::strripos($string, $find); + $expected = 20; + $this->assertEquals($expected, $result); + + $string = 'ÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬ'; + $find = 'é'; + $result = Multibyte::strripos($string, $find); + $expected = 32; + $this->assertEquals($expected, $result); + + $string = 'ĭĮįİıIJijĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏƐ'; + $find = 'Ņ'; + $result = Multibyte::strripos($string, $find); + $expected = 25; + $this->assertEquals($expected, $result); + + $string = 'ƑƒƓƔƕƖƗƘƙƚƛƜƝƞƟƠơƢƣƤƥƦƧƨƩƪƫƬƭƮƯưƱƲƳƴƵƶƷƸƹƺƻƼƽƾƿǀǁǂǃDŽDždžLJLjljNJNjnjǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰDZDzdzǴ'; + $find = 'Ƹ'; + $result = Multibyte::strripos($string, $find); + $expected = 40; + $this->assertEquals($expected, $result); + + $string = 'ƑƒƓƔƕƖƗƘƙƚƛƜƝƞƟƠơƢƣƤƥƦƧƨƩƪƫƬƭƮƯưƱƲƳƴƵƶƷƸƹƺƻƼƽƾƿǀǁǂǃDŽDždžLJLjljNJNjnjǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰDZDzdzǴ'; + $find = 'ƹ'; + $result = Multibyte::strripos($string, $find); + $expected = 40; + $this->assertEquals($expected, $result); + + $string = 'əɚɛɜɝɞɟɠɡɢɣɤɥɦɧɨɩɪɫɬɭɮɯɰɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿʀʁʂʃʄʅʆʇʈʉʊʋʌʍʎʏʐʑʒʓʔʕʖʗʘʙʚʛʜʝʞʟʠʡʢʣʤʥʦʧʨʩʪʫʬʭʮʯʰʱʲʳʴʵʶʷʸʹʺʻʼ'; + $find = 'ʀ'; + $result = Multibyte::strripos($string, $find); + $expected = 39; + $this->assertEquals($expected, $result); + + $string = 'ЀЁЂЃЄЅІЇЈЉЊЋЌЍЎЏАБВГДЕЖЗИЙКЛ'; + $find = 'Ї'; + $result = Multibyte::strripos($string, $find); + $expected = 7; + $this->assertEquals($expected, $result); + + $string = 'МНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыь'; + $find = 'Р'; + $result = Multibyte::strripos($string, $find); + $expected = 36; + $this->assertEquals($expected, $result); + + $string = 'МНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыь'; + $find = 'р'; + $result = Multibyte::strripos($string, $find, 5); + $expected = 36; + $this->assertEquals($expected, $result); + + $string = 'فقكلمنهوىيًٌٍَُ'; + $find = 'ن'; + $result = Multibyte::strripos($string, $find); + $expected = 5; + $this->assertEquals($expected, $result); + + $string = '✰✱✲✳✴✵✶✷✸✹✺✻✼✽✾✿❀❁❂❃❄❅❆❇❈❉❊❋❌❍❎❏❐❑❒❓❔❕❖❗❘❙❚❛❜❝❞'; + $find = '✿'; + $result = Multibyte::strripos($string, $find); + $expected = 15; + $this->assertEquals($expected, $result); + + $string = '⺀⺁⺂⺃⺄⺅⺆⺇⺈⺉⺊⺋⺌⺍⺎⺏⺐⺑⺒⺓⺔⺕⺖⺗⺘⺙⺛⺜⺝⺞⺟⺠⺡⺢⺣⺤⺥⺦⺧⺨⺩⺪⺫⺬⺭⺮⺯⺰⺱⺲⺳⺴⺵⺶⺷⺸⺹⺺⺻⺼⺽⺾⺿⻀⻁⻂⻃⻄⻅⻆⻇⻈⻉⻊⻋⻌⻍⻎⻏⻐⻑⻒⻓⻔⻕⻖⻗⻘⻙⻚⻛⻜⻝⻞⻟⻠'; + $find = '⺐'; + $result = Multibyte::strripos($string, $find); + $expected = 16; + $this->assertEquals($expected, $result); + + $string = '⽅⽆⽇⽈⽉⽊⽋⽌⽍⽎⽏⽐⽑⽒⽓⽔⽕⽖⽗⽘⽙⽚⽛⽜⽝⽞⽟⽠⽡⽢⽣⽤⽥⽦⽧⽨⽩⽪⽫⽬⽭⽮⽯⽰⽱⽲⽳⽴⽵⽶⽷⽸⽹⽺⽻⽼⽽⽾⽿'; + $find = '⽤'; + $result = Multibyte::strripos($string, $find); + $expected = 31; + $this->assertEquals($expected, $result); + + $string = '눡눢눣눤눥눦눧눨눩눪눫눬눭눮눯눰눱눲눳눴눵눶눷눸눹눺눻눼눽눾눿뉀뉁뉂뉃뉄뉅뉆뉇뉈뉉뉊뉋뉌뉍뉎뉏뉐뉑뉒뉓뉔뉕뉖뉗뉘뉙뉚뉛뉜뉝뉞뉟뉠뉡뉢뉣뉤뉥뉦뉧뉨뉩뉪뉫뉬뉭뉮뉯뉰뉱뉲뉳뉴뉵뉶뉷뉸뉹뉺뉻뉼뉽뉾뉿늀늁늂늃늄'; + $find = '눻'; + $result = Multibyte::strripos($string, $find); + $expected = 26; + $this->assertEquals($expected, $result); + + $string = 'ﹰﹱﹲﹳﹴ﹵ﹶﹷﹸﹹﹺﹻﹼﹽﹾﹿﺀﺁﺂﺃﺄﺅﺆﺇﺈﺉﺊﺋﺌﺍﺎﺏﺐﺑﺒﺓﺔﺕﺖﺗﺘﺙﺚﺛﺜﺝﺞﺟﺠﺡﺢﺣﺤﺥﺦﺧﺨﺩﺪﺫﺬﺭﺮﺯﺰ'; + $find = 'ﺞ'; + $result = Multibyte::strripos($string, $find); + $expected = 46; + $this->assertEquals($expected, $result); + + $string = 'ﺱﺲﺳﺴﺵﺶﺷﺸﺹﺺﺻﺼﺽﺾﺿﻀﻁﻂﻃﻄﻅﻆﻇﻈﻉﻊﻋﻌﻍﻎﻏﻐﻑﻒﻓﻔﻕﻖﻗﻘﻙﻚﻛﻜﻝﻞﻟﻠﻡﻢﻣﻤﻥﻦﻧﻨﻩﻪﻫﻬﻭﻮﻯﻰﻱﻲﻳﻴﻵﻶﻷﻸﻹﻺﻻﻼ'; + $find = 'ﻞ'; + $result = Multibyte::strripos($string, $find); + $expected = 45; + $this->assertEquals($expected, $result); + + $string = 'abcdefghijklmnopqrstuvwxyz'; + $find = 'k'; + $result = Multibyte::strripos($string, $find); + $expected = 10; + $this->assertEquals($expected, $result); + + $string = 'abcdefghijklmnopqrstuvwxyz'; + $find = 'k'; + $result = Multibyte::strripos($string, $find); + $expected = 10; + $this->assertEquals($expected, $result); + + $string = 'abcdefghijklmnoppqrstuvwxyz'; + $find = 'pp'; + $result = Multibyte::strripos($string, $find); + $expected = 15; + $this->assertEquals($expected, $result); + + $string = '。「」、・ヲァィゥェォャュョッーアイウエオカキク'; + $find = 'ア'; + $result = Multibyte::strripos($string, $find); + $expected = 16; + $this->assertEquals($expected, $result); + + $string = 'ケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン゙'; + $find = 'ハ'; + $result = Multibyte::strripos($string, $find); + $expected = 17; + $this->assertEquals($expected, $result); + + $string = 'Ĥēĺļŏ, Ŵőřļď!'; + $find = 'ő'; + $result = Multibyte::strripos($string, $find); + $expected = 8; + $this->assertEquals($expected, $result); + + $string = 'Ĥēĺļŏ, Ŵőřļď!'; + $find = 'ő'; + $result = Multibyte::strripos($string, $find); + $expected = 8; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'o'; + $result = Multibyte::strripos($string, $find); + $expected = 8; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'o'; + $result = Multibyte::strripos($string, $find, 5); + $expected = 8; + $this->assertEquals($expected, $result); + + $string = 'čini'; + $find = 'n'; + $result = Multibyte::strripos($string, $find); + $expected = 2; + $this->assertEquals($expected, $result); + + $string = 'čini'; + $find = 'n'; + $result = Multibyte::strripos($string, $find); + $expected = 2; + $this->assertEquals($expected, $result); + + $string = 'moći'; + $find = 'ć'; + $result = Multibyte::strripos($string, $find); + $expected = 2; + $this->assertEquals($expected, $result); + + $string = 'moći'; + $find = 'ć'; + $result = Multibyte::strripos($string, $find); + $expected = 2; + $this->assertEquals($expected, $result); + + $string = 'državni'; + $find = 'ž'; + $result = Multibyte::strripos($string, $find); + $expected = 2; + $this->assertEquals($expected, $result); + + $string = '把百度设为首页'; + $find = '设'; + $result = Multibyte::strripos($string, $find); + $expected = 3; + $this->assertEquals($expected, $result); + + $string = '一二三周永龍'; + $find = '周'; + $result = Multibyte::strripos($string, $find); + $expected = 3; + $this->assertEquals($expected, $result); + + $string = 'državni'; + $find = 'dž'; + $result = Multibyte::strripos($string, $find); + $expected = 0; + $this->assertEquals($expected, $result); + } + +/** + * testUsingMbStrrpos method + * + * @return void + */ + public function testUsingMbStrrpos() { + $this->skipIf(extension_loaded('mbstring') && version_compare(PHP_VERSION, '5.2.0', '<'), 'PHP version does not support $offset parameter in mb_strrpos().'); + + $string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; + $find = 'F'; + $result = mb_strrpos($string, $find); + $expected = 5; + $this->assertEquals($expected, $result); + + $string = 'ABCDEFGHIJKLMNOPQFRSTUVWXYZ0123456789'; + $find = 'F'; + $result = mb_strrpos($string, $find, 6); + $expected = 17; + $this->assertEquals($expected, $result); + + $string = 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ'; + $find = 'Å'; + $result = mb_strrpos($string, $find); + $expected = 5; + $this->assertEquals($expected, $result); + + $string = 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÅÙÚÛÜÝÞ'; + $find = 'ÙÚ'; + $result = mb_strrpos($string, $find); + $expected = 25; + $this->assertEquals($expected, $result); + + $string = 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÅÙÚÛÜÝÞ'; + $find = 'Å'; + $result = mb_strrpos($string, $find, 6); + $expected = 24; + $this->assertEquals($expected, $result); + + $string = 'ĀĂĄĆĈĊČĎĐĒĔĖĘĚĜĞĠĢĤĦĨĪĬĮIJĴĶĹĻĽĿŁŃŅŇŊŌŎŐŒŔŖŘŚŜŞŠŢŤŦŨŪŬŮŰŲŴŶŹŻŽ'; + $find = 'Ċ'; + $result = mb_strrpos($string, $find); + $expected = 5; + $this->assertEquals($expected, $result); + + $string = 'ĀĂĄĆĈĊČĎĐĒĔĖĘĚĜĞĠĢĤĦĨĪĬĮIJĴĶĹĻĽĿŁĊŃŅŇŊŌŎŐŒŔŖŘŚŜŞŠŢŤŦŨŪŬŮŰŲŴŶŹŻŽ'; + $find = 'Ċ'; + $result = mb_strrpos($string, $find, 6); + $expected = 32; + $this->assertEquals($expected, $result); + + $string = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'; + $find = 'F'; + $result = mb_strrpos($string, $find); + $expected = 37; + $this->assertEquals($expected, $result); + + $string = '¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈ'; + $find = 'µ'; + $result = mb_strrpos($string, $find); + $expected = 20; + $this->assertEquals($expected, $result); + + $string = 'ÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬ'; + $find = 'é'; + $result = mb_strrpos($string, $find); + $expected = 32; + $this->assertEquals($expected, $result); + + $string = 'ĭĮįİıIJijĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏƐ'; + $find = 'Ņ'; + $result = mb_strrpos($string, $find); + $expected = 24; + $this->assertEquals($expected, $result); + + $string = 'ƑƒƓƔƕƖƗƘƙƚƛƜƝƞƟƠơƢƣƤƥƦƧƨƩƪƫƬƭƮƯưƱƲƳƴƵƶƷƸƹƺƻƼƽƾƿǀǁǂǃDŽDždžLJLjljNJNjnjǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰDZDzdzǴ'; + $find = 'Ƹ'; + $result = mb_strrpos($string, $find); + $expected = 39; + $this->assertEquals($expected, $result); + + $string = 'ƑƒƓƔƕƖƗƘƙƚƛƜƝƞƟƠơƢƣƤƥƦƧƨƩƪƫƬƭƮƯưƱƲƳƴƵƶƷƸƹƺƻƼƽƾƿǀǁǂǃDŽDždžLJLjljNJNjnjǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰDZDzdzǴ'; + $find = 'ƹ'; + $result = mb_strrpos($string, $find); + $expected = 40; + $this->assertEquals($expected, $result); + + $string = 'əɚɛɜɝɞɟɠɡɢɣɤɥɦɧɨɩɪɫɬɭɮɯɰɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿʀʁʂʃʄʅʆʇʈʉʊʋʌʍʎʏʐʑʒʓʔʕʖʗʘʙʚʛʜʝʞʟʠʡʢʣʤʥʦʧʨʩʪʫʬʭʮʯʰʱʲʳʴʵʶʷʸʹʺʻʼ'; + $find = 'ʀ'; + $result = mb_strrpos($string, $find); + $expected = 39; + $this->assertEquals($expected, $result); + + $string = 'ЀЁЂЃЄЅІЇЈЉЊЋЌЍЎЏАБВГДЕЖЗИЙКЛ'; + $find = 'Ї'; + $result = mb_strrpos($string, $find); + $expected = 7; + $this->assertEquals($expected, $result); + + $string = 'МНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыь'; + $find = 'Р'; + $result = mb_strrpos($string, $find); + $expected = 4; + $this->assertEquals($expected, $result); + + $string = 'МНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыь'; + $find = 'р'; + $result = mb_strrpos($string, $find, 5); + $expected = 36; + $this->assertEquals($expected, $result); + + $string = 'فقكلمنهوىيًٌٍَُ'; + $find = 'ن'; + $result = mb_strrpos($string, $find); + $expected = 5; + $this->assertEquals($expected, $result); + + $string = '✰✱✲✳✴✵✶✷✸✹✺✻✼✽✾✿❀❁❂❃❄❅❆❇❈❉❊❋❌❍❎❏❐❑❒❓❔❕❖❗❘❙❚❛❜❝❞'; + $find = '✿'; + $result = mb_strrpos($string, $find); + $expected = 15; + $this->assertEquals($expected, $result); + + $string = '⺀⺁⺂⺃⺄⺅⺆⺇⺈⺉⺊⺋⺌⺍⺎⺏⺐⺑⺒⺓⺔⺕⺖⺗⺘⺙⺛⺜⺝⺞⺟⺠⺡⺢⺣⺤⺥⺦⺧⺨⺩⺪⺫⺬⺭⺮⺯⺰⺱⺲⺳⺴⺵⺶⺷⺸⺹⺺⺻⺼⺽⺾⺿⻀⻁⻂⻃⻄⻅⻆⻇⻈⻉⻊⻋⻌⻍⻎⻏⻐⻑⻒⻓⻔⻕⻖⻗⻘⻙⻚⻛⻜⻝⻞⻟⻠'; + $find = '⺐'; + $result = mb_strrpos($string, $find); + $expected = 16; + $this->assertEquals($expected, $result); + + $string = '⽅⽆⽇⽈⽉⽊⽋⽌⽍⽎⽏⽐⽑⽒⽓⽔⽕⽖⽗⽘⽙⽚⽛⽜⽝⽞⽟⽠⽡⽢⽣⽤⽥⽦⽧⽨⽩⽪⽫⽬⽭⽮⽯⽰⽱⽲⽳⽴⽵⽶⽷⽸⽹⽺⽻⽼⽽⽾⽿'; + $find = '⽤'; + $result = mb_strrpos($string, $find); + $expected = 31; + $this->assertEquals($expected, $result); + + $string = '눡눢눣눤눥눦눧눨눩눪눫눬눭눮눯눰눱눲눳눴눵눶눷눸눹눺눻눼눽눾눿뉀뉁뉂뉃뉄뉅뉆뉇뉈뉉뉊뉋뉌뉍뉎뉏뉐뉑뉒뉓뉔뉕뉖뉗뉘뉙뉚뉛뉜뉝뉞뉟뉠뉡뉢뉣뉤뉥뉦뉧뉨뉩뉪뉫뉬뉭뉮뉯뉰뉱뉲뉳뉴뉵뉶뉷뉸뉹뉺뉻뉼뉽뉾뉿늀늁늂늃늄'; + $find = '눻'; + $result = mb_strrpos($string, $find); + $expected = 26; + $this->assertEquals($expected, $result); + + $string = 'ﹰﹱﹲﹳﹴ﹵ﹶﹷﹸﹹﹺﹻﹼﹽﹾﹿﺀﺁﺂﺃﺄﺅﺆﺇﺈﺉﺊﺋﺌﺍﺎﺏﺐﺑﺒﺓﺔﺕﺖﺗﺘﺙﺚﺛﺜﺝﺞﺟﺠﺡﺢﺣﺤﺥﺦﺧﺨﺩﺪﺫﺬﺭﺮﺯﺰ'; + $find = 'ﺞ'; + $result = mb_strrpos($string, $find); + $expected = 46; + $this->assertEquals($expected, $result); + + $string = 'ﺱﺲﺳﺴﺵﺶﺷﺸﺹﺺﺻﺼﺽﺾﺿﻀﻁﻂﻃﻄﻅﻆﻇﻈﻉﻊﻋﻌﻍﻎﻏﻐﻑﻒﻓﻔﻕﻖﻗﻘﻙﻚﻛﻜﻝﻞﻟﻠﻡﻢﻣﻤﻥﻦﻧﻨﻩﻪﻫﻬﻭﻮﻯﻰﻱﻲﻳﻴﻵﻶﻷﻸﻹﻺﻻﻼ'; + $find = 'ﻞ'; + $result = mb_strrpos($string, $find); + $expected = 45; + $this->assertEquals($expected, $result); + + $string = 'abcdefghijklmnopqrstuvwxyz'; + $find = 'k'; + $result = mb_strrpos($string, $find); + $expected = 10; + $this->assertEquals($expected, $result); + + $string = 'abcdefghijklmnopqrstuvwxyz'; + $find = 'k'; + $result = mb_strrpos($string, $find); + $expected = 10; + $this->assertEquals($expected, $result); + + $string = 'abcdefghijklmnoppqrstuvwxyz'; + $find = 'pp'; + $result = mb_strrpos($string, $find); + $expected = 15; + $this->assertEquals($expected, $result); + + $string = '。「」、・ヲァィゥェォャュョッーアイウエオカキク'; + $find = 'ア'; + $result = mb_strrpos($string, $find); + $expected = 16; + $this->assertEquals($expected, $result); + + $string = 'ケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン゙'; + $find = 'ハ'; + $result = mb_strrpos($string, $find); + $expected = 17; + $this->assertEquals($expected, $result); + + $string = 'Ĥēĺļŏ, Ŵőřļď!'; + $find = 'ő'; + $result = mb_strrpos($string, $find); + $expected = 8; + $this->assertEquals($expected, $result); + + $string = 'Ĥēĺļŏ, Ŵőřļď!'; + $find = 'ő'; + $result = mb_strrpos($string, $find); + $expected = 8; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'o'; + $result = mb_strrpos($string, $find); + $expected = 8; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'o'; + $result = mb_strrpos($string, $find, 5); + $expected = 8; + $this->assertEquals($expected, $result); + + $string = 'čini'; + $find = 'n'; + $result = mb_strrpos($string, $find); + $expected = 2; + $this->assertEquals($expected, $result); + + $string = 'čini'; + $find = 'n'; + $result = mb_strrpos($string, $find); + $expected = 2; + $this->assertEquals($expected, $result); + + $string = 'moći'; + $find = 'ć'; + $result = mb_strrpos($string, $find); + $expected = 2; + $this->assertEquals($expected, $result); + + $string = 'moći'; + $find = 'ć'; + $result = mb_strrpos($string, $find); + $expected = 2; + $this->assertEquals($expected, $result); + + $string = 'državni'; + $find = 'ž'; + $result = mb_strrpos($string, $find); + $expected = 2; + $this->assertEquals($expected, $result); + + $string = '把百度设为首页'; + $find = '设'; + $result = mb_strrpos($string, $find); + $expected = 3; + $this->assertEquals($expected, $result); + + $string = '一二三周永龍'; + $find = '周'; + $result = mb_strrpos($string, $find); + $expected = 3; + $this->assertEquals($expected, $result); + + $string = 'Ĥēĺļŏ, Ŵőřļď!'; + $find = 'H'; + $result = mb_strrpos($string, $find); + $expected = false; + $this->assertEquals($expected, $result); + } + +/** + * testMultibyteStrrpos method + * + * @return void + */ + public function testMultibyteStrrpos() { + $string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; + $find = 'F'; + $result = Multibyte::strrpos($string, $find); + $expected = 5; + $this->assertEquals($expected, $result); + + $string = 'ABCDEFGHIJKLMNOPQFRSTUVWXYZ0123456789'; + $find = 'F'; + $result = Multibyte::strrpos($string, $find, 6); + $expected = 17; + $this->assertEquals($expected, $result); + + $string = 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ'; + $find = 'Å'; + $result = Multibyte::strrpos($string, $find); + $expected = 5; + $this->assertEquals($expected, $result); + + $string = 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÅÙÚÛÜÝÞ'; + $find = 'Å'; + $result = Multibyte::strrpos($string, $find, 6); + $expected = 24; + $this->assertEquals($expected, $result); + + $string = 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÅÙÚÛÜÝÞ'; + $find = 'ÙÚ'; + $result = Multibyte::strrpos($string, $find); + $expected = 25; + $this->assertEquals($expected, $result); + + $string = 'ĀĂĄĆĈĊČĎĐĒĔĖĘĚĜĞĠĢĤĦĨĪĬĮIJĴĶĹĻĽĿŁŃŅŇŊŌŎŐŒŔŖŘŚŜŞŠŢŤŦŨŪŬŮŰŲŴŶŹŻŽ'; + $find = 'Ċ'; + $result = Multibyte::strrpos($string, $find); + $expected = 5; + $this->assertEquals($expected, $result); + + $string = 'ĀĂĄĆĈĊČĎĐĒĔĖĘĚĜĞĠĢĤĦĨĪĬĮIJĴĶĹĻĽĿŁĊŃŅŇŊŌŎŐŒŔŖŘŚŜŞŠŢŤŦŨŪŬŮŰŲŴŶŹŻŽ'; + $find = 'Ċ'; + $result = Multibyte::strrpos($string, $find, 6); + $expected = 32; + $this->assertEquals($expected, $result); + + $string = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'; + $find = 'F'; + $result = Multibyte::strrpos($string, $find); + $expected = 37; + $this->assertEquals($expected, $result); + + $string = '¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈ'; + $find = 'µ'; + $result = Multibyte::strrpos($string, $find); + $expected = 20; + $this->assertEquals($expected, $result); + + $string = 'ÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬ'; + $find = 'é'; + $result = Multibyte::strrpos($string, $find); + $expected = 32; + $this->assertEquals($expected, $result); + + $string = 'ĭĮįİıIJijĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏƐ'; + $find = 'Ņ'; + $result = Multibyte::strrpos($string, $find); + $expected = 24; + $this->assertEquals($expected, $result); + + $string = 'ƑƒƓƔƕƖƗƘƙƚƛƜƝƞƟƠơƢƣƤƥƦƧƨƩƪƫƬƭƮƯưƱƲƳƴƵƶƷƸƹƺƻƼƽƾƿǀǁǂǃDŽDždžLJLjljNJNjnjǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰDZDzdzǴ'; + $find = 'Ƹ'; + $result = Multibyte::strrpos($string, $find); + $expected = 39; + $this->assertEquals($expected, $result); + + $string = 'ƑƒƓƔƕƖƗƘƙƚƛƜƝƞƟƠơƢƣƤƥƦƧƨƩƪƫƬƭƮƯưƱƲƳƴƵƶƷƸƹƺƻƼƽƾƿǀǁǂǃDŽDždžLJLjljNJNjnjǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰDZDzdzǴ'; + $find = 'ƹ'; + $result = Multibyte::strrpos($string, $find); + $expected = 40; + $this->assertEquals($expected, $result); + + $string = 'əɚɛɜɝɞɟɠɡɢɣɤɥɦɧɨɩɪɫɬɭɮɯɰɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿʀʁʂʃʄʅʆʇʈʉʊʋʌʍʎʏʐʑʒʓʔʕʖʗʘʙʚʛʜʝʞʟʠʡʢʣʤʥʦʧʨʩʪʫʬʭʮʯʰʱʲʳʴʵʶʷʸʹʺʻʼ'; + $find = 'ʀ'; + $result = Multibyte::strrpos($string, $find); + $expected = 39; + $this->assertEquals($expected, $result); + + $string = 'ЀЁЂЃЄЅІЇЈЉЊЋЌЍЎЏАБВГДЕЖЗИЙКЛ'; + $find = 'Ї'; + $result = Multibyte::strrpos($string, $find); + $expected = 7; + $this->assertEquals($expected, $result); + + $string = 'МНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыь'; + $find = 'Р'; + $result = Multibyte::strrpos($string, $find); + $expected = 4; + $this->assertEquals($expected, $result); + + $string = 'МНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыь'; + $find = 'р'; + $result = Multibyte::strrpos($string, $find, 5); + $expected = 36; + $this->assertEquals($expected, $result); + + $string = 'فقكلمنهوىيًٌٍَُ'; + $find = 'ن'; + $result = Multibyte::strrpos($string, $find); + $expected = 5; + $this->assertEquals($expected, $result); + + $string = '✰✱✲✳✴✵✶✷✸✹✺✻✼✽✾✿❀❁❂❃❄❅❆❇❈❉❊❋❌❍❎❏❐❑❒❓❔❕❖❗❘❙❚❛❜❝❞'; + $find = '✿'; + $result = Multibyte::strrpos($string, $find); + $expected = 15; + $this->assertEquals($expected, $result); + + $string = '⺀⺁⺂⺃⺄⺅⺆⺇⺈⺉⺊⺋⺌⺍⺎⺏⺐⺑⺒⺓⺔⺕⺖⺗⺘⺙⺛⺜⺝⺞⺟⺠⺡⺢⺣⺤⺥⺦⺧⺨⺩⺪⺫⺬⺭⺮⺯⺰⺱⺲⺳⺴⺵⺶⺷⺸⺹⺺⺻⺼⺽⺾⺿⻀⻁⻂⻃⻄⻅⻆⻇⻈⻉⻊⻋⻌⻍⻎⻏⻐⻑⻒⻓⻔⻕⻖⻗⻘⻙⻚⻛⻜⻝⻞⻟⻠'; + $find = '⺐'; + $result = Multibyte::strrpos($string, $find); + $expected = 16; + $this->assertEquals($expected, $result); + + $string = '⽅⽆⽇⽈⽉⽊⽋⽌⽍⽎⽏⽐⽑⽒⽓⽔⽕⽖⽗⽘⽙⽚⽛⽜⽝⽞⽟⽠⽡⽢⽣⽤⽥⽦⽧⽨⽩⽪⽫⽬⽭⽮⽯⽰⽱⽲⽳⽴⽵⽶⽷⽸⽹⽺⽻⽼⽽⽾⽿'; + $find = '⽤'; + $result = Multibyte::strrpos($string, $find); + $expected = 31; + $this->assertEquals($expected, $result); + + $string = '눡눢눣눤눥눦눧눨눩눪눫눬눭눮눯눰눱눲눳눴눵눶눷눸눹눺눻눼눽눾눿뉀뉁뉂뉃뉄뉅뉆뉇뉈뉉뉊뉋뉌뉍뉎뉏뉐뉑뉒뉓뉔뉕뉖뉗뉘뉙뉚뉛뉜뉝뉞뉟뉠뉡뉢뉣뉤뉥뉦뉧뉨뉩뉪뉫뉬뉭뉮뉯뉰뉱뉲뉳뉴뉵뉶뉷뉸뉹뉺뉻뉼뉽뉾뉿늀늁늂늃늄'; + $find = '눻'; + $result = Multibyte::strrpos($string, $find); + $expected = 26; + $this->assertEquals($expected, $result); + + $string = 'ﹰﹱﹲﹳﹴ﹵ﹶﹷﹸﹹﹺﹻﹼﹽﹾﹿﺀﺁﺂﺃﺄﺅﺆﺇﺈﺉﺊﺋﺌﺍﺎﺏﺐﺑﺒﺓﺔﺕﺖﺗﺘﺙﺚﺛﺜﺝﺞﺟﺠﺡﺢﺣﺤﺥﺦﺧﺨﺩﺪﺫﺬﺭﺮﺯﺰ'; + $find = 'ﺞ'; + $result = Multibyte::strrpos($string, $find); + $expected = 46; + $this->assertEquals($expected, $result); + + $string = 'ﺱﺲﺳﺴﺵﺶﺷﺸﺹﺺﺻﺼﺽﺾﺿﻀﻁﻂﻃﻄﻅﻆﻇﻈﻉﻊﻋﻌﻍﻎﻏﻐﻑﻒﻓﻔﻕﻖﻗﻘﻙﻚﻛﻜﻝﻞﻟﻠﻡﻢﻣﻤﻥﻦﻧﻨﻩﻪﻫﻬﻭﻮﻯﻰﻱﻲﻳﻴﻵﻶﻷﻸﻹﻺﻻﻼ'; + $find = 'ﻞ'; + $result = Multibyte::strrpos($string, $find); + $expected = 45; + $this->assertEquals($expected, $result); + + $string = 'abcdefghijklmnopqrstuvwxyz'; + $find = 'k'; + $result = Multibyte::strrpos($string, $find); + $expected = 10; + $this->assertEquals($expected, $result); + + $string = 'abcdefghijklmnopqrstuvwxyz'; + $find = 'k'; + $result = Multibyte::strrpos($string, $find); + $expected = 10; + $this->assertEquals($expected, $result); + + $string = 'abcdefghijklmnoppqrstuvwxyz'; + $find = 'pp'; + $result = Multibyte::strrpos($string, $find); + $expected = 15; + $this->assertEquals($expected, $result); + + $string = '。「」、・ヲァィゥェォャュョッーアイウエオカキク'; + $find = 'ア'; + $result = Multibyte::strrpos($string, $find); + $expected = 16; + $this->assertEquals($expected, $result); + + $string = 'ケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン゙'; + $find = 'ハ'; + $result = Multibyte::strrpos($string, $find); + $expected = 17; + $this->assertEquals($expected, $result); + + $string = 'Ĥēĺļŏ, Ŵőřļď!'; + $find = 'ő'; + $result = Multibyte::strrpos($string, $find); + $expected = 8; + $this->assertEquals($expected, $result); + + $string = 'Ĥēĺļŏ, Ŵőřļď!'; + $find = 'ő'; + $result = Multibyte::strrpos($string, $find); + $expected = 8; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'o'; + $result = Multibyte::strrpos($string, $find); + $expected = 8; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'o'; + $result = Multibyte::strrpos($string, $find, 5); + $expected = 8; + $this->assertEquals($expected, $result); + + $string = 'čini'; + $find = 'n'; + $result = Multibyte::strrpos($string, $find); + $expected = 2; + $this->assertEquals($expected, $result); + + $string = 'čini'; + $find = 'n'; + $result = Multibyte::strrpos($string, $find); + $expected = 2; + $this->assertEquals($expected, $result); + + $string = 'moći'; + $find = 'ć'; + $result = Multibyte::strrpos($string, $find); + $expected = 2; + $this->assertEquals($expected, $result); + + $string = 'moći'; + $find = 'ć'; + $result = Multibyte::strrpos($string, $find); + $expected = 2; + $this->assertEquals($expected, $result); + + $string = 'državni'; + $find = 'ž'; + $result = Multibyte::strrpos($string, $find); + $expected = 2; + $this->assertEquals($expected, $result); + + $string = '把百度设为首页'; + $find = '设'; + $result = Multibyte::strrpos($string, $find); + $expected = 3; + $this->assertEquals($expected, $result); + + $string = '一二三周永龍'; + $find = '周'; + $result = Multibyte::strrpos($string, $find); + $expected = 3; + $this->assertEquals($expected, $result); + + $string = 'Ĥēĺļŏ, Ŵőřļď!'; + $find = 'H'; + $result = Multibyte::strrpos($string, $find); + $expected = false; + $this->assertEquals($expected, $result); + } + +/** + * testUsingMbStrstr method + * + * @return void + */ + public function testUsingMbStrstr() { + $string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; + $find = 'F'; + $result = mb_strstr($string, $find); + $expected = 'FGHIJKLMNOPQRSTUVWXYZ0123456789'; + $this->assertEquals($expected, $result); + + $string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; + $find = 'F'; + $result = mb_strstr($string, $find, true); + $expected = 'ABCDE'; + $this->assertEquals($expected, $result); + + $string = 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ'; + $find = 'Å'; + $result = mb_strstr($string, $find); + $expected = 'ÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ'; + $this->assertEquals($expected, $result); + + $string = 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ'; + $find = 'Å'; + $result = mb_strstr($string, $find, true); + $expected = 'ÀÁÂÃÄ'; + $this->assertEquals($expected, $result); + + $string = 'ĀĂĄĆĈĊČĎĐĒĔĖĘĚĜĞĠĢĤĦĨĪĬĮIJĴĶĹĻĽĿŁŃŅŇŊŌŎŐŒŔŖŘŚŜŞŠŢŤŦŨŪŬŮŰŲŴŶŹŻŽ'; + $find = 'Ċ'; + $result = mb_strstr($string, $find); + $expected = 'ĊČĎĐĒĔĖĘĚĜĞĠĢĤĦĨĪĬĮIJĴĶĹĻĽĿŁŃŅŇŊŌŎŐŒŔŖŘŚŜŞŠŢŤŦŨŪŬŮŰŲŴŶŹŻŽ'; + $this->assertEquals($expected, $result); + + $string = 'ĀĂĄĆĈĊČĎĐĒĔĖĘĚĜĞĠĢĤĦĨĪĬĮIJĴĶĹĻĽĿŁŃŅŇŊŌŎŐŒŔŖŘŚŜŞŠŢŤŦŨŪŬŮŰŲŴŶŹŻŽ'; + $find = 'Ċ'; + $result = mb_strstr($string, $find, true); + $expected = 'ĀĂĄĆĈ'; + $this->assertEquals($expected, $result); + + $string = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'; + $find = 'F'; + $result = mb_strstr($string, $find); + $expected = 'FGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'; + $this->assertEquals($expected, $result); + + $string = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'; + $find = 'F'; + $result = mb_strstr($string, $find, true); + $expected = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDE'; + $this->assertEquals($expected, $result); + + $string = '¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈ'; + $find = 'µ'; + $result = mb_strstr($string, $find); + $expected = 'µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈ'; + $this->assertEquals($expected, $result); + + $string = '¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈ'; + $find = 'µ'; + $result = mb_strstr($string, $find, true); + $expected = '¡¢£¤¥¦§¨©ª«¬­®¯°±²³´'; + $this->assertEquals($expected, $result); + + $string = 'ÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬ'; + $find = 'Þ'; + $result = mb_strstr($string, $find); + $expected = 'Þßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬ'; + $this->assertEquals($expected, $result); + + $string = 'ÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬ'; + $find = 'Þ'; + $result = mb_strstr($string, $find, true); + $expected = 'ÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝ'; + $this->assertEquals($expected, $result); + + $string = 'ĭĮįİıIJijĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏƐ'; + $find = 'Ņ'; + $result = mb_strstr($string, $find); + $expected = 'ŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏƐ'; + $this->assertEquals($expected, $result); + + $string = 'ĭĮįİıIJijĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏƐ'; + $find = 'Ņ'; + $result = mb_strstr($string, $find, true); + $expected = 'ĭĮįİıIJijĴĵĶķĸĹĺĻļĽľĿŀŁłŃń'; + $this->assertEquals($expected, $result); + + $string = 'ƑƒƓƔƕƖƗƘƙƚƛƜƝƞƟƠơƢƣƤƥƦƧƨƩƪƫƬƭƮƯưƱƲƳƴƵƶƷƸƹƺƻƼƽƾƿǀǁǂǃDŽDždžLJLjljNJNjnjǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰDZDzdzǴ'; + $find = 'Ƹ'; + $result = mb_strstr($string, $find); + $expected = 'ƸƹƺƻƼƽƾƿǀǁǂǃDŽDždžLJLjljNJNjnjǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰDZDzdzǴ'; + $this->assertEquals($expected, $result); + + $find = 'Ƹ'; + $result = mb_strstr($string, $find, true); + $expected = 'ƑƒƓƔƕƖƗƘƙƚƛƜƝƞƟƠơƢƣƤƥƦƧƨƩƪƫƬƭƮƯưƱƲƳƴƵƶƷ'; + $this->assertEquals($expected, $result); + + $string = 'əɚɛɜɝɞɟɠɡɢɣɤɥɦɧɨɩɪɫɬɭɮɯɰɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿʀʁʂʃʄʅʆʇʈʉʊʋʌʍʎʏʐʑʒʓʔʕʖʗʘʙʚʛʜʝʞʟʠʡʢʣʤʥʦʧʨʩʪʫʬʭʮʯʰʱʲʳʴʵʶʷʸʹʺʻʼ'; + $find = 'ʀ'; + $result = mb_strstr($string, $find); + $expected = 'ʀʁʂʃʄʅʆʇʈʉʊʋʌʍʎʏʐʑʒʓʔʕʖʗʘʙʚʛʜʝʞʟʠʡʢʣʤʥʦʧʨʩʪʫʬʭʮʯʰʱʲʳʴʵʶʷʸʹʺʻʼ'; + $this->assertEquals($expected, $result); + + $string = 'əɚɛɜɝɞɟɠɡɢɣɤɥɦɧɨɩɪɫɬɭɮɯɰɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿʀʁʂʃʄʅʆʇʈʉʊʋʌʍʎʏʐʑʒʓʔʕʖʗʘʙʚʛʜʝʞʟʠʡʢʣʤʥʦʧʨʩʪʫʬʭʮʯʰʱʲʳʴʵʶʷʸʹʺʻʼ'; + $find = 'ʀ'; + $result = mb_strstr($string, $find, true); + $expected = 'əɚɛɜɝɞɟɠɡɢɣɤɥɦɧɨɩɪɫɬɭɮɯɰɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿ'; + $this->assertEquals($expected, $result); + + $string = 'ЀЁЂЃЄЅІЇЈЉЊЋЌЍЎЏАБВГДЕЖЗИЙКЛ'; + $find = 'Ї'; + $result = mb_strstr($string, $find); + $expected = 'ЇЈЉЊЋЌЍЎЏАБВГДЕЖЗИЙКЛ'; + $this->assertEquals($expected, $result); + + $string = 'ЀЁЂЃЄЅІЇЈЉЊЋЌЍЎЏАБВГДЕЖЗИЙКЛ'; + $find = 'Ї'; + $result = mb_strstr($string, $find, true); + $expected = 'ЀЁЂЃЄЅІ'; + $this->assertEquals($expected, $result); + + $string = 'МНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыь'; + $find = 'Р'; + $result = mb_strstr($string, $find); + $expected = 'РСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыь'; + $this->assertEquals($expected, $result); + + $string = 'МНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыь'; + $find = 'Р'; + $result = mb_strstr($string, $find, true); + $expected = 'МНОП'; + $this->assertEquals($expected, $result); + + $string = 'فقكلمنهوىيًٌٍَُ'; + $find = 'ن'; + $result = mb_strstr($string, $find); + $expected = 'نهوىيًٌٍَُ'; + $this->assertEquals($expected, $result); + + $string = 'فقكلمنهوىيًٌٍَُ'; + $find = 'ن'; + $result = mb_strstr($string, $find, true); + $expected = 'فقكلم'; + $this->assertEquals($expected, $result); + + $string = '✰✱✲✳✴✵✶✷✸✹✺✻✼✽✾✿❀❁❂❃❄❅❆❇❈❉❊❋❌❍❎❏❐❑❒❓❔❕❖❗❘❙❚❛❜❝❞'; + $find = '✿'; + $result = mb_strstr($string, $find); + $expected = '✿❀❁❂❃❄❅❆❇❈❉❊❋❌❍❎❏❐❑❒❓❔❕❖❗❘❙❚❛❜❝❞'; + $this->assertEquals($expected, $result); + + $string = '✰✱✲✳✴✵✶✷✸✹✺✻✼✽✾✿❀❁❂❃❄❅❆❇❈❉❊❋❌❍❎❏❐❑❒❓❔❕❖❗❘❙❚❛❜❝❞'; + $find = '✿'; + $result = mb_strstr($string, $find, true); + $expected = '✰✱✲✳✴✵✶✷✸✹✺✻✼✽✾'; + $this->assertEquals($expected, $result); + + $string = '⺀⺁⺂⺃⺄⺅⺆⺇⺈⺉⺊⺋⺌⺍⺎⺏⺐⺑⺒⺓⺔⺕⺖⺗⺘⺙⺛⺜⺝⺞⺟⺠⺡⺢⺣⺤⺥⺦⺧⺨⺩⺪⺫⺬⺭⺮⺯⺰⺱⺲⺳⺴⺵⺶⺷⺸⺹⺺⺻⺼⺽⺾⺿⻀⻁⻂⻃⻄⻅⻆⻇⻈⻉⻊⻋⻌⻍⻎⻏⻐⻑⻒⻓⻔⻕⻖⻗⻘⻙⻚⻛⻜⻝⻞⻟⻠'; + $find = '⺐'; + $result = mb_strstr($string, $find); + $expected = '⺐⺑⺒⺓⺔⺕⺖⺗⺘⺙⺛⺜⺝⺞⺟⺠⺡⺢⺣⺤⺥⺦⺧⺨⺩⺪⺫⺬⺭⺮⺯⺰⺱⺲⺳⺴⺵⺶⺷⺸⺹⺺⺻⺼⺽⺾⺿⻀⻁⻂⻃⻄⻅⻆⻇⻈⻉⻊⻋⻌⻍⻎⻏⻐⻑⻒⻓⻔⻕⻖⻗⻘⻙⻚⻛⻜⻝⻞⻟⻠'; + $this->assertEquals($expected, $result); + + $string = '⺀⺁⺂⺃⺄⺅⺆⺇⺈⺉⺊⺋⺌⺍⺎⺏⺐⺑⺒⺓⺔⺕⺖⺗⺘⺙⺛⺜⺝⺞⺟⺠⺡⺢⺣⺤⺥⺦⺧⺨⺩⺪⺫⺬⺭⺮⺯⺰⺱⺲⺳⺴⺵⺶⺷⺸⺹⺺⺻⺼⺽⺾⺿⻀⻁⻂⻃⻄⻅⻆⻇⻈⻉⻊⻋⻌⻍⻎⻏⻐⻑⻒⻓⻔⻕⻖⻗⻘⻙⻚⻛⻜⻝⻞⻟⻠'; + $find = '⺐'; + $result = mb_strstr($string, $find, true); + $expected = '⺀⺁⺂⺃⺄⺅⺆⺇⺈⺉⺊⺋⺌⺍⺎⺏'; + $this->assertEquals($expected, $result); + + $string = '⽅⽆⽇⽈⽉⽊⽋⽌⽍⽎⽏⽐⽑⽒⽓⽔⽕⽖⽗⽘⽙⽚⽛⽜⽝⽞⽟⽠⽡⽢⽣⽤⽥⽦⽧⽨⽩⽪⽫⽬⽭⽮⽯⽰⽱⽲⽳⽴⽵⽶⽷⽸⽹⽺⽻⽼⽽⽾⽿'; + $find = '⽤'; + $result = mb_strstr($string, $find); + $expected = '⽤⽥⽦⽧⽨⽩⽪⽫⽬⽭⽮⽯⽰⽱⽲⽳⽴⽵⽶⽷⽸⽹⽺⽻⽼⽽⽾⽿'; + $this->assertEquals($expected, $result); + + $string = '⽅⽆⽇⽈⽉⽊⽋⽌⽍⽎⽏⽐⽑⽒⽓⽔⽕⽖⽗⽘⽙⽚⽛⽜⽝⽞⽟⽠⽡⽢⽣⽤⽥⽦⽧⽨⽩⽪⽫⽬⽭⽮⽯⽰⽱⽲⽳⽴⽵⽶⽷⽸⽹⽺⽻⽼⽽⽾⽿'; + $find = '⽤'; + $result = mb_strstr($string, $find, true); + $expected = '⽅⽆⽇⽈⽉⽊⽋⽌⽍⽎⽏⽐⽑⽒⽓⽔⽕⽖⽗⽘⽙⽚⽛⽜⽝⽞⽟⽠⽡⽢⽣'; + $this->assertEquals($expected, $result); + + $string = '눡눢눣눤눥눦눧눨눩눪눫눬눭눮눯눰눱눲눳눴눵눶눷눸눹눺눻눼눽눾눿뉀뉁뉂뉃뉄뉅뉆뉇뉈뉉뉊뉋뉌뉍뉎뉏뉐뉑뉒뉓뉔뉕뉖뉗뉘뉙뉚뉛뉜뉝뉞뉟뉠뉡뉢뉣뉤뉥뉦뉧뉨뉩뉪뉫뉬뉭뉮뉯뉰뉱뉲뉳뉴뉵뉶뉷뉸뉹뉺뉻뉼뉽뉾뉿늀늁늂늃늄'; + $find = '눻'; + $result = mb_strstr($string, $find); + $expected = '눻눼눽눾눿뉀뉁뉂뉃뉄뉅뉆뉇뉈뉉뉊뉋뉌뉍뉎뉏뉐뉑뉒뉓뉔뉕뉖뉗뉘뉙뉚뉛뉜뉝뉞뉟뉠뉡뉢뉣뉤뉥뉦뉧뉨뉩뉪뉫뉬뉭뉮뉯뉰뉱뉲뉳뉴뉵뉶뉷뉸뉹뉺뉻뉼뉽뉾뉿늀늁늂늃늄'; + $this->assertEquals($expected, $result); + + $string = '눡눢눣눤눥눦눧눨눩눪눫눬눭눮눯눰눱눲눳눴눵눶눷눸눹눺눻눼눽눾눿뉀뉁뉂뉃뉄뉅뉆뉇뉈뉉뉊뉋뉌뉍뉎뉏뉐뉑뉒뉓뉔뉕뉖뉗뉘뉙뉚뉛뉜뉝뉞뉟뉠뉡뉢뉣뉤뉥뉦뉧뉨뉩뉪뉫뉬뉭뉮뉯뉰뉱뉲뉳뉴뉵뉶뉷뉸뉹뉺뉻뉼뉽뉾뉿늀늁늂늃늄'; + $find = '눻'; + $result = mb_strstr($string, $find, true); + $expected = '눡눢눣눤눥눦눧눨눩눪눫눬눭눮눯눰눱눲눳눴눵눶눷눸눹눺'; + $this->assertEquals($expected, $result); + + $string = 'ﹰﹱﹲﹳﹴ﹵ﹶﹷﹸﹹﹺﹻﹼﹽﹾﹿﺀﺁﺂﺃﺄﺅﺆﺇﺈﺉﺊﺋﺌﺍﺎﺏﺐﺑﺒﺓﺔﺕﺖﺗﺘﺙﺚﺛﺜﺝﺞﺟﺠﺡﺢﺣﺤﺥﺦﺧﺨﺩﺪﺫﺬﺭﺮﺯﺰ'; + $find = 'ﺞ'; + $result = mb_strstr($string, $find); + $expected = 'ﺞﺟﺠﺡﺢﺣﺤﺥﺦﺧﺨﺩﺪﺫﺬﺭﺮﺯﺰ'; + $this->assertEquals($expected, $result); + + $string = 'ﹰﹱﹲﹳﹴ﹵ﹶﹷﹸﹹﹺﹻﹼﹽﹾﹿﺀﺁﺂﺃﺄﺅﺆﺇﺈﺉﺊﺋﺌﺍﺎﺏﺐﺑﺒﺓﺔﺕﺖﺗﺘﺙﺚﺛﺜﺝﺞﺟﺠﺡﺢﺣﺤﺥﺦﺧﺨﺩﺪﺫﺬﺭﺮﺯﺰ'; + $find = 'ﺞ'; + $result = mb_strstr($string, $find, true); + $expected = 'ﹰﹱﹲﹳﹴ﹵ﹶﹷﹸﹹﹺﹻﹼﹽﹾﹿﺀﺁﺂﺃﺄﺅﺆﺇﺈﺉﺊﺋﺌﺍﺎﺏﺐﺑﺒﺓﺔﺕﺖﺗﺘﺙﺚﺛﺜﺝ'; + $this->assertEquals($expected, $result); + + $string = 'ﺱﺲﺳﺴﺵﺶﺷﺸﺹﺺﺻﺼﺽﺾﺿﻀﻁﻂﻃﻄﻅﻆﻇﻈﻉﻊﻋﻌﻍﻎﻏﻐﻑﻒﻓﻔﻕﻖﻗﻘﻙﻚﻛﻜﻝﻞﻟﻠﻡﻢﻣﻤﻥﻦﻧﻨﻩﻪﻫﻬﻭﻮﻯﻰﻱﻲﻳﻴﻵﻶﻷﻸﻹﻺﻻﻼ'; + $find = 'ﻞ'; + $result = mb_strstr($string, $find); + $expected = 'ﻞﻟﻠﻡﻢﻣﻤﻥﻦﻧﻨﻩﻪﻫﻬﻭﻮﻯﻰﻱﻲﻳﻴﻵﻶﻷﻸﻹﻺﻻﻼ'; + $this->assertEquals($expected, $result); + + $string = 'ﺱﺲﺳﺴﺵﺶﺷﺸﺹﺺﺻﺼﺽﺾﺿﻀﻁﻂﻃﻄﻅﻆﻇﻈﻉﻊﻋﻌﻍﻎﻏﻐﻑﻒﻓﻔﻕﻖﻗﻘﻙﻚﻛﻜﻝﻞﻟﻠﻡﻢﻣﻤﻥﻦﻧﻨﻩﻪﻫﻬﻭﻮﻯﻰﻱﻲﻳﻴﻵﻶﻷﻸﻹﻺﻻﻼ'; + $find = 'ﻞ'; + $result = mb_strstr($string, $find, true); + $expected = 'ﺱﺲﺳﺴﺵﺶﺷﺸﺹﺺﺻﺼﺽﺾﺿﻀﻁﻂﻃﻄﻅﻆﻇﻈﻉﻊﻋﻌﻍﻎﻏﻐﻑﻒﻓﻔﻕﻖﻗﻘﻙﻚﻛﻜﻝ'; + $this->assertEquals($expected, $result); + + $string = 'abcdefghijklmnopqrstuvwxyz'; + $find = 'k'; + $result = mb_strstr($string, $find); + $expected = 'klmnopqrstuvwxyz'; + $this->assertEquals($expected, $result); + + $string = 'abcdefghijklmnopqrstuvwxyz'; + $find = 'k'; + $result = mb_strstr($string, $find, true); + $expected = 'abcdefghij'; + $this->assertEquals($expected, $result); + + $string = 'abcdefghijklmnopqrstuvwxyz'; + $find = 'K'; + $result = mb_strstr($string, $find); + $expected = false; + $this->assertEquals($expected, $result); + + $string = '。「」、・ヲァィゥェォャュョッーアイウエオカキク'; + $find = 'ア'; + $result = mb_strstr($string, $find); + $expected = 'アイウエオカキク'; + $this->assertEquals($expected, $result); + + $string = '。「」、・ヲァィゥェォャュョッーアイウエオカキク'; + $find = 'ア'; + $result = mb_strstr($string, $find, true); + $expected = '。「」、・ヲァィゥェォャュョッー'; + $this->assertEquals($expected, $result); + + $string = 'ケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン゙'; + $find = 'ハ'; + $result = mb_strstr($string, $find); + $expected = 'ハヒフヘホマミムメモヤユヨラリルレロワン゙'; + $this->assertEquals($expected, $result); + + $string = 'ケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン゙'; + $find = 'ハ'; + $result = mb_strstr($string, $find, true); + $expected = 'ケコサシスセソタチツテトナニヌネノ'; + $this->assertEquals($expected, $result); + + $string = 'Ĥēĺļŏ, Ŵőřļď!'; + $find = 'ő'; + $result = mb_strstr($string, $find); + $expected = 'őřļď!'; + $this->assertEquals($expected, $result); + + $string = 'Ĥēĺļŏ, Ŵőřļď!'; + $find = 'ő'; + $result = mb_strstr($string, $find, true); + $expected = 'Ĥēĺļŏ, Ŵ'; + $this->assertEquals($expected, $result); + + $string = 'Ĥēĺļŏ, Ŵőřļď!'; + $find = 'ĺļ'; + $result = mb_strstr($string, $find, true); + $expected = 'Ĥē'; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'o'; + $result = mb_strstr($string, $find); + $expected = 'o, World!'; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'o'; + $result = mb_strstr($string, $find, true); + $expected = 'Hell'; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'Wo'; + $result = mb_strstr($string, $find); + $expected = 'World!'; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'Wo'; + $result = mb_strstr($string, $find, true); + $expected = 'Hello, '; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'll'; + $result = mb_strstr($string, $find); + $expected = 'llo, World!'; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'll'; + $result = mb_strstr($string, $find, true); + $expected = 'He'; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'rld'; + $result = mb_strstr($string, $find); + $expected = 'rld!'; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'rld'; + $result = mb_strstr($string, $find, true); + $expected = 'Hello, Wo'; + $this->assertEquals($expected, $result); + + $string = 'čini'; + $find = 'n'; + $result = mb_strstr($string, $find); + $expected = 'ni'; + $this->assertEquals($expected, $result); + + $string = 'čini'; + $find = 'n'; + $result = mb_strstr($string, $find, true); + $expected = 'či'; + $this->assertEquals($expected, $result); + + $string = 'moći'; + $find = 'ć'; + $result = mb_strstr($string, $find); + $expected = 'ći'; + $this->assertEquals($expected, $result); + + $string = 'moći'; + $find = 'ć'; + $result = mb_strstr($string, $find, true); + $expected = 'mo'; + $this->assertEquals($expected, $result); + + $string = 'državni'; + $find = 'ž'; + $result = mb_strstr($string, $find); + $expected = 'žavni'; + $this->assertEquals($expected, $result); + + $string = 'državni'; + $find = 'ž'; + $result = mb_strstr($string, $find, true); + $expected = 'dr'; + $this->assertEquals($expected, $result); + + $string = '把百度设为首页'; + $find = '设'; + $result = mb_strstr($string, $find); + $expected = '设为首页'; + $this->assertEquals($expected, $result); + + $string = '把百度设为首页'; + $find = '设'; + $result = mb_strstr($string, $find, true); + $expected = '把百度'; + $this->assertEquals($expected, $result); + + $string = '一二三周永龍'; + $find = '周'; + $result = mb_strstr($string, $find); + $expected = '周永龍'; + $this->assertEquals($expected, $result); + + $string = '一二三周永龍'; + $find = '周'; + $result = mb_strstr($string, $find, true); + $expected = '一二三'; + $this->assertEquals($expected, $result); + + $string = '一二三周永龍'; + $find = '二周'; + $result = mb_strstr($string, $find); + $expected = false; + $this->assertEquals($expected, $result); + } + +/** + * testMultibyteStrstr method + * + * @return void + */ + public function testMultibyteStrstr() { + $string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; + $find = 'F'; + $result = Multibyte::strstr($string, $find); + $expected = 'FGHIJKLMNOPQRSTUVWXYZ0123456789'; + $this->assertEquals($expected, $result); + + $string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; + $find = 'F'; + $result = Multibyte::strstr($string, $find, true); + $expected = 'ABCDE'; + $this->assertEquals($expected, $result); + + $string = 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ'; + $find = 'Å'; + $result = Multibyte::strstr($string, $find); + $expected = 'ÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ'; + $this->assertEquals($expected, $result); + + $string = 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ'; + $find = 'Å'; + $result = Multibyte::strstr($string, $find, true); + $expected = 'ÀÁÂÃÄ'; + $this->assertEquals($expected, $result); + + $string = 'ĀĂĄĆĈĊČĎĐĒĔĖĘĚĜĞĠĢĤĦĨĪĬĮIJĴĶĹĻĽĿŁŃŅŇŊŌŎŐŒŔŖŘŚŜŞŠŢŤŦŨŪŬŮŰŲŴŶŹŻŽ'; + $find = 'Ċ'; + $result = Multibyte::strstr($string, $find); + $expected = 'ĊČĎĐĒĔĖĘĚĜĞĠĢĤĦĨĪĬĮIJĴĶĹĻĽĿŁŃŅŇŊŌŎŐŒŔŖŘŚŜŞŠŢŤŦŨŪŬŮŰŲŴŶŹŻŽ'; + $this->assertEquals($expected, $result); + + $string = 'ĀĂĄĆĈĊČĎĐĒĔĖĘĚĜĞĠĢĤĦĨĪĬĮIJĴĶĹĻĽĿŁŃŅŇŊŌŎŐŒŔŖŘŚŜŞŠŢŤŦŨŪŬŮŰŲŴŶŹŻŽ'; + $find = 'Ċ'; + $result = Multibyte::strstr($string, $find, true); + $expected = 'ĀĂĄĆĈ'; + $this->assertEquals($expected, $result); + + $string = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'; + $find = 'F'; + $result = Multibyte::strstr($string, $find); + $expected = 'FGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'; + $this->assertEquals($expected, $result); + + $string = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'; + $find = 'F'; + $result = Multibyte::strstr($string, $find, true); + $expected = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDE'; + $this->assertEquals($expected, $result); + + $string = '¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈ'; + $find = 'µ'; + $result = Multibyte::strstr($string, $find); + $expected = 'µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈ'; + $this->assertEquals($expected, $result); + + $string = '¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈ'; + $find = 'µ'; + $result = Multibyte::strstr($string, $find, true); + $expected = '¡¢£¤¥¦§¨©ª«¬­®¯°±²³´'; + $this->assertEquals($expected, $result); + + $string = 'ÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬ'; + $find = 'Þ'; + $result = Multibyte::strstr($string, $find); + $expected = 'Þßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬ'; + $this->assertEquals($expected, $result); + + $string = 'ÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬ'; + $find = 'Þ'; + $result = Multibyte::strstr($string, $find, true); + $expected = 'ÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝ'; + $this->assertEquals($expected, $result); + + $string = 'ĭĮįİıIJijĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏƐ'; + $find = 'Ņ'; + $result = Multibyte::strstr($string, $find); + $expected = 'ŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏƐ'; + $this->assertEquals($expected, $result); + + $string = 'ĭĮįİıIJijĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏƐ'; + $find = 'Ņ'; + $result = Multibyte::strstr($string, $find, true); + $expected = 'ĭĮįİıIJijĴĵĶķĸĹĺĻļĽľĿŀŁłŃń'; + $this->assertEquals($expected, $result); + + $string = 'ƑƒƓƔƕƖƗƘƙƚƛƜƝƞƟƠơƢƣƤƥƦƧƨƩƪƫƬƭƮƯưƱƲƳƴƵƶƷƸƹƺƻƼƽƾƿǀǁǂǃDŽDždžLJLjljNJNjnjǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰDZDzdzǴ'; + $find = 'Ƹ'; + $result = Multibyte::strstr($string, $find); + $expected = 'ƸƹƺƻƼƽƾƿǀǁǂǃDŽDždžLJLjljNJNjnjǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰDZDzdzǴ'; + $this->assertEquals($expected, $result); + + $find = 'Ƹ'; + $result = Multibyte::strstr($string, $find, true); + $expected = 'ƑƒƓƔƕƖƗƘƙƚƛƜƝƞƟƠơƢƣƤƥƦƧƨƩƪƫƬƭƮƯưƱƲƳƴƵƶƷ'; + $this->assertEquals($expected, $result); + + $string = 'əɚɛɜɝɞɟɠɡɢɣɤɥɦɧɨɩɪɫɬɭɮɯɰɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿʀʁʂʃʄʅʆʇʈʉʊʋʌʍʎʏʐʑʒʓʔʕʖʗʘʙʚʛʜʝʞʟʠʡʢʣʤʥʦʧʨʩʪʫʬʭʮʯʰʱʲʳʴʵʶʷʸʹʺʻʼ'; + $find = 'ʀ'; + $result = Multibyte::strstr($string, $find); + $expected = 'ʀʁʂʃʄʅʆʇʈʉʊʋʌʍʎʏʐʑʒʓʔʕʖʗʘʙʚʛʜʝʞʟʠʡʢʣʤʥʦʧʨʩʪʫʬʭʮʯʰʱʲʳʴʵʶʷʸʹʺʻʼ'; + $this->assertEquals($expected, $result); + + $string = 'əɚɛɜɝɞɟɠɡɢɣɤɥɦɧɨɩɪɫɬɭɮɯɰɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿʀʁʂʃʄʅʆʇʈʉʊʋʌʍʎʏʐʑʒʓʔʕʖʗʘʙʚʛʜʝʞʟʠʡʢʣʤʥʦʧʨʩʪʫʬʭʮʯʰʱʲʳʴʵʶʷʸʹʺʻʼ'; + $find = 'ʀ'; + $result = Multibyte::strstr($string, $find, true); + $expected = 'əɚɛɜɝɞɟɠɡɢɣɤɥɦɧɨɩɪɫɬɭɮɯɰɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿ'; + $this->assertEquals($expected, $result); + + $string = 'ЀЁЂЃЄЅІЇЈЉЊЋЌЍЎЏАБВГДЕЖЗИЙКЛ'; + $find = 'Ї'; + $result = Multibyte::strstr($string, $find); + $expected = 'ЇЈЉЊЋЌЍЎЏАБВГДЕЖЗИЙКЛ'; + $this->assertEquals($expected, $result); + + $string = 'ЀЁЂЃЄЅІЇЈЉЊЋЌЍЎЏАБВГДЕЖЗИЙКЛ'; + $find = 'Ї'; + $result = Multibyte::strstr($string, $find, true); + $expected = 'ЀЁЂЃЄЅІ'; + $this->assertEquals($expected, $result); + + $string = 'МНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыь'; + $find = 'Р'; + $result = Multibyte::strstr($string, $find); + $expected = 'РСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыь'; + $this->assertEquals($expected, $result); + + $string = 'МНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыь'; + $find = 'Р'; + $result = Multibyte::strstr($string, $find, true); + $expected = 'МНОП'; + $this->assertEquals($expected, $result); + + $string = 'فقكلمنهوىيًٌٍَُ'; + $find = 'ن'; + $result = Multibyte::strstr($string, $find); + $expected = 'نهوىيًٌٍَُ'; + $this->assertEquals($expected, $result); + + $string = 'فقكلمنهوىيًٌٍَُ'; + $find = 'ن'; + $result = Multibyte::strstr($string, $find, true); + $expected = 'فقكلم'; + $this->assertEquals($expected, $result); + + $string = '✰✱✲✳✴✵✶✷✸✹✺✻✼✽✾✿❀❁❂❃❄❅❆❇❈❉❊❋❌❍❎❏❐❑❒❓❔❕❖❗❘❙❚❛❜❝❞'; + $find = '✿'; + $result = Multibyte::strstr($string, $find); + $expected = '✿❀❁❂❃❄❅❆❇❈❉❊❋❌❍❎❏❐❑❒❓❔❕❖❗❘❙❚❛❜❝❞'; + $this->assertEquals($expected, $result); + + $string = '✰✱✲✳✴✵✶✷✸✹✺✻✼✽✾✿❀❁❂❃❄❅❆❇❈❉❊❋❌❍❎❏❐❑❒❓❔❕❖❗❘❙❚❛❜❝❞'; + $find = '✿'; + $result = Multibyte::strstr($string, $find, true); + $expected = '✰✱✲✳✴✵✶✷✸✹✺✻✼✽✾'; + $this->assertEquals($expected, $result); + + $string = '⺀⺁⺂⺃⺄⺅⺆⺇⺈⺉⺊⺋⺌⺍⺎⺏⺐⺑⺒⺓⺔⺕⺖⺗⺘⺙⺛⺜⺝⺞⺟⺠⺡⺢⺣⺤⺥⺦⺧⺨⺩⺪⺫⺬⺭⺮⺯⺰⺱⺲⺳⺴⺵⺶⺷⺸⺹⺺⺻⺼⺽⺾⺿⻀⻁⻂⻃⻄⻅⻆⻇⻈⻉⻊⻋⻌⻍⻎⻏⻐⻑⻒⻓⻔⻕⻖⻗⻘⻙⻚⻛⻜⻝⻞⻟⻠'; + $find = '⺐'; + $result = Multibyte::strstr($string, $find); + $expected = '⺐⺑⺒⺓⺔⺕⺖⺗⺘⺙⺛⺜⺝⺞⺟⺠⺡⺢⺣⺤⺥⺦⺧⺨⺩⺪⺫⺬⺭⺮⺯⺰⺱⺲⺳⺴⺵⺶⺷⺸⺹⺺⺻⺼⺽⺾⺿⻀⻁⻂⻃⻄⻅⻆⻇⻈⻉⻊⻋⻌⻍⻎⻏⻐⻑⻒⻓⻔⻕⻖⻗⻘⻙⻚⻛⻜⻝⻞⻟⻠'; + $this->assertEquals($expected, $result); + + $string = '⺀⺁⺂⺃⺄⺅⺆⺇⺈⺉⺊⺋⺌⺍⺎⺏⺐⺑⺒⺓⺔⺕⺖⺗⺘⺙⺛⺜⺝⺞⺟⺠⺡⺢⺣⺤⺥⺦⺧⺨⺩⺪⺫⺬⺭⺮⺯⺰⺱⺲⺳⺴⺵⺶⺷⺸⺹⺺⺻⺼⺽⺾⺿⻀⻁⻂⻃⻄⻅⻆⻇⻈⻉⻊⻋⻌⻍⻎⻏⻐⻑⻒⻓⻔⻕⻖⻗⻘⻙⻚⻛⻜⻝⻞⻟⻠'; + $find = '⺐'; + $result = Multibyte::strstr($string, $find, true); + $expected = '⺀⺁⺂⺃⺄⺅⺆⺇⺈⺉⺊⺋⺌⺍⺎⺏'; + $this->assertEquals($expected, $result); + + $string = '⽅⽆⽇⽈⽉⽊⽋⽌⽍⽎⽏⽐⽑⽒⽓⽔⽕⽖⽗⽘⽙⽚⽛⽜⽝⽞⽟⽠⽡⽢⽣⽤⽥⽦⽧⽨⽩⽪⽫⽬⽭⽮⽯⽰⽱⽲⽳⽴⽵⽶⽷⽸⽹⽺⽻⽼⽽⽾⽿'; + $find = '⽤'; + $result = Multibyte::strstr($string, $find); + $expected = '⽤⽥⽦⽧⽨⽩⽪⽫⽬⽭⽮⽯⽰⽱⽲⽳⽴⽵⽶⽷⽸⽹⽺⽻⽼⽽⽾⽿'; + $this->assertEquals($expected, $result); + + $string = '⽅⽆⽇⽈⽉⽊⽋⽌⽍⽎⽏⽐⽑⽒⽓⽔⽕⽖⽗⽘⽙⽚⽛⽜⽝⽞⽟⽠⽡⽢⽣⽤⽥⽦⽧⽨⽩⽪⽫⽬⽭⽮⽯⽰⽱⽲⽳⽴⽵⽶⽷⽸⽹⽺⽻⽼⽽⽾⽿'; + $find = '⽤'; + $result = Multibyte::strstr($string, $find, true); + $expected = '⽅⽆⽇⽈⽉⽊⽋⽌⽍⽎⽏⽐⽑⽒⽓⽔⽕⽖⽗⽘⽙⽚⽛⽜⽝⽞⽟⽠⽡⽢⽣'; + $this->assertEquals($expected, $result); + + $string = '눡눢눣눤눥눦눧눨눩눪눫눬눭눮눯눰눱눲눳눴눵눶눷눸눹눺눻눼눽눾눿뉀뉁뉂뉃뉄뉅뉆뉇뉈뉉뉊뉋뉌뉍뉎뉏뉐뉑뉒뉓뉔뉕뉖뉗뉘뉙뉚뉛뉜뉝뉞뉟뉠뉡뉢뉣뉤뉥뉦뉧뉨뉩뉪뉫뉬뉭뉮뉯뉰뉱뉲뉳뉴뉵뉶뉷뉸뉹뉺뉻뉼뉽뉾뉿늀늁늂늃늄'; + $find = '눻'; + $result = Multibyte::strstr($string, $find); + $expected = '눻눼눽눾눿뉀뉁뉂뉃뉄뉅뉆뉇뉈뉉뉊뉋뉌뉍뉎뉏뉐뉑뉒뉓뉔뉕뉖뉗뉘뉙뉚뉛뉜뉝뉞뉟뉠뉡뉢뉣뉤뉥뉦뉧뉨뉩뉪뉫뉬뉭뉮뉯뉰뉱뉲뉳뉴뉵뉶뉷뉸뉹뉺뉻뉼뉽뉾뉿늀늁늂늃늄'; + $this->assertEquals($expected, $result); + + $string = '눡눢눣눤눥눦눧눨눩눪눫눬눭눮눯눰눱눲눳눴눵눶눷눸눹눺눻눼눽눾눿뉀뉁뉂뉃뉄뉅뉆뉇뉈뉉뉊뉋뉌뉍뉎뉏뉐뉑뉒뉓뉔뉕뉖뉗뉘뉙뉚뉛뉜뉝뉞뉟뉠뉡뉢뉣뉤뉥뉦뉧뉨뉩뉪뉫뉬뉭뉮뉯뉰뉱뉲뉳뉴뉵뉶뉷뉸뉹뉺뉻뉼뉽뉾뉿늀늁늂늃늄'; + $find = '눻'; + $result = Multibyte::strstr($string, $find, true); + $expected = '눡눢눣눤눥눦눧눨눩눪눫눬눭눮눯눰눱눲눳눴눵눶눷눸눹눺'; + $this->assertEquals($expected, $result); + + $string = 'ﹰﹱﹲﹳﹴ﹵ﹶﹷﹸﹹﹺﹻﹼﹽﹾﹿﺀﺁﺂﺃﺄﺅﺆﺇﺈﺉﺊﺋﺌﺍﺎﺏﺐﺑﺒﺓﺔﺕﺖﺗﺘﺙﺚﺛﺜﺝﺞﺟﺠﺡﺢﺣﺤﺥﺦﺧﺨﺩﺪﺫﺬﺭﺮﺯﺰ'; + $find = 'ﺞ'; + $result = Multibyte::strstr($string, $find); + $expected = 'ﺞﺟﺠﺡﺢﺣﺤﺥﺦﺧﺨﺩﺪﺫﺬﺭﺮﺯﺰ'; + $this->assertEquals($expected, $result); + + $string = 'ﹰﹱﹲﹳﹴ﹵ﹶﹷﹸﹹﹺﹻﹼﹽﹾﹿﺀﺁﺂﺃﺄﺅﺆﺇﺈﺉﺊﺋﺌﺍﺎﺏﺐﺑﺒﺓﺔﺕﺖﺗﺘﺙﺚﺛﺜﺝﺞﺟﺠﺡﺢﺣﺤﺥﺦﺧﺨﺩﺪﺫﺬﺭﺮﺯﺰ'; + $find = 'ﺞ'; + $result = Multibyte::strstr($string, $find, true); + $expected = 'ﹰﹱﹲﹳﹴ﹵ﹶﹷﹸﹹﹺﹻﹼﹽﹾﹿﺀﺁﺂﺃﺄﺅﺆﺇﺈﺉﺊﺋﺌﺍﺎﺏﺐﺑﺒﺓﺔﺕﺖﺗﺘﺙﺚﺛﺜﺝ'; + $this->assertEquals($expected, $result); + + $string = 'ﺱﺲﺳﺴﺵﺶﺷﺸﺹﺺﺻﺼﺽﺾﺿﻀﻁﻂﻃﻄﻅﻆﻇﻈﻉﻊﻋﻌﻍﻎﻏﻐﻑﻒﻓﻔﻕﻖﻗﻘﻙﻚﻛﻜﻝﻞﻟﻠﻡﻢﻣﻤﻥﻦﻧﻨﻩﻪﻫﻬﻭﻮﻯﻰﻱﻲﻳﻴﻵﻶﻷﻸﻹﻺﻻﻼ'; + $find = 'ﻞ'; + $result = Multibyte::strstr($string, $find); + $expected = 'ﻞﻟﻠﻡﻢﻣﻤﻥﻦﻧﻨﻩﻪﻫﻬﻭﻮﻯﻰﻱﻲﻳﻴﻵﻶﻷﻸﻹﻺﻻﻼ'; + $this->assertEquals($expected, $result); + + $string = 'ﺱﺲﺳﺴﺵﺶﺷﺸﺹﺺﺻﺼﺽﺾﺿﻀﻁﻂﻃﻄﻅﻆﻇﻈﻉﻊﻋﻌﻍﻎﻏﻐﻑﻒﻓﻔﻕﻖﻗﻘﻙﻚﻛﻜﻝﻞﻟﻠﻡﻢﻣﻤﻥﻦﻧﻨﻩﻪﻫﻬﻭﻮﻯﻰﻱﻲﻳﻴﻵﻶﻷﻸﻹﻺﻻﻼ'; + $find = 'ﻞ'; + $result = Multibyte::strstr($string, $find, true); + $expected = 'ﺱﺲﺳﺴﺵﺶﺷﺸﺹﺺﺻﺼﺽﺾﺿﻀﻁﻂﻃﻄﻅﻆﻇﻈﻉﻊﻋﻌﻍﻎﻏﻐﻑﻒﻓﻔﻕﻖﻗﻘﻙﻚﻛﻜﻝ'; + $this->assertEquals($expected, $result); + + $string = 'abcdefghijklmnopqrstuvwxyz'; + $find = 'k'; + $result = Multibyte::strstr($string, $find); + $expected = 'klmnopqrstuvwxyz'; + $this->assertEquals($expected, $result); + + $string = 'abcdefghijklmnopqrstuvwxyz'; + $find = 'k'; + $result = Multibyte::strstr($string, $find, true); + $expected = 'abcdefghij'; + $this->assertEquals($expected, $result); + + $string = 'abcdefghijklmnopqrstuvwxyz'; + $find = 'K'; + $result = Multibyte::strstr($string, $find); + $expected = false; + $this->assertEquals($expected, $result); + + $string = '。「」、・ヲァィゥェォャュョッーアイウエオカキク'; + $find = 'ア'; + $result = Multibyte::strstr($string, $find); + $expected = 'アイウエオカキク'; + $this->assertEquals($expected, $result); + + $string = '。「」、・ヲァィゥェォャュョッーアイウエオカキク'; + $find = 'ア'; + $result = Multibyte::strstr($string, $find, true); + $expected = '。「」、・ヲァィゥェォャュョッー'; + $this->assertEquals($expected, $result); + + $string = 'ケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン゙'; + $find = 'ハ'; + $result = Multibyte::strstr($string, $find); + $expected = 'ハヒフヘホマミムメモヤユヨラリルレロワン゙'; + $this->assertEquals($expected, $result); + + $string = 'ケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン゙'; + $find = 'ハ'; + $result = Multibyte::strstr($string, $find, true); + $expected = 'ケコサシスセソタチツテトナニヌネノ'; + $this->assertEquals($expected, $result); + + $string = 'Ĥēĺļŏ, Ŵőřļď!'; + $find = 'ő'; + $result = Multibyte::strstr($string, $find); + $expected = 'őřļď!'; + $this->assertEquals($expected, $result); + + $string = 'Ĥēĺļŏ, Ŵőřļď!'; + $find = 'ő'; + $result = Multibyte::strstr($string, $find, true); + $expected = 'Ĥēĺļŏ, Ŵ'; + $this->assertEquals($expected, $result); + + $string = 'Ĥēĺļŏ, Ŵőřļď!'; + $find = 'ĺļ'; + $result = Multibyte::strstr($string, $find, true); + $expected = 'Ĥē'; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'o'; + $result = Multibyte::strstr($string, $find); + $expected = 'o, World!'; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'o'; + $result = Multibyte::strstr($string, $find, true); + $expected = 'Hell'; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'Wo'; + $result = Multibyte::strstr($string, $find); + $expected = 'World!'; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'Wo'; + $result = Multibyte::strstr($string, $find, true); + $expected = 'Hello, '; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'll'; + $result = Multibyte::strstr($string, $find); + $expected = 'llo, World!'; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'll'; + $result = Multibyte::strstr($string, $find, true); + $expected = 'He'; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'rld'; + $result = Multibyte::strstr($string, $find); + $expected = 'rld!'; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'rld'; + $result = Multibyte::strstr($string, $find, true); + $expected = 'Hello, Wo'; + $this->assertEquals($expected, $result); + + $string = 'čini'; + $find = 'n'; + $result = Multibyte::strstr($string, $find); + $expected = 'ni'; + $this->assertEquals($expected, $result); + + $string = 'čini'; + $find = 'n'; + $result = Multibyte::strstr($string, $find, true); + $expected = 'či'; + $this->assertEquals($expected, $result); + + $string = 'moći'; + $find = 'ć'; + $result = Multibyte::strstr($string, $find); + $expected = 'ći'; + $this->assertEquals($expected, $result); + + $string = 'moći'; + $find = 'ć'; + $result = Multibyte::strstr($string, $find, true); + $expected = 'mo'; + $this->assertEquals($expected, $result); + + $string = 'državni'; + $find = 'ž'; + $result = Multibyte::strstr($string, $find); + $expected = 'žavni'; + $this->assertEquals($expected, $result); + + $string = 'državni'; + $find = 'ž'; + $result = Multibyte::strstr($string, $find, true); + $expected = 'dr'; + $this->assertEquals($expected, $result); + + $string = '把百度设为首页'; + $find = '设'; + $result = Multibyte::strstr($string, $find); + $expected = '设为首页'; + $this->assertEquals($expected, $result); + + $string = '把百度设为首页'; + $find = '设'; + $result = Multibyte::strstr($string, $find, true); + $expected = '把百度'; + $this->assertEquals($expected, $result); + + $string = '一二三周永龍'; + $find = '周'; + $result = Multibyte::strstr($string, $find); + $expected = '周永龍'; + $this->assertEquals($expected, $result); + + $string = '一二三周永龍'; + $find = '周'; + $result = Multibyte::strstr($string, $find, true); + $expected = '一二三'; + $this->assertEquals($expected, $result); + + $string = '一二三周永龍'; + $find = '二周'; + $result = Multibyte::strstr($string, $find); + $expected = false; + $this->assertEquals($expected, $result); + } + +/** + * testUsingMbStrtolower method + * + * @return void + */ + public function testUsingMbStrtolower() { + $string = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`ABCDEFGHIJKLMNOPQRSTUVWXYZ{|}~'; + $result = mb_strtolower($string); + $expected = '!"#$%&\'()*+,-./0123456789:;<=>?@abcdefghijklmnopqrstuvwxyz[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'; + $this->assertEquals($expected, $result); + + $string = '!"#$%&\'()*+,-./0123456789:;<=>?@'; + $result = mb_strtolower($string); + $expected = '!"#$%&\'()*+,-./0123456789:;<=>?@'; + $this->assertEquals($expected, $result); + + $string = 'À'; + $result = mb_strtolower($string); + $expected = 'à'; + $this->assertEquals($expected, $result); + + $string = 'Á'; + $result = mb_strtolower($string); + $expected = 'á'; + $this->assertEquals($expected, $result); + + $string = 'Â'; + $result = mb_strtolower($string); + $expected = 'â'; + $this->assertEquals($expected, $result); + + $string = 'Ã'; + $result = mb_strtolower($string); + $expected = 'ã'; + $this->assertEquals($expected, $result); + + $string = 'Ä'; + $result = mb_strtolower($string); + $expected = 'ä'; + $this->assertEquals($expected, $result); + + $string = 'Å'; + $result = mb_strtolower($string); + $expected = 'å'; + $this->assertEquals($expected, $result); + + $string = 'Æ'; + $result = mb_strtolower($string); + $expected = 'æ'; + $this->assertEquals($expected, $result); + + $string = 'Ç'; + $result = mb_strtolower($string); + $expected = 'ç'; + $this->assertEquals($expected, $result); + + $string = 'È'; + $result = mb_strtolower($string); + $expected = 'è'; + $this->assertEquals($expected, $result); + + $string = 'É'; + $result = mb_strtolower($string); + $expected = 'é'; + $this->assertEquals($expected, $result); + + $string = 'Ê'; + $result = mb_strtolower($string); + $expected = 'ê'; + $this->assertEquals($expected, $result); + + $string = 'Ë'; + $result = mb_strtolower($string); + $expected = 'ë'; + $this->assertEquals($expected, $result); + + $string = 'Ì'; + $result = mb_strtolower($string); + $expected = 'ì'; + $this->assertEquals($expected, $result); + + $string = 'Í'; + $result = mb_strtolower($string); + $expected = 'í'; + $this->assertEquals($expected, $result); + + $string = 'Î'; + $result = mb_strtolower($string); + $expected = 'î'; + $this->assertEquals($expected, $result); + + $string = 'Ï'; + $result = mb_strtolower($string); + $expected = 'ï'; + $this->assertEquals($expected, $result); + + $string = 'Ð'; + $result = mb_strtolower($string); + $expected = 'ð'; + $this->assertEquals($expected, $result); + + $string = 'Ñ'; + $result = mb_strtolower($string); + $expected = 'ñ'; + $this->assertEquals($expected, $result); + + $string = 'Ò'; + $result = mb_strtolower($string); + $expected = 'ò'; + $this->assertEquals($expected, $result); + + $string = 'Ó'; + $result = mb_strtolower($string); + $expected = 'ó'; + $this->assertEquals($expected, $result); + + $string = 'Ô'; + $result = mb_strtolower($string); + $expected = 'ô'; + $this->assertEquals($expected, $result); + + $string = 'Õ'; + $result = mb_strtolower($string); + $expected = 'õ'; + $this->assertEquals($expected, $result); + + $string = 'Ö'; + $result = mb_strtolower($string); + $expected = 'ö'; + $this->assertEquals($expected, $result); + + $string = 'Ø'; + $result = mb_strtolower($string); + $expected = 'ø'; + $this->assertEquals($expected, $result); + + $string = 'Ù'; + $result = mb_strtolower($string); + $expected = 'ù'; + $this->assertEquals($expected, $result); + + $string = 'Ú'; + $result = mb_strtolower($string); + $expected = 'ú'; + $this->assertEquals($expected, $result); + + $string = 'Û'; + $result = mb_strtolower($string); + $expected = 'û'; + $this->assertEquals($expected, $result); + + $string = 'Ü'; + $result = mb_strtolower($string); + $expected = 'ü'; + $this->assertEquals($expected, $result); + + $string = 'Ý'; + $result = mb_strtolower($string); + $expected = 'ý'; + $this->assertEquals($expected, $result); + + $string = 'Þ'; + $result = mb_strtolower($string); + $expected = 'þ'; + $this->assertEquals($expected, $result); + + $string = 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ'; + $result = mb_strtolower($string); + $expected = 'àáâãäåæçèéêëìíîïðñòóôõöøùúûüýþ'; + $this->assertEquals($expected, $result); + + $string = 'Ā'; + $result = mb_strtolower($string); + $expected = 'ā'; + $this->assertEquals($expected, $result); + + $string = 'Ă'; + $result = mb_strtolower($string); + $expected = 'ă'; + $this->assertEquals($expected, $result); + + $string = 'Ą'; + $result = mb_strtolower($string); + $expected = 'ą'; + $this->assertEquals($expected, $result); + + $string = 'Ć'; + $result = mb_strtolower($string); + $expected = 'ć'; + $this->assertEquals($expected, $result); + + $string = 'Ĉ'; + $result = mb_strtolower($string); + $expected = 'ĉ'; + $this->assertEquals($expected, $result); + + $string = 'Ċ'; + $result = mb_strtolower($string); + $expected = 'ċ'; + $this->assertEquals($expected, $result); + + $string = 'Č'; + $result = mb_strtolower($string); + $expected = 'č'; + $this->assertEquals($expected, $result); + + $string = 'Ď'; + $result = mb_strtolower($string); + $expected = 'ď'; + $this->assertEquals($expected, $result); + + $string = 'Đ'; + $result = mb_strtolower($string); + $expected = 'đ'; + $this->assertEquals($expected, $result); + + $string = 'Ē'; + $result = mb_strtolower($string); + $expected = 'ē'; + $this->assertEquals($expected, $result); + + $string = 'Ĕ'; + $result = mb_strtolower($string); + $expected = 'ĕ'; + $this->assertEquals($expected, $result); + + $string = 'Ė'; + $result = mb_strtolower($string); + $expected = 'ė'; + $this->assertEquals($expected, $result); + + $string = 'Ę'; + $result = mb_strtolower($string); + $expected = 'ę'; + $this->assertEquals($expected, $result); + + $string = 'Ě'; + $result = mb_strtolower($string); + $expected = 'ě'; + $this->assertEquals($expected, $result); + + $string = 'Ĝ'; + $result = mb_strtolower($string); + $expected = 'ĝ'; + $this->assertEquals($expected, $result); + + $string = 'Ğ'; + $result = mb_strtolower($string); + $expected = 'ğ'; + $this->assertEquals($expected, $result); + + $string = 'Ġ'; + $result = mb_strtolower($string); + $expected = 'ġ'; + $this->assertEquals($expected, $result); + + $string = 'Ģ'; + $result = mb_strtolower($string); + $expected = 'ģ'; + $this->assertEquals($expected, $result); + + $string = 'Ĥ'; + $result = mb_strtolower($string); + $expected = 'ĥ'; + $this->assertEquals($expected, $result); + + $string = 'Ħ'; + $result = mb_strtolower($string); + $expected = 'ħ'; + $this->assertEquals($expected, $result); + + $string = 'Ĩ'; + $result = mb_strtolower($string); + $expected = 'ĩ'; + $this->assertEquals($expected, $result); + + $string = 'Ī'; + $result = mb_strtolower($string); + $expected = 'ī'; + $this->assertEquals($expected, $result); + + $string = 'Ĭ'; + $result = mb_strtolower($string); + $expected = 'ĭ'; + $this->assertEquals($expected, $result); + + $string = 'Į'; + $result = mb_strtolower($string); + $expected = 'į'; + $this->assertEquals($expected, $result); + + $string = 'IJ'; + $result = mb_strtolower($string); + $expected = 'ij'; + $this->assertEquals($expected, $result); + + $string = 'Ĵ'; + $result = mb_strtolower($string); + $expected = 'ĵ'; + $this->assertEquals($expected, $result); + + $string = 'Ķ'; + $result = mb_strtolower($string); + $expected = 'ķ'; + $this->assertEquals($expected, $result); + + $string = 'Ĺ'; + $result = mb_strtolower($string); + $expected = 'ĺ'; + $this->assertEquals($expected, $result); + + $string = 'Ļ'; + $result = mb_strtolower($string); + $expected = 'ļ'; + $this->assertEquals($expected, $result); + + $string = 'Ľ'; + $result = mb_strtolower($string); + $expected = 'ľ'; + $this->assertEquals($expected, $result); + + $string = 'Ŀ'; + $result = mb_strtolower($string); + $expected = 'ŀ'; + $this->assertEquals($expected, $result); + + $string = 'Ł'; + $result = mb_strtolower($string); + $expected = 'ł'; + $this->assertEquals($expected, $result); + + $string = 'Ń'; + $result = mb_strtolower($string); + $expected = 'ń'; + $this->assertEquals($expected, $result); + + $string = 'Ņ'; + $result = mb_strtolower($string); + $expected = 'ņ'; + $this->assertEquals($expected, $result); + + $string = 'Ň'; + $result = mb_strtolower($string); + $expected = 'ň'; + $this->assertEquals($expected, $result); + + $string = 'Ŋ'; + $result = mb_strtolower($string); + $expected = 'ŋ'; + $this->assertEquals($expected, $result); + + $string = 'Ō'; + $result = mb_strtolower($string); + $expected = 'ō'; + $this->assertEquals($expected, $result); + + $string = 'Ŏ'; + $result = mb_strtolower($string); + $expected = 'ŏ'; + $this->assertEquals($expected, $result); + + $string = 'Ő'; + $result = mb_strtolower($string); + $expected = 'ő'; + $this->assertEquals($expected, $result); + + $string = 'Œ'; + $result = mb_strtolower($string); + $expected = 'œ'; + $this->assertEquals($expected, $result); + + $string = 'Ŕ'; + $result = mb_strtolower($string); + $expected = 'ŕ'; + $this->assertEquals($expected, $result); + + $string = 'Ŗ'; + $result = mb_strtolower($string); + $expected = 'ŗ'; + $this->assertEquals($expected, $result); + + $string = 'Ř'; + $result = mb_strtolower($string); + $expected = 'ř'; + $this->assertEquals($expected, $result); + + $string = 'Ś'; + $result = mb_strtolower($string); + $expected = 'ś'; + $this->assertEquals($expected, $result); + + $string = 'Ŝ'; + $result = mb_strtolower($string); + $expected = 'ŝ'; + $this->assertEquals($expected, $result); + + $string = 'Ş'; + $result = mb_strtolower($string); + $expected = 'ş'; + $this->assertEquals($expected, $result); + + $string = 'Š'; + $result = mb_strtolower($string); + $expected = 'š'; + $this->assertEquals($expected, $result); + + $string = 'Ţ'; + $result = mb_strtolower($string); + $expected = 'ţ'; + $this->assertEquals($expected, $result); + + $string = 'Ť'; + $result = mb_strtolower($string); + $expected = 'ť'; + $this->assertEquals($expected, $result); + + $string = 'Ŧ'; + $result = mb_strtolower($string); + $expected = 'ŧ'; + $this->assertEquals($expected, $result); + + $string = 'Ũ'; + $result = mb_strtolower($string); + $expected = 'ũ'; + $this->assertEquals($expected, $result); + + $string = 'Ū'; + $result = mb_strtolower($string); + $expected = 'ū'; + $this->assertEquals($expected, $result); + + $string = 'Ŭ'; + $result = mb_strtolower($string); + $expected = 'ŭ'; + $this->assertEquals($expected, $result); + + $string = 'Ů'; + $result = mb_strtolower($string); + $expected = 'ů'; + $this->assertEquals($expected, $result); + + $string = 'Ű'; + $result = mb_strtolower($string); + $expected = 'ű'; + $this->assertEquals($expected, $result); + + $string = 'Ų'; + $result = mb_strtolower($string); + $expected = 'ų'; + $this->assertEquals($expected, $result); + + $string = 'Ŵ'; + $result = mb_strtolower($string); + $expected = 'ŵ'; + $this->assertEquals($expected, $result); + + $string = 'Ŷ'; + $result = mb_strtolower($string); + $expected = 'ŷ'; + $this->assertEquals($expected, $result); + + $string = 'Ź'; + $result = mb_strtolower($string); + $expected = 'ź'; + $this->assertEquals($expected, $result); + + $string = 'Ż'; + $result = mb_strtolower($string); + $expected = 'ż'; + $this->assertEquals($expected, $result); + + $string = 'Ž'; + $result = mb_strtolower($string); + $expected = 'ž'; + $this->assertEquals($expected, $result); + + $string = 'ĀĂĄĆĈĊČĎĐĒĔĖĘĚĜĞĠĢĤĦĨĪĬĮIJĴĶĹĻĽĿŁŃŅŇŊŌŎŐŒŔŖŘŚŜŞŠŢŤŦŨŪŬŮŰŲŴŶŹŻŽ'; + $result = mb_strtolower($string); + $expected = 'āăąćĉċčďđēĕėęěĝğġģĥħĩīĭįijĵķĺļľŀłńņňŋōŏőœŕŗřśŝşšţťŧũūŭůűųŵŷźżž'; + $this->assertEquals($expected, $result); + + $string = 'ĤĒĹĻŎ, ŴŐŘĻĎ!'; + $result = mb_strtolower($string); + $expected = 'ĥēĺļŏ, ŵőřļď!'; + $this->assertEquals($expected, $result); + + $string = 'ĥēĺļŏ, ŵőřļď!'; + $result = mb_strtolower($string); + $expected = 'ĥēĺļŏ, ŵőřļď!'; + $this->assertEquals($expected, $result); + + $string = 'ἈΙ'; + $result = mb_strtolower($string); + $expected = 'ἀι'; + $this->assertEquals($expected, $result); + + $string = 'fffiflffifflſtstﬓﬔﬕﬖﬗ'; + $result = mb_strtolower($string); + $expected = 'fffiflffifflſtstﬓﬔﬕﬖﬗ'; + $this->assertEquals($expected, $result); + } + +/** + * testMultibyteStrtolower method + * + * @return void + */ + public function testMultibyteStrtolower() { + $string = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`ABCDEFGHIJKLMNOPQRSTUVWXYZ{|}~'; + $result = Multibyte::strtolower($string); + $expected = '!"#$%&\'()*+,-./0123456789:;<=>?@abcdefghijklmnopqrstuvwxyz[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'; + $this->assertEquals($expected, $result); + + $string = '!"#$%&\'()*+,-./0123456789:;<=>?@'; + $result = Multibyte::strtolower($string); + $expected = '!"#$%&\'()*+,-./0123456789:;<=>?@'; + $this->assertEquals($expected, $result); + + $string = 'À'; + $result = Multibyte::strtolower($string); + $expected = 'à'; + $this->assertEquals($expected, $result); + + $string = 'Á'; + $result = Multibyte::strtolower($string); + $expected = 'á'; + $this->assertEquals($expected, $result); + + $string = 'Â'; + $result = Multibyte::strtolower($string); + $expected = 'â'; + $this->assertEquals($expected, $result); + + $string = 'Ã'; + $result = Multibyte::strtolower($string); + $expected = 'ã'; + $this->assertEquals($expected, $result); + + $string = 'Ä'; + $result = Multibyte::strtolower($string); + $expected = 'ä'; + $this->assertEquals($expected, $result); + + $string = 'Å'; + $result = Multibyte::strtolower($string); + $expected = 'å'; + $this->assertEquals($expected, $result); + + $string = 'Æ'; + $result = Multibyte::strtolower($string); + $expected = 'æ'; + $this->assertEquals($expected, $result); + + $string = 'Ç'; + $result = Multibyte::strtolower($string); + $expected = 'ç'; + $this->assertEquals($expected, $result); + + $string = 'È'; + $result = Multibyte::strtolower($string); + $expected = 'è'; + $this->assertEquals($expected, $result); + + $string = 'É'; + $result = Multibyte::strtolower($string); + $expected = 'é'; + $this->assertEquals($expected, $result); + + $string = 'Ê'; + $result = Multibyte::strtolower($string); + $expected = 'ê'; + $this->assertEquals($expected, $result); + + $string = 'Ë'; + $result = Multibyte::strtolower($string); + $expected = 'ë'; + $this->assertEquals($expected, $result); + + $string = 'Ì'; + $result = Multibyte::strtolower($string); + $expected = 'ì'; + $this->assertEquals($expected, $result); + + $string = 'Í'; + $result = Multibyte::strtolower($string); + $expected = 'í'; + $this->assertEquals($expected, $result); + + $string = 'Î'; + $result = Multibyte::strtolower($string); + $expected = 'î'; + $this->assertEquals($expected, $result); + + $string = 'Ï'; + $result = Multibyte::strtolower($string); + $expected = 'ï'; + $this->assertEquals($expected, $result); + + $string = 'Ð'; + $result = Multibyte::strtolower($string); + $expected = 'ð'; + $this->assertEquals($expected, $result); + + $string = 'Ñ'; + $result = Multibyte::strtolower($string); + $expected = 'ñ'; + $this->assertEquals($expected, $result); + + $string = 'Ò'; + $result = Multibyte::strtolower($string); + $expected = 'ò'; + $this->assertEquals($expected, $result); + + $string = 'Ó'; + $result = Multibyte::strtolower($string); + $expected = 'ó'; + $this->assertEquals($expected, $result); + + $string = 'Ô'; + $result = Multibyte::strtolower($string); + $expected = 'ô'; + $this->assertEquals($expected, $result); + + $string = 'Õ'; + $result = Multibyte::strtolower($string); + $expected = 'õ'; + $this->assertEquals($expected, $result); + + $string = 'Ö'; + $result = Multibyte::strtolower($string); + $expected = 'ö'; + $this->assertEquals($expected, $result); + + $string = 'Ø'; + $result = Multibyte::strtolower($string); + $expected = 'ø'; + $this->assertEquals($expected, $result); + + $string = 'Ù'; + $result = Multibyte::strtolower($string); + $expected = 'ù'; + $this->assertEquals($expected, $result); + + $string = 'Ú'; + $result = Multibyte::strtolower($string); + $expected = 'ú'; + $this->assertEquals($expected, $result); + + $string = 'Û'; + $result = Multibyte::strtolower($string); + $expected = 'û'; + $this->assertEquals($expected, $result); + + $string = 'Ü'; + $result = Multibyte::strtolower($string); + $expected = 'ü'; + $this->assertEquals($expected, $result); + + $string = 'Ý'; + $result = Multibyte::strtolower($string); + $expected = 'ý'; + $this->assertEquals($expected, $result); + + $string = 'Þ'; + $result = Multibyte::strtolower($string); + $expected = 'þ'; + $this->assertEquals($expected, $result); + + $string = 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ'; + $result = Multibyte::strtolower($string); + $expected = 'àáâãäåæçèéêëìíîïðñòóôõöøùúûüýþ'; + $this->assertEquals($expected, $result); + + $string = 'Ā'; + $result = Multibyte::strtolower($string); + $expected = 'ā'; + $this->assertEquals($expected, $result); + + $string = 'Ă'; + $result = Multibyte::strtolower($string); + $expected = 'ă'; + $this->assertEquals($expected, $result); + + $string = 'Ą'; + $result = Multibyte::strtolower($string); + $expected = 'ą'; + $this->assertEquals($expected, $result); + + $string = 'Ć'; + $result = Multibyte::strtolower($string); + $expected = 'ć'; + $this->assertEquals($expected, $result); + + $string = 'Ĉ'; + $result = Multibyte::strtolower($string); + $expected = 'ĉ'; + $this->assertEquals($expected, $result); + + $string = 'Ċ'; + $result = Multibyte::strtolower($string); + $expected = 'ċ'; + $this->assertEquals($expected, $result); + + $string = 'Č'; + $result = Multibyte::strtolower($string); + $expected = 'č'; + $this->assertEquals($expected, $result); + + $string = 'Ď'; + $result = Multibyte::strtolower($string); + $expected = 'ď'; + $this->assertEquals($expected, $result); + + $string = 'Đ'; + $result = Multibyte::strtolower($string); + $expected = 'đ'; + $this->assertEquals($expected, $result); + + $string = 'Ē'; + $result = Multibyte::strtolower($string); + $expected = 'ē'; + $this->assertEquals($expected, $result); + + $string = 'Ĕ'; + $result = Multibyte::strtolower($string); + $expected = 'ĕ'; + $this->assertEquals($expected, $result); + + $string = 'Ė'; + $result = Multibyte::strtolower($string); + $expected = 'ė'; + $this->assertEquals($expected, $result); + + $string = 'Ę'; + $result = Multibyte::strtolower($string); + $expected = 'ę'; + $this->assertEquals($expected, $result); + + $string = 'Ě'; + $result = Multibyte::strtolower($string); + $expected = 'ě'; + $this->assertEquals($expected, $result); + + $string = 'Ĝ'; + $result = Multibyte::strtolower($string); + $expected = 'ĝ'; + $this->assertEquals($expected, $result); + + $string = 'Ğ'; + $result = Multibyte::strtolower($string); + $expected = 'ğ'; + $this->assertEquals($expected, $result); + + $string = 'Ġ'; + $result = Multibyte::strtolower($string); + $expected = 'ġ'; + $this->assertEquals($expected, $result); + + $string = 'Ģ'; + $result = Multibyte::strtolower($string); + $expected = 'ģ'; + $this->assertEquals($expected, $result); + + $string = 'Ĥ'; + $result = Multibyte::strtolower($string); + $expected = 'ĥ'; + $this->assertEquals($expected, $result); + + $string = 'Ħ'; + $result = Multibyte::strtolower($string); + $expected = 'ħ'; + $this->assertEquals($expected, $result); + + $string = 'Ĩ'; + $result = Multibyte::strtolower($string); + $expected = 'ĩ'; + $this->assertEquals($expected, $result); + + $string = 'Ī'; + $result = Multibyte::strtolower($string); + $expected = 'ī'; + $this->assertEquals($expected, $result); + + $string = 'Ĭ'; + $result = Multibyte::strtolower($string); + $expected = 'ĭ'; + $this->assertEquals($expected, $result); + + $string = 'Į'; + $result = Multibyte::strtolower($string); + $expected = 'į'; + $this->assertEquals($expected, $result); + + $string = 'IJ'; + $result = Multibyte::strtolower($string); + $expected = 'ij'; + $this->assertEquals($expected, $result); + + $string = 'Ĵ'; + $result = Multibyte::strtolower($string); + $expected = 'ĵ'; + $this->assertEquals($expected, $result); + + $string = 'Ķ'; + $result = Multibyte::strtolower($string); + $expected = 'ķ'; + $this->assertEquals($expected, $result); + + $string = 'Ĺ'; + $result = Multibyte::strtolower($string); + $expected = 'ĺ'; + $this->assertEquals($expected, $result); + + $string = 'Ļ'; + $result = Multibyte::strtolower($string); + $expected = 'ļ'; + $this->assertEquals($expected, $result); + + $string = 'Ľ'; + $result = Multibyte::strtolower($string); + $expected = 'ľ'; + $this->assertEquals($expected, $result); + + $string = 'Ŀ'; + $result = Multibyte::strtolower($string); + $expected = 'ŀ'; + $this->assertEquals($expected, $result); + + $string = 'Ł'; + $result = Multibyte::strtolower($string); + $expected = 'ł'; + $this->assertEquals($expected, $result); + + $string = 'Ń'; + $result = Multibyte::strtolower($string); + $expected = 'ń'; + $this->assertEquals($expected, $result); + + $string = 'Ņ'; + $result = Multibyte::strtolower($string); + $expected = 'ņ'; + $this->assertEquals($expected, $result); + + $string = 'Ň'; + $result = Multibyte::strtolower($string); + $expected = 'ň'; + $this->assertEquals($expected, $result); + + $string = 'Ŋ'; + $result = Multibyte::strtolower($string); + $expected = 'ŋ'; + $this->assertEquals($expected, $result); + + $string = 'Ō'; + $result = Multibyte::strtolower($string); + $expected = 'ō'; + $this->assertEquals($expected, $result); + + $string = 'Ŏ'; + $result = Multibyte::strtolower($string); + $expected = 'ŏ'; + $this->assertEquals($expected, $result); + + $string = 'Ő'; + $result = Multibyte::strtolower($string); + $expected = 'ő'; + $this->assertEquals($expected, $result); + + $string = 'Œ'; + $result = Multibyte::strtolower($string); + $expected = 'œ'; + $this->assertEquals($expected, $result); + + $string = 'Ŕ'; + $result = Multibyte::strtolower($string); + $expected = 'ŕ'; + $this->assertEquals($expected, $result); + + $string = 'Ŗ'; + $result = Multibyte::strtolower($string); + $expected = 'ŗ'; + $this->assertEquals($expected, $result); + + $string = 'Ř'; + $result = Multibyte::strtolower($string); + $expected = 'ř'; + $this->assertEquals($expected, $result); + + $string = 'Ś'; + $result = Multibyte::strtolower($string); + $expected = 'ś'; + $this->assertEquals($expected, $result); + + $string = 'Ŝ'; + $result = Multibyte::strtolower($string); + $expected = 'ŝ'; + $this->assertEquals($expected, $result); + + $string = 'Ş'; + $result = Multibyte::strtolower($string); + $expected = 'ş'; + $this->assertEquals($expected, $result); + + $string = 'Š'; + $result = Multibyte::strtolower($string); + $expected = 'š'; + $this->assertEquals($expected, $result); + + $string = 'Ţ'; + $result = Multibyte::strtolower($string); + $expected = 'ţ'; + $this->assertEquals($expected, $result); + + $string = 'Ť'; + $result = Multibyte::strtolower($string); + $expected = 'ť'; + $this->assertEquals($expected, $result); + + $string = 'Ŧ'; + $result = Multibyte::strtolower($string); + $expected = 'ŧ'; + $this->assertEquals($expected, $result); + + $string = 'Ũ'; + $result = Multibyte::strtolower($string); + $expected = 'ũ'; + $this->assertEquals($expected, $result); + + $string = 'Ū'; + $result = Multibyte::strtolower($string); + $expected = 'ū'; + $this->assertEquals($expected, $result); + + $string = 'Ŭ'; + $result = Multibyte::strtolower($string); + $expected = 'ŭ'; + $this->assertEquals($expected, $result); + + $string = 'Ů'; + $result = Multibyte::strtolower($string); + $expected = 'ů'; + $this->assertEquals($expected, $result); + + $string = 'Ű'; + $result = Multibyte::strtolower($string); + $expected = 'ű'; + $this->assertEquals($expected, $result); + + $string = 'Ų'; + $result = Multibyte::strtolower($string); + $expected = 'ų'; + $this->assertEquals($expected, $result); + + $string = 'Ŵ'; + $result = Multibyte::strtolower($string); + $expected = 'ŵ'; + $this->assertEquals($expected, $result); + + $string = 'Ŷ'; + $result = Multibyte::strtolower($string); + $expected = 'ŷ'; + $this->assertEquals($expected, $result); + + $string = 'Ź'; + $result = Multibyte::strtolower($string); + $expected = 'ź'; + $this->assertEquals($expected, $result); + + $string = 'Ż'; + $result = Multibyte::strtolower($string); + $expected = 'ż'; + $this->assertEquals($expected, $result); + + $string = 'Ž'; + $result = Multibyte::strtolower($string); + $expected = 'ž'; + $this->assertEquals($expected, $result); + + $string = 'ĀĂĄĆĈĊČĎĐĒĔĖĘĚĜĞĠĢĤĦĨĪĬĮIJĴĶĹĻĽĿŁŃŅŇŊŌŎŐŒŔŖŘŚŜŞŠŢŤŦŨŪŬŮŰŲŴŶŹŻŽ'; + $result = Multibyte::strtolower($string); + $expected = 'āăąćĉċčďđēĕėęěĝğġģĥħĩīĭįijĵķĺļľŀłńņňŋōŏőœŕŗřśŝşšţťŧũūŭůűųŵŷźżž'; + $this->assertEquals($expected, $result); + + $string = 'ĤĒĹĻŎ, ŴŐŘĻĎ!'; + $result = Multibyte::strtolower($string); + $expected = 'ĥēĺļŏ, ŵőřļď!'; + $this->assertEquals($expected, $result); + + $string = 'ĥēĺļŏ, ŵőřļď!'; + $result = Multibyte::strtolower($string); + $expected = 'ĥēĺļŏ, ŵőřļď!'; + $this->assertEquals($expected, $result); + + $string = 'ἈΙ'; + $result = Multibyte::strtolower($string); + $expected = 'ἀι'; + $this->assertEquals($expected, $result); + + $string = 'ԀԂԄԆԈԊԌԎԐԒ'; + $result = Multibyte::strtolower($string); + $expected = 'ԁԃԅԇԉԋԍԏԑԓ'; + $this->assertEquals($expected, $result); + + $string = 'ԱԲԳԴԵԶԷԸԹԺԻԼԽԾԿՀՁՂՃՄՅՆՇՈՉՊՋՌՍՎՏՐՑՒՓՔՕՖև'; + $result = Multibyte::strtolower($string); + $expected = 'աբգդեզէըթժիլխծկհձղճմյնշոչպջռսվտրցւփքօֆև'; + $this->assertEquals($expected, $result); + + $string = 'ႠႡႢႣႤႥႦႧႨႩႪႫႬႭႮႯႰႱႲႳႴႵႶႷႸႹႺႻႼႽႾႿჀჁჂჃჄჅ'; + $result = Multibyte::strtolower($string); + $expected = 'ႠႡႢႣႤႥႦႧႨႩႪႫႬႭႮႯႰႱႲႳႴႵႶႷႸႹႺႻႼႽႾႿჀჁჂჃჄჅ'; + $this->assertEquals($expected, $result); + + $string = 'ḀḂḄḆḈḊḌḎḐḒḔḖḘḚḜḞḠḢḤḦḨḪḬḮḰḲḴḶḸḺḼḾṀṂṄṆṈṊṌṎṐṒṔṖṘṚṜṞṠṢṤṦṨṪṬṮṰṲṴṶṸṺṼṾẀẂẄẆẈẊẌẎẐẒẔẖẗẘẙẚẠẢẤẦẨẪẬẮẰẲẴẶẸẺẼẾỀỂỄỆỈỊỌỎỐỒỔỖỘỚỜỞỠỢỤỦỨỪỬỮỰỲỴỶỸ'; + $result = Multibyte::strtolower($string); + $expected = 'ḁḃḅḇḉḋḍḏḑḓḕḗḙḛḝḟḡḣḥḧḩḫḭḯḱḳḵḷḹḻḽḿṁṃṅṇṉṋṍṏṑṓṕṗṙṛṝṟṡṣṥṧṩṫṭṯṱṳṵṷṹṻṽṿẁẃẅẇẉẋẍẏẑẓẕẖẗẘẙẚạảấầẩẫậắằẳẵặẹẻẽếềểễệỉịọỏốồổỗộớờởỡợụủứừửữựỳỵỷỹ'; + $this->assertEquals($expected, $result); + + $string = 'ΩKÅℲ'; + $result = Multibyte::strtolower($string); + $expected = 'ωkåⅎ'; + $this->assertEquals($expected, $result); + + $string = 'ΩKÅ'; + $result = Multibyte::strtolower($string); + $expected = 'ωkå'; + $this->assertEquals($expected, $result); + + $string = 'ΩKÅ'; + $result = Multibyte::strtolower($string); + $expected = 'ωkå'; + $this->assertEquals($expected, $result); + + $string = 'ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪⅫⅬⅭⅮⅯↃ'; + $result = Multibyte::strtolower($string); + $expected = 'ⅰⅱⅲⅳⅴⅵⅶⅷⅸⅹⅺⅻⅼⅽⅾⅿↄ'; + $this->assertEquals($expected, $result); + + $string = 'ⒶⒷⒸⒹⒺⒻⒼⒽⒾⒿⓀⓁⓂⓃⓄⓅⓆⓇⓈⓉⓊⓋⓌⓍⓎⓏ'; + $result = Multibyte::strtolower($string); + $expected = 'ⓐⓑⓒⓓⓔⓕⓖⓗⓘⓙⓚⓛⓜⓝⓞⓟⓠⓡⓢⓣⓤⓥⓦⓧⓨⓩ'; + $this->assertEquals($expected, $result); + + $string = 'ⰀⰁⰂⰃⰄⰅⰆⰇⰈⰉⰊⰋⰌⰍⰎⰏⰐⰑⰒⰓⰔⰕⰖⰗⰘⰙⰚⰛⰜⰝⰞⰟⰠⰡⰢⰣⰤⰥⰦⰧⰨⰩⰪⰫⰬⰭⰮ'; + $result = Multibyte::strtolower($string); + $expected = 'ⰰⰱⰲⰳⰴⰵⰶⰷⰸⰹⰺⰻⰼⰽⰾⰿⱀⱁⱂⱃⱄⱅⱆⱇⱈⱉⱊⱋⱌⱍⱎⱏⱐⱑⱒⱓⱔⱕⱖⱗⱘⱙⱚⱛⱜⱝⱞ'; + $this->assertEquals($expected, $result); + + $string = 'ⲀⲂⲄⲆⲈⲊⲌⲎⲐⲒⲔⲖⲘⲚⲜⲞⲠⲢⲤⲦⲨⲪⲬⲮⲰⲲⲴⲶⲸⲺⲼⲾⳀⳂⳄⳆⳈⳊⳌⳎⳐⳒⳔⳖⳘⳚⳜⳞⳠⳢ'; + $result = Multibyte::strtolower($string); + $expected = 'ⲁⲃⲅⲇⲉⲋⲍⲏⲑⲓⲕⲗⲙⲛⲝⲟⲡⲣⲥⲧⲩⲫⲭⲯⲱⲳⲵⲷⲹⲻⲽⲿⳁⳃⳅⳇⳉⳋⳍⳏⳑⳓⳕⳗⳙⳛⳝⳟⳡⳣ'; + $this->assertEquals($expected, $result); + + $string = 'fffiflffifflſtstﬓﬔﬕﬖﬗ'; + $result = Multibyte::strtolower($string); + $expected = 'fffiflffifflſtstﬓﬔﬕﬖﬗ'; + $this->assertEquals($expected, $result); + } + +/** + * testUsingMbStrtoupper method + * + * @return void + */ + public function testUsingMbStrtoupper() { + $string = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'; + $result = mb_strtoupper($string); + $expected = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`ABCDEFGHIJKLMNOPQRSTUVWXYZ{|}~'; + $this->assertEquals($expected, $result); + + $string = '!"#$%&\'()*+,-./0123456789:;<=>?@'; + $result = mb_strtoupper($string); + $expected = '!"#$%&\'()*+,-./0123456789:;<=>?@'; + $this->assertEquals($expected, $result); + + $string = 'à'; + $result = mb_strtoupper($string); + $expected = 'À'; + $this->assertEquals($expected, $result); + + $string = 'á'; + $result = mb_strtoupper($string); + $expected = 'Á'; + $this->assertEquals($expected, $result); + + $string = 'â'; + $result = mb_strtoupper($string); + $expected = 'Â'; + $this->assertEquals($expected, $result); + + $string = 'ã'; + $result = mb_strtoupper($string); + $expected = 'Ã'; + $this->assertEquals($expected, $result); + + $string = 'ä'; + $result = mb_strtoupper($string); + $expected = 'Ä'; + $this->assertEquals($expected, $result); + + $string = 'å'; + $result = mb_strtoupper($string); + $expected = 'Å'; + $this->assertEquals($expected, $result); + + $string = 'æ'; + $result = mb_strtoupper($string); + $expected = 'Æ'; + $this->assertEquals($expected, $result); + + $string = 'ç'; + $result = mb_strtoupper($string); + $expected = 'Ç'; + $this->assertEquals($expected, $result); + + $string = 'è'; + $result = mb_strtoupper($string); + $expected = 'È'; + $this->assertEquals($expected, $result); + + $string = 'é'; + $result = mb_strtoupper($string); + $expected = 'É'; + $this->assertEquals($expected, $result); + + $string = 'ê'; + $result = mb_strtoupper($string); + $expected = 'Ê'; + $this->assertEquals($expected, $result); + + $string = 'ë'; + $result = mb_strtoupper($string); + $expected = 'Ë'; + $this->assertEquals($expected, $result); + + $string = 'ì'; + $result = mb_strtoupper($string); + $expected = 'Ì'; + $this->assertEquals($expected, $result); + + $string = 'í'; + $result = mb_strtoupper($string); + $expected = 'Í'; + $this->assertEquals($expected, $result); + + $string = 'î'; + $result = mb_strtoupper($string); + $expected = 'Î'; + $this->assertEquals($expected, $result); + + $string = 'ï'; + $result = mb_strtoupper($string); + $expected = 'Ï'; + $this->assertEquals($expected, $result); + + $string = 'ð'; + $result = mb_strtoupper($string); + $expected = 'Ð'; + $this->assertEquals($expected, $result); + + $string = 'ñ'; + $result = mb_strtoupper($string); + $expected = 'Ñ'; + $this->assertEquals($expected, $result); + + $string = 'ò'; + $result = mb_strtoupper($string); + $expected = 'Ò'; + $this->assertEquals($expected, $result); + + $string = 'ó'; + $result = mb_strtoupper($string); + $expected = 'Ó'; + $this->assertEquals($expected, $result); + + $string = 'ô'; + $result = mb_strtoupper($string); + $expected = 'Ô'; + $this->assertEquals($expected, $result); + + $string = 'õ'; + $result = mb_strtoupper($string); + $expected = 'Õ'; + $this->assertEquals($expected, $result); + + $string = 'ö'; + $result = mb_strtoupper($string); + $expected = 'Ö'; + $this->assertEquals($expected, $result); + + $string = 'ø'; + $result = mb_strtoupper($string); + $expected = 'Ø'; + $this->assertEquals($expected, $result); + + $string = 'ù'; + $result = mb_strtoupper($string); + $expected = 'Ù'; + $this->assertEquals($expected, $result); + + $string = 'ú'; + $result = mb_strtoupper($string); + $expected = 'Ú'; + $this->assertEquals($expected, $result); + + $string = 'û'; + $result = mb_strtoupper($string); + $expected = 'Û'; + $this->assertEquals($expected, $result); + + $string = 'ü'; + $result = mb_strtoupper($string); + $expected = 'Ü'; + $this->assertEquals($expected, $result); + + $string = 'ý'; + $result = mb_strtoupper($string); + $expected = 'Ý'; + $this->assertEquals($expected, $result); + + $string = 'þ'; + $result = mb_strtoupper($string); + $expected = 'Þ'; + $this->assertEquals($expected, $result); + + $string = 'àáâãäåæçèéêëìíîïðñòóôõöøùúûüýþ'; + $result = mb_strtoupper($string); + $expected = 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ'; + $this->assertEquals($expected, $result); + + $string = 'ā'; + $result = mb_strtoupper($string); + $expected = 'Ā'; + $this->assertEquals($expected, $result); + + $string = 'ă'; + $result = mb_strtoupper($string); + $expected = 'Ă'; + $this->assertEquals($expected, $result); + + $string = 'ą'; + $result = mb_strtoupper($string); + $expected = 'Ą'; + $this->assertEquals($expected, $result); + + $string = 'ć'; + $result = mb_strtoupper($string); + $expected = 'Ć'; + $this->assertEquals($expected, $result); + + $string = 'ĉ'; + $result = mb_strtoupper($string); + $expected = 'Ĉ'; + $this->assertEquals($expected, $result); + + $string = 'ċ'; + $result = mb_strtoupper($string); + $expected = 'Ċ'; + $this->assertEquals($expected, $result); + + $string = 'č'; + $result = mb_strtoupper($string); + $expected = 'Č'; + $this->assertEquals($expected, $result); + + $string = 'ď'; + $result = mb_strtoupper($string); + $expected = 'Ď'; + $this->assertEquals($expected, $result); + + $string = 'đ'; + $result = mb_strtoupper($string); + $expected = 'Đ'; + $this->assertEquals($expected, $result); + + $string = 'ē'; + $result = mb_strtoupper($string); + $expected = 'Ē'; + $this->assertEquals($expected, $result); + + $string = 'ĕ'; + $result = mb_strtoupper($string); + $expected = 'Ĕ'; + $this->assertEquals($expected, $result); + + $string = 'ė'; + $result = mb_strtoupper($string); + $expected = 'Ė'; + $this->assertEquals($expected, $result); + + $string = 'ę'; + $result = mb_strtoupper($string); + $expected = 'Ę'; + $this->assertEquals($expected, $result); + + $string = 'ě'; + $result = mb_strtoupper($string); + $expected = 'Ě'; + $this->assertEquals($expected, $result); + + $string = 'ĝ'; + $result = mb_strtoupper($string); + $expected = 'Ĝ'; + $this->assertEquals($expected, $result); + + $string = 'ğ'; + $result = mb_strtoupper($string); + $expected = 'Ğ'; + $this->assertEquals($expected, $result); + + $string = 'ġ'; + $result = mb_strtoupper($string); + $expected = 'Ġ'; + $this->assertEquals($expected, $result); + + $string = 'ģ'; + $result = mb_strtoupper($string); + $expected = 'Ģ'; + $this->assertEquals($expected, $result); + + $string = 'ĥ'; + $result = mb_strtoupper($string); + $expected = 'Ĥ'; + $this->assertEquals($expected, $result); + + $string = 'ħ'; + $result = mb_strtoupper($string); + $expected = 'Ħ'; + $this->assertEquals($expected, $result); + + $string = 'ĩ'; + $result = mb_strtoupper($string); + $expected = 'Ĩ'; + $this->assertEquals($expected, $result); + + $string = 'ī'; + $result = mb_strtoupper($string); + $expected = 'Ī'; + $this->assertEquals($expected, $result); + + $string = 'ĭ'; + $result = mb_strtoupper($string); + $expected = 'Ĭ'; + $this->assertEquals($expected, $result); + + $string = 'į'; + $result = mb_strtoupper($string); + $expected = 'Į'; + $this->assertEquals($expected, $result); + + $string = 'ij'; + $result = mb_strtoupper($string); + $expected = 'IJ'; + $this->assertEquals($expected, $result); + + $string = 'ĵ'; + $result = mb_strtoupper($string); + $expected = 'Ĵ'; + $this->assertEquals($expected, $result); + + $string = 'ķ'; + $result = mb_strtoupper($string); + $expected = 'Ķ'; + $this->assertEquals($expected, $result); + + $string = 'ĺ'; + $result = mb_strtoupper($string); + $expected = 'Ĺ'; + $this->assertEquals($expected, $result); + + $string = 'ļ'; + $result = mb_strtoupper($string); + $expected = 'Ļ'; + $this->assertEquals($expected, $result); + + $string = 'ľ'; + $result = mb_strtoupper($string); + $expected = 'Ľ'; + $this->assertEquals($expected, $result); + + $string = 'ŀ'; + $result = mb_strtoupper($string); + $expected = 'Ŀ'; + $this->assertEquals($expected, $result); + + $string = 'ł'; + $result = mb_strtoupper($string); + $expected = 'Ł'; + $this->assertEquals($expected, $result); + + $string = 'ń'; + $result = mb_strtoupper($string); + $expected = 'Ń'; + $this->assertEquals($expected, $result); + + $string = 'ņ'; + $result = mb_strtoupper($string); + $expected = 'Ņ'; + $this->assertEquals($expected, $result); + + $string = 'ň'; + $result = mb_strtoupper($string); + $expected = 'Ň'; + $this->assertEquals($expected, $result); + + $string = 'ŋ'; + $result = mb_strtoupper($string); + $expected = 'Ŋ'; + $this->assertEquals($expected, $result); + + $string = 'ō'; + $result = mb_strtoupper($string); + $expected = 'Ō'; + $this->assertEquals($expected, $result); + + $string = 'ŏ'; + $result = mb_strtoupper($string); + $expected = 'Ŏ'; + $this->assertEquals($expected, $result); + + $string = 'ő'; + $result = mb_strtoupper($string); + $expected = 'Ő'; + $this->assertEquals($expected, $result); + + $string = 'œ'; + $result = mb_strtoupper($string); + $expected = 'Œ'; + $this->assertEquals($expected, $result); + + $string = 'ŕ'; + $result = mb_strtoupper($string); + $expected = 'Ŕ'; + $this->assertEquals($expected, $result); + + $string = 'ŗ'; + $result = mb_strtoupper($string); + $expected = 'Ŗ'; + $this->assertEquals($expected, $result); + + $string = 'ř'; + $result = mb_strtoupper($string); + $expected = 'Ř'; + $this->assertEquals($expected, $result); + + $string = 'ś'; + $result = mb_strtoupper($string); + $expected = 'Ś'; + $this->assertEquals($expected, $result); + + $string = 'ŝ'; + $result = mb_strtoupper($string); + $expected = 'Ŝ'; + $this->assertEquals($expected, $result); + + $string = 'ş'; + $result = mb_strtoupper($string); + $expected = 'Ş'; + $this->assertEquals($expected, $result); + + $string = 'š'; + $result = mb_strtoupper($string); + $expected = 'Š'; + $this->assertEquals($expected, $result); + + $string = 'ţ'; + $result = mb_strtoupper($string); + $expected = 'Ţ'; + $this->assertEquals($expected, $result); + + $string = 'ť'; + $result = mb_strtoupper($string); + $expected = 'Ť'; + $this->assertEquals($expected, $result); + + $string = 'ŧ'; + $result = mb_strtoupper($string); + $expected = 'Ŧ'; + $this->assertEquals($expected, $result); + + $string = 'ũ'; + $result = mb_strtoupper($string); + $expected = 'Ũ'; + $this->assertEquals($expected, $result); + + $string = 'ū'; + $result = mb_strtoupper($string); + $expected = 'Ū'; + $this->assertEquals($expected, $result); + + $string = 'ŭ'; + $result = mb_strtoupper($string); + $expected = 'Ŭ'; + $this->assertEquals($expected, $result); + + $string = 'ů'; + $result = mb_strtoupper($string); + $expected = 'Ů'; + $this->assertEquals($expected, $result); + + $string = 'ű'; + $result = mb_strtoupper($string); + $expected = 'Ű'; + $this->assertEquals($expected, $result); + + $string = 'ų'; + $result = mb_strtoupper($string); + $expected = 'Ų'; + $this->assertEquals($expected, $result); + + $string = 'ŵ'; + $result = mb_strtoupper($string); + $expected = 'Ŵ'; + $this->assertEquals($expected, $result); + + $string = 'ŷ'; + $result = mb_strtoupper($string); + $expected = 'Ŷ'; + $this->assertEquals($expected, $result); + + $string = 'ź'; + $result = mb_strtoupper($string); + $expected = 'Ź'; + $this->assertEquals($expected, $result); + + $string = 'ż'; + $result = mb_strtoupper($string); + $expected = 'Ż'; + $this->assertEquals($expected, $result); + + $string = 'ž'; + $result = mb_strtoupper($string); + $expected = 'Ž'; + $this->assertEquals($expected, $result); + + $string = 'āăąćĉċčďđēĕėęěĝğġģĥħĩīĭįijĵķĺļľŀłńņňŋōŏőœŕŗřśŝşšţťŧũūŭůűųŵŷźżž'; + $result = mb_strtoupper($string); + $expected = 'ĀĂĄĆĈĊČĎĐĒĔĖĘĚĜĞĠĢĤĦĨĪĬĮIJĴĶĹĻĽĿŁŃŅŇŊŌŎŐŒŔŖŘŚŜŞŠŢŤŦŨŪŬŮŰŲŴŶŹŻŽ'; + $this->assertEquals($expected, $result); + + $string = 'Ĥēĺļŏ, Ŵőřļď!'; + $result = mb_strtoupper($string); + $expected = 'ĤĒĹĻŎ, ŴŐŘĻĎ!'; + $this->assertEquals($expected, $result); + + $string = 'ἀι'; + $result = mb_strtoupper($string); + $expected = 'ἈΙ'; + $this->assertEquals($expected, $result); + + $string = 'ԁԃԅԇԉԋԍԏԐԒ'; + $result = mb_strtoupper($string); + $expected = 'ԀԂԄԆԈԊԌԎԐԒ'; + $this->assertEquals($expected, $result); + + $string = 'աբգդեզէըթժիլխծկհձղճմյնշոչպջռսվտրցւփքօֆև'; + $result = mb_strtoupper($string); + $expected = 'ԱԲԳԴԵԶԷԸԹԺԻԼԽԾԿՀՁՂՃՄՅՆՇՈՉՊՋՌՍՎՏՐՑՒՓՔՕՖև'; + $this->assertEquals($expected, $result); + + $string = 'ႠႡႢႣႤႥႦႧႨႩႪႫႬႭႮႯႰႱႲႳႴႵႶႷႸႹႺႻႼႽႾႿჀჁჂჃჄჅ'; + $result = mb_strtoupper($string); + $expected = 'ႠႡႢႣႤႥႦႧႨႩႪႫႬႭႮႯႰႱႲႳႴႵႶႷႸႹႺႻႼႽႾႿჀჁჂჃჄჅ'; + $this->assertEquals($expected, $result); + + $string = 'ḁḃḅḇḉḋḍḏḑḓḕḗḙḛḝḟḡḣḥḧḩḫḭḯḱḳḵḷḹḻḽḿṁṃṅṇṉṋṍṏṑṓṕṗṙṛṝṟṡṣṥṧṩṫṭṯṱṳṵṷṹṻṽṿẁẃẅẇẉẋẍẏẑẓẕẖẗẘẙẚạảấầẩẫậắằẳẵặẹẻẽếềểễệỉịọỏốồổỗộớờởỡợụủứừửữựỳỵỷỹ'; + $result = mb_strtoupper($string); + $expected = 'ḀḂḄḆḈḊḌḎḐḒḔḖḘḚḜḞḠḢḤḦḨḪḬḮḰḲḴḶḸḺḼḾṀṂṄṆṈṊṌṎṐṒṔṖṘṚṜṞṠṢṤṦṨṪṬṮṰṲṴṶṸṺṼṾẀẂẄẆẈẊẌẎẐẒẔẖẗẘẙẚẠẢẤẦẨẪẬẮẰẲẴẶẸẺẼẾỀỂỄỆỈỊỌỎỐỒỔỖỘỚỜỞỠỢỤỦỨỪỬỮỰỲỴỶỸ'; + $this->assertEquals($expected, $result); + + $string = 'ωkå'; + $result = mb_strtoupper($string); + $expected = 'ΩKÅ'; + $this->assertEquals($expected, $result); + + $string = 'fffiflffifflſtstﬓﬔﬕﬖﬗ'; + $result = mb_strtoupper($string); + $expected = 'fffiflffifflſtstﬓﬔﬕﬖﬗ'; + $this->assertEquals($expected, $result); + } + +/** + * testMultibyteStrtoupper method + * + * @return void + */ + public function testMultibyteStrtoupper() { + $string = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'; + $result = Multibyte::strtoupper($string); + $expected = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`ABCDEFGHIJKLMNOPQRSTUVWXYZ{|}~'; + $this->assertEquals($expected, $result); + + $string = '!"#$%&\'()*+,-./0123456789:;<=>?@'; + $result = Multibyte::strtoupper($string); + $expected = '!"#$%&\'()*+,-./0123456789:;<=>?@'; + $this->assertEquals($expected, $result); + + $string = 'à'; + $result = Multibyte::strtoupper($string); + $expected = 'À'; + $this->assertEquals($expected, $result); + + $string = 'á'; + $result = Multibyte::strtoupper($string); + $expected = 'Á'; + $this->assertEquals($expected, $result); + + $string = 'â'; + $result = Multibyte::strtoupper($string); + $expected = 'Â'; + $this->assertEquals($expected, $result); + + $string = 'ã'; + $result = Multibyte::strtoupper($string); + $expected = 'Ã'; + $this->assertEquals($expected, $result); + + $string = 'ä'; + $result = Multibyte::strtoupper($string); + $expected = 'Ä'; + $this->assertEquals($expected, $result); + + $string = 'å'; + $result = Multibyte::strtoupper($string); + $expected = 'Å'; + $this->assertEquals($expected, $result); + + $string = 'æ'; + $result = Multibyte::strtoupper($string); + $expected = 'Æ'; + $this->assertEquals($expected, $result); + + $string = 'ç'; + $result = Multibyte::strtoupper($string); + $expected = 'Ç'; + $this->assertEquals($expected, $result); + + $string = 'è'; + $result = Multibyte::strtoupper($string); + $expected = 'È'; + $this->assertEquals($expected, $result); + + $string = 'é'; + $result = Multibyte::strtoupper($string); + $expected = 'É'; + $this->assertEquals($expected, $result); + + $string = 'ê'; + $result = Multibyte::strtoupper($string); + $expected = 'Ê'; + $this->assertEquals($expected, $result); + + $string = 'ë'; + $result = Multibyte::strtoupper($string); + $expected = 'Ë'; + $this->assertEquals($expected, $result); + + $string = 'ì'; + $result = Multibyte::strtoupper($string); + $expected = 'Ì'; + $this->assertEquals($expected, $result); + + $string = 'í'; + $result = Multibyte::strtoupper($string); + $expected = 'Í'; + $this->assertEquals($expected, $result); + + $string = 'î'; + $result = Multibyte::strtoupper($string); + $expected = 'Î'; + $this->assertEquals($expected, $result); + + $string = 'ï'; + $result = Multibyte::strtoupper($string); + $expected = 'Ï'; + $this->assertEquals($expected, $result); + + $string = 'ð'; + $result = Multibyte::strtoupper($string); + $expected = 'Ð'; + $this->assertEquals($expected, $result); + + $string = 'ñ'; + $result = Multibyte::strtoupper($string); + $expected = 'Ñ'; + $this->assertEquals($expected, $result); + + $string = 'ò'; + $result = Multibyte::strtoupper($string); + $expected = 'Ò'; + $this->assertEquals($expected, $result); + + $string = 'ó'; + $result = Multibyte::strtoupper($string); + $expected = 'Ó'; + $this->assertEquals($expected, $result); + + $string = 'ô'; + $result = Multibyte::strtoupper($string); + $expected = 'Ô'; + $this->assertEquals($expected, $result); + + $string = 'õ'; + $result = Multibyte::strtoupper($string); + $expected = 'Õ'; + $this->assertEquals($expected, $result); + + $string = 'ö'; + $result = Multibyte::strtoupper($string); + $expected = 'Ö'; + $this->assertEquals($expected, $result); + + $string = 'ø'; + $result = Multibyte::strtoupper($string); + $expected = 'Ø'; + $this->assertEquals($expected, $result); + + $string = 'ù'; + $result = Multibyte::strtoupper($string); + $expected = 'Ù'; + $this->assertEquals($expected, $result); + + $string = 'ú'; + $result = Multibyte::strtoupper($string); + $expected = 'Ú'; + $this->assertEquals($expected, $result); + + $string = 'û'; + $result = Multibyte::strtoupper($string); + $expected = 'Û'; + $this->assertEquals($expected, $result); + + $string = 'ü'; + $result = Multibyte::strtoupper($string); + $expected = 'Ü'; + $this->assertEquals($expected, $result); + + $string = 'ý'; + $result = Multibyte::strtoupper($string); + $expected = 'Ý'; + $this->assertEquals($expected, $result); + + $string = 'þ'; + $result = Multibyte::strtoupper($string); + $expected = 'Þ'; + $this->assertEquals($expected, $result); + + $string = 'àáâãäåæçèéêëìíîïðñòóôõöøùúûüýþ'; + $result = Multibyte::strtoupper($string); + $expected = 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ'; + $this->assertEquals($expected, $result); + + $string = 'ā'; + $result = Multibyte::strtoupper($string); + $expected = 'Ā'; + $this->assertEquals($expected, $result); + + $string = 'ă'; + $result = Multibyte::strtoupper($string); + $expected = 'Ă'; + $this->assertEquals($expected, $result); + + $string = 'ą'; + $result = Multibyte::strtoupper($string); + $expected = 'Ą'; + $this->assertEquals($expected, $result); + + $string = 'ć'; + $result = Multibyte::strtoupper($string); + $expected = 'Ć'; + $this->assertEquals($expected, $result); + + $string = 'ĉ'; + $result = Multibyte::strtoupper($string); + $expected = 'Ĉ'; + $this->assertEquals($expected, $result); + + $string = 'ċ'; + $result = Multibyte::strtoupper($string); + $expected = 'Ċ'; + $this->assertEquals($expected, $result); + + $string = 'č'; + $result = Multibyte::strtoupper($string); + $expected = 'Č'; + $this->assertEquals($expected, $result); + + $string = 'ď'; + $result = Multibyte::strtoupper($string); + $expected = 'Ď'; + $this->assertEquals($expected, $result); + + $string = 'đ'; + $result = Multibyte::strtoupper($string); + $expected = 'Đ'; + $this->assertEquals($expected, $result); + + $string = 'ē'; + $result = Multibyte::strtoupper($string); + $expected = 'Ē'; + $this->assertEquals($expected, $result); + + $string = 'ĕ'; + $result = Multibyte::strtoupper($string); + $expected = 'Ĕ'; + $this->assertEquals($expected, $result); + + $string = 'ė'; + $result = Multibyte::strtoupper($string); + $expected = 'Ė'; + $this->assertEquals($expected, $result); + + $string = 'ę'; + $result = Multibyte::strtoupper($string); + $expected = 'Ę'; + $this->assertEquals($expected, $result); + + $string = 'ě'; + $result = Multibyte::strtoupper($string); + $expected = 'Ě'; + $this->assertEquals($expected, $result); + + $string = 'ĝ'; + $result = Multibyte::strtoupper($string); + $expected = 'Ĝ'; + $this->assertEquals($expected, $result); + + $string = 'ğ'; + $result = Multibyte::strtoupper($string); + $expected = 'Ğ'; + $this->assertEquals($expected, $result); + + $string = 'ġ'; + $result = Multibyte::strtoupper($string); + $expected = 'Ġ'; + $this->assertEquals($expected, $result); + + $string = 'ģ'; + $result = Multibyte::strtoupper($string); + $expected = 'Ģ'; + $this->assertEquals($expected, $result); + + $string = 'ĥ'; + $result = Multibyte::strtoupper($string); + $expected = 'Ĥ'; + $this->assertEquals($expected, $result); + + $string = 'ħ'; + $result = Multibyte::strtoupper($string); + $expected = 'Ħ'; + $this->assertEquals($expected, $result); + + $string = 'ĩ'; + $result = Multibyte::strtoupper($string); + $expected = 'Ĩ'; + $this->assertEquals($expected, $result); + + $string = 'ī'; + $result = Multibyte::strtoupper($string); + $expected = 'Ī'; + $this->assertEquals($expected, $result); + + $string = 'ĭ'; + $result = Multibyte::strtoupper($string); + $expected = 'Ĭ'; + $this->assertEquals($expected, $result); + + $string = 'į'; + $result = Multibyte::strtoupper($string); + $expected = 'Į'; + $this->assertEquals($expected, $result); + + $string = 'ij'; + $result = Multibyte::strtoupper($string); + $expected = 'IJ'; + $this->assertEquals($expected, $result); + + $string = 'ĵ'; + $result = Multibyte::strtoupper($string); + $expected = 'Ĵ'; + $this->assertEquals($expected, $result); + + $string = 'ķ'; + $result = Multibyte::strtoupper($string); + $expected = 'Ķ'; + $this->assertEquals($expected, $result); + + $string = 'ĺ'; + $result = Multibyte::strtoupper($string); + $expected = 'Ĺ'; + $this->assertEquals($expected, $result); + + $string = 'ļ'; + $result = Multibyte::strtoupper($string); + $expected = 'Ļ'; + $this->assertEquals($expected, $result); + + $string = 'ľ'; + $result = Multibyte::strtoupper($string); + $expected = 'Ľ'; + $this->assertEquals($expected, $result); + + $string = 'ŀ'; + $result = Multibyte::strtoupper($string); + $expected = 'Ŀ'; + $this->assertEquals($expected, $result); + + $string = 'ł'; + $result = Multibyte::strtoupper($string); + $expected = 'Ł'; + $this->assertEquals($expected, $result); + + $string = 'ń'; + $result = Multibyte::strtoupper($string); + $expected = 'Ń'; + $this->assertEquals($expected, $result); + + $string = 'ņ'; + $result = Multibyte::strtoupper($string); + $expected = 'Ņ'; + $this->assertEquals($expected, $result); + + $string = 'ň'; + $result = Multibyte::strtoupper($string); + $expected = 'Ň'; + $this->assertEquals($expected, $result); + + $string = 'ŋ'; + $result = Multibyte::strtoupper($string); + $expected = 'Ŋ'; + $this->assertEquals($expected, $result); + + $string = 'ō'; + $result = Multibyte::strtoupper($string); + $expected = 'Ō'; + $this->assertEquals($expected, $result); + + $string = 'ŏ'; + $result = Multibyte::strtoupper($string); + $expected = 'Ŏ'; + $this->assertEquals($expected, $result); + + $string = 'ő'; + $result = Multibyte::strtoupper($string); + $expected = 'Ő'; + $this->assertEquals($expected, $result); + + $string = 'œ'; + $result = Multibyte::strtoupper($string); + $expected = 'Œ'; + $this->assertEquals($expected, $result); + + $string = 'ŕ'; + $result = Multibyte::strtoupper($string); + $expected = 'Ŕ'; + $this->assertEquals($expected, $result); + + $string = 'ŗ'; + $result = Multibyte::strtoupper($string); + $expected = 'Ŗ'; + $this->assertEquals($expected, $result); + + $string = 'ř'; + $result = Multibyte::strtoupper($string); + $expected = 'Ř'; + $this->assertEquals($expected, $result); + + $string = 'ś'; + $result = Multibyte::strtoupper($string); + $expected = 'Ś'; + $this->assertEquals($expected, $result); + + $string = 'ŝ'; + $result = Multibyte::strtoupper($string); + $expected = 'Ŝ'; + $this->assertEquals($expected, $result); + + $string = 'ş'; + $result = Multibyte::strtoupper($string); + $expected = 'Ş'; + $this->assertEquals($expected, $result); + + $string = 'š'; + $result = Multibyte::strtoupper($string); + $expected = 'Š'; + $this->assertEquals($expected, $result); + + $string = 'ţ'; + $result = Multibyte::strtoupper($string); + $expected = 'Ţ'; + $this->assertEquals($expected, $result); + + $string = 'ť'; + $result = Multibyte::strtoupper($string); + $expected = 'Ť'; + $this->assertEquals($expected, $result); + + $string = 'ŧ'; + $result = Multibyte::strtoupper($string); + $expected = 'Ŧ'; + $this->assertEquals($expected, $result); + + $string = 'ũ'; + $result = Multibyte::strtoupper($string); + $expected = 'Ũ'; + $this->assertEquals($expected, $result); + + $string = 'ū'; + $result = Multibyte::strtoupper($string); + $expected = 'Ū'; + $this->assertEquals($expected, $result); + + $string = 'ŭ'; + $result = Multibyte::strtoupper($string); + $expected = 'Ŭ'; + $this->assertEquals($expected, $result); + + $string = 'ů'; + $result = Multibyte::strtoupper($string); + $expected = 'Ů'; + $this->assertEquals($expected, $result); + + $string = 'ű'; + $result = Multibyte::strtoupper($string); + $expected = 'Ű'; + $this->assertEquals($expected, $result); + + $string = 'ų'; + $result = Multibyte::strtoupper($string); + $expected = 'Ų'; + $this->assertEquals($expected, $result); + + $string = 'ŵ'; + $result = Multibyte::strtoupper($string); + $expected = 'Ŵ'; + $this->assertEquals($expected, $result); + + $string = 'ŷ'; + $result = Multibyte::strtoupper($string); + $expected = 'Ŷ'; + $this->assertEquals($expected, $result); + + $string = 'ź'; + $result = Multibyte::strtoupper($string); + $expected = 'Ź'; + $this->assertEquals($expected, $result); + + $string = 'ż'; + $result = Multibyte::strtoupper($string); + $expected = 'Ż'; + $this->assertEquals($expected, $result); + + $string = 'ž'; + $result = Multibyte::strtoupper($string); + $expected = 'Ž'; + $this->assertEquals($expected, $result); + + $string = 'āăąćĉċčďđēĕėęěĝğġģĥħĩīĭįijĵķĺļľŀłńņňŋōŏőœŕŗřśŝşšţťŧũūŭůűųŵŷźżž'; + $result = Multibyte::strtoupper($string); + $expected = 'ĀĂĄĆĈĊČĎĐĒĔĖĘĚĜĞĠĢĤĦĨĪĬĮIJĴĶĹĻĽĿŁŃŅŇŊŌŎŐŒŔŖŘŚŜŞŠŢŤŦŨŪŬŮŰŲŴŶŹŻŽ'; + $this->assertEquals($expected, $result); + + $string = 'Ĥēĺļŏ, Ŵőřļď!'; + $result = Multibyte::strtoupper($string); + $expected = 'ĤĒĹĻŎ, ŴŐŘĻĎ!'; + $this->assertEquals($expected, $result); + + $string = 'ἀι'; + $result = mb_strtoupper($string); + $expected = 'ἈΙ'; + $this->assertEquals($expected, $result); + + $string = 'ἀι'; + $result = Multibyte::strtoupper($string); + $expected = 'ἈΙ'; + $this->assertEquals($expected, $result); + + $string = 'ԁԃԅԇԉԋԍԏԐԒ'; + $result = Multibyte::strtoupper($string); + $expected = 'ԀԂԄԆԈԊԌԎԐԒ'; + $this->assertEquals($expected, $result); + + $string = 'աբգդեզէըթժիլխծկհձղճմյնշոչպջռսվտրցւփքօֆև'; + $result = Multibyte::strtoupper($string); + $expected = 'ԱԲԳԴԵԶԷԸԹԺԻԼԽԾԿՀՁՂՃՄՅՆՇՈՉՊՋՌՍՎՏՐՑՒՓՔՕՖև'; + $this->assertEquals($expected, $result); + + $string = 'ႠႡႢႣႤႥႦႧႨႩႪႫႬႭႮႯႰႱႲႳႴႵႶႷႸႹႺႻႼႽႾႿჀჁჂჃჄჅ'; + $result = Multibyte::strtoupper($string); + $expected = 'ႠႡႢႣႤႥႦႧႨႩႪႫႬႭႮႯႰႱႲႳႴႵႶႷႸႹႺႻႼႽႾႿჀჁჂჃჄჅ'; + $this->assertEquals($expected, $result); + + $string = 'ḁḃḅḇḉḋḍḏḑḓḕḗḙḛḝḟḡḣḥḧḩḫḭḯḱḳḵḷḹḻḽḿṁṃṅṇṉṋṍṏṑṓṕṗṙṛṝṟṡṣṥṧṩṫṭṯṱṳṵṷṹṻṽṿẁẃẅẇẉẋẍẏẑẓẕẖẗẘẙẚạảấầẩẫậắằẳẵặẹẻẽếềểễệỉịọỏốồổỗộớờởỡợụủứừửữựỳỵỷỹ'; + $result = Multibyte::strtoupper($string); + $expected = 'ḀḂḄḆḈḊḌḎḐḒḔḖḘḚḜḞḠḢḤḦḨḪḬḮḰḲḴḶḸḺḼḾṀṂṄṆṈṊṌṎṐṒṔṖṘṚṜṞṠṢṤṦṨṪṬṮṰṲṴṶṸṺṼṾẀẂẄẆẈẊẌẎẐẒẔẖẗẘẙẚẠẢẤẦẨẪẬẮẰẲẴẶẸẺẼẾỀỂỄỆỈỊỌỎỐỒỔỖỘỚỜỞỠỢỤỦỨỪỬỮỰỲỴỶỸ'; + $this->assertEquals($expected, $result); + + $string = 'ωkåⅎ'; + $result = Multibyte::strtoupper($string); + $expected = 'ΩKÅℲ'; + $this->assertEquals($expected, $result); + + $string = 'ωkå'; + $result = Multibyte::strtoupper($string); + $expected = 'ΩKÅ'; + $this->assertEquals($expected, $result); + + $string = 'ⅰⅱⅲⅳⅴⅵⅶⅷⅸⅹⅺⅻⅼⅽⅾⅿↄ'; + $result = Multibyte::strtoupper($string); + $expected = 'ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪⅫⅬⅭⅮⅯↃ'; + $this->assertEquals($expected, $result); + + $string = 'ⓐⓑⓒⓓⓔⓕⓖⓗⓘⓙⓚⓛⓜⓝⓞⓟⓠⓡⓢⓣⓤⓥⓦⓧⓨⓩ'; + $result = Multibyte::strtoupper($string); + $expected = 'ⒶⒷⒸⒹⒺⒻⒼⒽⒾⒿⓀⓁⓂⓃⓄⓅⓆⓇⓈⓉⓊⓋⓌⓍⓎⓏ'; + $this->assertEquals($expected, $result); + + $string = 'ⰰⰱⰲⰳⰴⰵⰶⰷⰸⰹⰺⰻⰼⰽⰾⰿⱀⱁⱂⱃⱄⱅⱆⱇⱈⱉⱊⱋⱌⱍⱎⱏⱐⱑⱒⱓⱔⱕⱖⱗⱘⱙⱚⱛⱜⱝⱞ'; + $result = Multibyte::strtoupper($string); + $expected = 'ⰀⰁⰂⰃⰄⰅⰆⰇⰈⰉⰊⰋⰌⰍⰎⰏⰐⰑⰒⰓⰔⰕⰖⰗⰘⰙⰚⰛⰜⰝⰞⰟⰠⰡⰢⰣⰤⰥⰦⰧⰨⰩⰪⰫⰬⰭⰮ'; + $this->assertEquals($expected, $result); + + $string = 'ⲁⲃⲅⲇⲉⲋⲍⲏⲑⲓⲕⲗⲙⲛⲝⲟⲡⲣⲥⲧⲩⲫⲭⲯⲱⲳⲵⲷⲹⲻⲽⲿⳁⳃⳅⳇⳉⳋⳍⳏⳑⳓⳕⳗⳙⳛⳝⳟⳡⳣ'; + $result = Multibyte::strtoupper($string); + $expected = 'ⲀⲂⲄⲆⲈⲊⲌⲎⲐⲒⲔⲖⲘⲚⲜⲞⲠⲢⲤⲦⲨⲪⲬⲮⲰⲲⲴⲶⲸⲺⲼⲾⳀⳂⳄⳆⳈⳊⳌⳎⳐⳒⳔⳖⳘⳚⳜⳞⳠⳢ'; + $this->assertEquals($expected, $result); + + $string = 'fffiflffifflſtstﬓﬔﬕﬖﬗ'; + $result = Multibyte::strtoupper($string); + $expected = 'fffiflffifflſtstﬓﬔﬕﬖﬗ'; + $this->assertEquals($expected, $result); + } + +/** + * testUsingMbSubstrCount method + * + * @return void + */ + public function testUsingMbSubstrCount() { + $string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; + $find = 'F'; + $result = mb_substr_count($string, $find); + $expected = 1; + $this->assertEquals($expected, $result); + + $string = 'ABCDEFGHIJKLMNOPQFRSFTUVWXYZ0F12345F6789'; + $find = 'F'; + $result = mb_substr_count($string, $find); + $expected = 5; + $this->assertEquals($expected, $result); + + $string = 'ÀÁÂÃÄÅÆÇÈÉÅÊËÌÍÎÏÐÑÒÓÔÅÕÖØÅÙÚÛÅÜÝÞ'; + $find = 'Å'; + $result = mb_substr_count($string, $find); + $expected = 5; + $this->assertEquals($expected, $result); + + $string = 'ÀÁÙÚÂÃÄÅÆÇÈÙÚÉÊËÌÍÎÏÐÑÒÓÔÕÖØÅÙÚÛÜÝÞÙÚ'; + $find = 'ÙÚ'; + $result = mb_substr_count($string, $find); + $expected = 4; + $this->assertEquals($expected, $result); + + $string = 'ÀÁÂÃÄÅÆÇÈÉÊÅËÌÍÎÏÐÑÒÓÔÕÅÖØÅÙÚÅÛÜÅÝÞÅ'; + $find = 'Å'; + $result = mb_substr_count($string, $find); + $expected = 7; + $this->assertEquals($expected, $result); + + $string = 'ĊĀĂĄĆĈĊČĎĐĒĔĖĊĘĚĜĞĠĢĤĦĨĪĬĮĊIJĴĶĹĻĽĿŁŃŅŇŊŌĊŎŐŒŔŖŘŚŜŞŠŢĊŤŦŨŪŬŮŰĊŲŴŶŹŻŽ'; + $find = 'Ċ'; + $result = mb_substr_count($string, $find); + $expected = 7; + $this->assertEquals($expected, $result); + + $string = 'ĀĂĄĆĈĊČĎĐĒĔĖĘĚĜĊĞĠĢĤĦĨĪĬĮIJĴĶĹĻĽĿŁĊŃŅĊŇŊŌŎŐŒŔŖĊŘŚŜŞŠŢŤŦŨŪŬŮŰŲŴŶŹŻŽ'; + $find = 'Ċ'; + $result = mb_substr_count($string, $find); + $expected = 5; + $this->assertEquals($expected, $result); + + $string = '!"#$%&\'()*+,-./012F34567F89:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghiFjklmnopqFrstuvwFxyz{|}~'; + $find = 'F'; + $result = mb_substr_count($string, $find); + $expected = 6; + $this->assertEquals($expected, $result); + + $string = '¡¢£¤¥µ¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁµÂõÄÅÆǵÈ'; + $find = 'µ'; + $result = mb_substr_count($string, $find); + $expected = 5; + $this->assertEquals($expected, $result); + + $string = 'ÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôÕÖõö÷øùúûüýþÿĀāĂ㥹ĆćĈĉÕÖĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝÕÖĞğĠġĢģĤĥĦÕÖħĨĩĪīĬ'; + $find = 'ÕÖ'; + $result = mb_substr_count($string, $find); + $expected = 5; + $this->assertEquals($expected, $result); + + $string = 'ĭĮįİıIJijĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňʼnŊŋŌōĵĶķĸĹŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšĵĶķĸĹŢţŤťŦŧŨũŪūŬŭŮůŰűŲųĵĶķĸĹŴŵŶŷŸŹźŻżŽžſƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏƐ'; + $find = 'ĵĶķĸĹ'; + $result = mb_substr_count($string, $find); + $expected = 4; + $this->assertEquals($expected, $result); + + $string = 'ƑƒƓƔƕƖƸƗƘƙƚƛƜƝƞƟƠơƢƣƤƥƦƧƨƩƪƫƬƭƮƯưƱƲƳƴƵƶƷƸƹƺƻƼƽƾƿǀǁǂǃDŽDždžLJLjljNJƸNjnjǍǎǏǐǑǒǓƸǔǕǖǗǘǙǚƸǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰDZDzdzǴ'; + $find = 'Ƹ'; + $result = mb_substr_count($string, $find); + $expected = 5; + $this->assertEquals($expected, $result); + + $string = 'ƑƒƓƔƕƖƗƘƙƚƛƜƝƞƟƹƠơƢƣƤƥƦƧƨƩƹƪƫƬƭƮƯưƱƲƳƴƹƵƶƷƸƹƺƻƼƽƾƿǀǁǂƹǃDŽDždžLJLjljNJNjnjǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰDZDzdzǴ'; + $find = 'ƹ'; + $result = mb_substr_count($string, $find); + $expected = 5; + $this->assertEquals($expected, $result); + + $string = 'əɚɛɜɝɞʀɟɠɡɢɣɤɥɦɧɨɩɪɫɬɭɮɯɰɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿʀʁʂʃʄʅʆʀʇʈʉʊʋʌʍʎʏʐʑʒʓʔʕʖʗʘʙʚʛʜʝʞʟʠʡʢʣʤʥʦʧʀʨʩʪʫʬʭʮʯʰʱʲʳʴʵʶʷʸʹʺʀʻʼ'; + $find = 'ʀ'; + $result = mb_substr_count($string, $find); + $expected = 5; + $this->assertEquals($expected, $result); + + $string = 'ЀЁЂЃЄЅІЇЈЉЊЋЌЍЇЎЏАБВГДЕЖЗИЙКЛ'; + $find = 'Ї'; + $result = mb_substr_count($string, $find); + $expected = 2; + $this->assertEquals($expected, $result); + + $string = 'МНОПРСРТУФХЦЧШЩЪЫЬРЭЮЯабРвгдежзийклРмнопрстуфхцчшщъыь'; + $find = 'Р'; + $result = mb_substr_count($string, $find); + $expected = 5; + $this->assertEquals($expected, $result); + + $string = 'МНОПРСрТУФХЦЧШЩЪЫрЬЭЮЯабвгдежзийклмнопррстуфхцчшщъыь'; + $find = 'р'; + $result = mb_substr_count($string, $find); + $expected = 4; + $this->assertEquals($expected, $result); + + $string = 'فنقكلنمنهونىينًٌٍَُ'; + $find = 'ن'; + $result = mb_substr_count($string, $find); + $expected = 5; + $this->assertEquals($expected, $result); + + $string = '✰✱✲✳✿✴✵✶✷✸✿✹✺✻✼✽✾✿❀❁❂❃❄❅❆✿❇❈❉❊❋❌❍❎❏❐❑❒❓❔❕❖❗❘❙❚❛❜❝❞'; + $find = '✿'; + $result = mb_substr_count($string, $find); + $expected = 4; + $this->assertEquals($expected, $result); + + $string = '⺀⺁⺂⺃⺄⺅⺆⺇⺈⺉⺐⺊⺋⺌⺍⺎⺏⺐⺑⺒⺓⺔⺕⺖⺗⺘⺙⺛⺜⺝⺞⺟⺠⺡⺢⺣⺤⺥⺦⺧⺨⺐⺩⺪⺫⺬⺭⺮⺯⺰⺱⺲⺳⺴⺵⺶⺷⺸⺹⺺⺻⺼⺽⺾⺿⻀⻁⻂⻃⻄⻅⻆⻇⻈⻉⺐⻊⻋⻌⻍⻎⻏⻐⻑⻒⻓⻔⻕⻖⻗⻘⻙⻚⻛⻜⻝⻞⻟⻠'; + $find = '⺐'; + $result = mb_substr_count($string, $find); + $expected = 4; + $this->assertEquals($expected, $result); + + $string = '⽅⽆⽇⽈⽉⽊⽋⽌⽍⽎⽏⽐⽑⽒⽓⽔⽕⽖⽤⽗⽘⽙⽚⽛⽜⽝⽞⽟⽠⽡⽢⽣⽤⽥⽦⽧⽨⽩⽪⽫⽬⽭⽮⽯⽰⽱⽲⽳⽴⽵⽤⽶⽷⽸⽹⽺⽻⽼⽽⽾⽿'; + $find = '⽤'; + $result = mb_substr_count($string, $find); + $expected = 3; + $this->assertEquals($expected, $result); + + $string = '눡눢눣눤눥눦눺눻눼눧눨눩눪눫눬눭눮눯눰눱눲눳눴눵눶눷눸눹눺눻눼눽눾눿뉀뉁뉂뉃뉄뉅뉆뉇뉈뉉뉊뉋뉌뉍뉎뉏뉐뉑뉒뉓뉔뉕눺눻눼뉖뉗뉘뉙뉚뉛뉜뉝눺눻눼뉞뉟뉠뉡뉢뉣뉤뉥뉦뉧뉨뉩뉪뉫뉬뉭뉮뉯뉰뉱뉲뉳뉴뉵뉶뉷뉸뉹뉺뉻뉼뉽뉾뉿늀늁늂늃늄'; + $find = '눺눻눼'; + $result = mb_substr_count($string, $find); + $expected = 4; + $this->assertEquals($expected, $result); + + $string = 'ﺞﺟﺠﺡﹰﹱﹲﹳﹴ﹵ﹶﹷﹸﹹﹺﹻﹼﹽﹾﹿﺀﺁﺂﺃﺄﺅﺞﺟﺠﺡﺆﺇﺞﺟﺠﺡﺈﺉﺊﺋﺌﺍﺎﺏﺐﺑﺒﺓﺔﺕﺖﺗﺘﺙﺚﺛﺜﺝﺞﺟﺠﺡﺢﺣﺤﺥﺦﺧﺨﺩﺪﺫﺬﺭﺮﺯﺰ'; + $find = 'ﺞﺟﺠﺡ'; + $result = mb_substr_count($string, $find); + $expected = 4; + $this->assertEquals($expected, $result); + + $string = 'ﺱﺲﺳﺴﺵﺶﺷﺸﺹﺺﺻﺼﻞﺽﺾﺿﻀﻁﻂﻃﻄﻅﻆﻇﻈﻉﻊﻋﻌﻍﻎﻏﻐﻑﻒﻓﻔﻞﻕﻖﻗﻘﻙﻚﻛﻜﻝﻞﻟﻠﻡﻢﻣﻤﻥﻦﻧﻨﻩﻪﻫﻬﻭﻮﻯﻰﻱﻲﻳﻴﻵﻶﻷﻞﻸﻹﻺﻞﻻﻼ'; + $find = 'ﻞ'; + $result = mb_substr_count($string, $find); + $expected = 5; + $this->assertEquals($expected, $result); + + $string = 'abcdkefghijklmnopqrstuvwxkyz'; + $find = 'k'; + $result = mb_substr_count($string, $find); + $expected = 3; + $this->assertEquals($expected, $result); + + $string = 'abklmcdefghijklmnopqrstuvklmwxyz'; + $find = 'klm'; + $result = mb_substr_count($string, $find); + $expected = 3; + $this->assertEquals($expected, $result); + + $string = 'abcdppefghijklmnoppqrstuvwxyz'; + $find = 'ppe'; + $result = mb_substr_count($string, $find); + $expected = 1; + $this->assertEquals($expected, $result); + + $string = '。「」、・ヲァィゥェォャュョッーアイウエオカキク'; + $find = 'ア'; + $result = mb_substr_count($string, $find); + $expected = 1; + $this->assertEquals($expected, $result); + + $string = 'ケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン゙'; + $find = 'ハ'; + $result = mb_substr_count($string, $find); + $expected = 1; + $this->assertEquals($expected, $result); + + $string = 'Ĥēĺļŏ, Ŵőřļď!'; + $find = 'ő'; + $result = mb_substr_count($string, $find); + $expected = 1; + $this->assertEquals($expected, $result); + + $string = 'Ĥēĺļŏ, Ŵőřļď!'; + $find = 'ĺļ'; + $result = mb_substr_count($string, $find); + $expected = 1; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'o'; + $result = mb_substr_count($string, $find); + $expected = 2; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'rl'; + $result = mb_substr_count($string, $find); + $expected = 1; + $this->assertEquals($expected, $result); + + $string = 'čini'; + $find = 'n'; + $result = mb_substr_count($string, $find); + $expected = 1; + $this->assertEquals($expected, $result); + + $string = 'ničiničiini'; + $find = 'n'; + $result = mb_substr_count($string, $find); + $expected = 3; + $this->assertEquals($expected, $result); + + $string = 'moći'; + $find = 'ć'; + $result = mb_substr_count($string, $find); + $expected = 1; + $this->assertEquals($expected, $result); + + $string = 'moćimoćimoćmćioći'; + $find = 'ći'; + $result = mb_substr_count($string, $find); + $expected = 4; + $this->assertEquals($expected, $result); + + $string = 'državni'; + $find = 'ž'; + $result = mb_substr_count($string, $find); + $expected = 1; + $this->assertEquals($expected, $result); + + $string = '把百度设为首页'; + $find = '设'; + $result = mb_substr_count($string, $find); + $expected = 1; + $this->assertEquals($expected, $result); + + $string = '一二三周永龍'; + $find = '周'; + $result = mb_substr_count($string, $find); + $expected = 1; + $this->assertEquals($expected, $result); + + $string = 'Ĥēĺļŏ, Ŵőřļď!'; + $find = 'H'; + $result = mb_substr_count($string, $find); + $expected = 0; + $this->assertEquals($expected, $result); + } + +/** + * testMultibyteSubstrCount method + * + * @return void + */ + public function testMultibyteSubstrCount() { + $string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; + $find = 'F'; + $result = Multibyte::substrCount($string, $find); + $expected = 1; + $this->assertEquals($expected, $result); + + $string = 'ABCDEFGHIJKLMNOPQFRSFTUVWXYZ0F12345F6789'; + $find = 'F'; + $result = Multibyte::substrCount($string, $find); + $expected = 5; + $this->assertEquals($expected, $result); + + $string = 'ÀÁÂÃÄÅÆÇÈÉÅÊËÌÍÎÏÐÑÒÓÔÅÕÖØÅÙÚÛÅÜÝÞ'; + $find = 'Å'; + $result = Multibyte::substrCount($string, $find); + $expected = 5; + $this->assertEquals($expected, $result); + + $string = 'ÀÁÙÚÂÃÄÅÆÇÈÙÚÉÊËÌÍÎÏÐÑÒÓÔÕÖØÅÙÚÛÜÝÞÙÚ'; + $find = 'ÙÚ'; + $result = Multibyte::substrCount($string, $find); + $expected = 4; + $this->assertEquals($expected, $result); + + $string = 'ÀÁÂÃÄÅÆÇÈÉÊÅËÌÍÎÏÐÑÒÓÔÕÅÖØÅÙÚÅÛÜÅÝÞÅ'; + $find = 'Å'; + $result = Multibyte::substrCount($string, $find); + $expected = 7; + $this->assertEquals($expected, $result); + + $string = 'ĊĀĂĄĆĈĊČĎĐĒĔĖĊĘĚĜĞĠĢĤĦĨĪĬĮĊIJĴĶĹĻĽĿŁŃŅŇŊŌĊŎŐŒŔŖŘŚŜŞŠŢĊŤŦŨŪŬŮŰĊŲŴŶŹŻŽ'; + $find = 'Ċ'; + $result = Multibyte::substrCount($string, $find); + $expected = 7; + $this->assertEquals($expected, $result); + + $string = 'ĀĂĄĆĈĊČĎĐĒĔĖĘĚĜĊĞĠĢĤĦĨĪĬĮIJĴĶĹĻĽĿŁĊŃŅĊŇŊŌŎŐŒŔŖĊŘŚŜŞŠŢŤŦŨŪŬŮŰŲŴŶŹŻŽ'; + $find = 'Ċ'; + $result = Multibyte::substrCount($string, $find); + $expected = 5; + $this->assertEquals($expected, $result); + + $string = '!"#$%&\'()*+,-./012F34567F89:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghiFjklmnopqFrstuvwFxyz{|}~'; + $find = 'F'; + $result = Multibyte::substrCount($string, $find); + $expected = 6; + $this->assertEquals($expected, $result); + + $string = '¡¢£¤¥µ¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁµÂõÄÅÆǵÈ'; + $find = 'µ'; + $result = Multibyte::substrCount($string, $find); + $expected = 5; + $this->assertEquals($expected, $result); + + $string = 'ÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôÕÖõö÷øùúûüýþÿĀāĂ㥹ĆćĈĉÕÖĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝÕÖĞğĠġĢģĤĥĦÕÖħĨĩĪīĬ'; + $find = 'ÕÖ'; + $result = Multibyte::substrCount($string, $find); + $expected = 5; + $this->assertEquals($expected, $result); + + $string = 'ĭĮįİıIJijĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňʼnŊŋŌōĵĶķĸĹŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšĵĶķĸĹŢţŤťŦŧŨũŪūŬŭŮůŰűŲųĵĶķĸĹŴŵŶŷŸŹźŻżŽžſƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏƐ'; + $find = 'ĵĶķĸĹ'; + $result = Multibyte::substrCount($string, $find); + $expected = 4; + $this->assertEquals($expected, $result); + + $string = 'ƑƒƓƔƕƖƸƗƘƙƚƛƜƝƞƟƠơƢƣƤƥƦƧƨƩƪƫƬƭƮƯưƱƲƳƴƵƶƷƸƹƺƻƼƽƾƿǀǁǂǃDŽDždžLJLjljNJƸNjnjǍǎǏǐǑǒǓƸǔǕǖǗǘǙǚƸǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰDZDzdzǴ'; + $find = 'Ƹ'; + $result = Multibyte::substrCount($string, $find); + $expected = 5; + $this->assertEquals($expected, $result); + + $string = 'ƑƒƓƔƕƖƗƘƙƚƛƜƝƞƟƹƠơƢƣƤƥƦƧƨƩƹƪƫƬƭƮƯưƱƲƳƴƹƵƶƷƸƹƺƻƼƽƾƿǀǁǂƹǃDŽDždžLJLjljNJNjnjǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰDZDzdzǴ'; + $find = 'ƹ'; + $result = Multibyte::substrCount($string, $find); + $expected = 5; + $this->assertEquals($expected, $result); + + $string = 'əɚɛɜɝɞʀɟɠɡɢɣɤɥɦɧɨɩɪɫɬɭɮɯɰɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿʀʁʂʃʄʅʆʀʇʈʉʊʋʌʍʎʏʐʑʒʓʔʕʖʗʘʙʚʛʜʝʞʟʠʡʢʣʤʥʦʧʀʨʩʪʫʬʭʮʯʰʱʲʳʴʵʶʷʸʹʺʀʻʼ'; + $find = 'ʀ'; + $result = Multibyte::substrCount($string, $find); + $expected = 5; + $this->assertEquals($expected, $result); + + $string = 'ЀЁЂЃЄЅІЇЈЉЊЋЌЍЇЎЏАБВГДЕЖЗИЙКЛ'; + $find = 'Ї'; + $result = Multibyte::substrCount($string, $find); + $expected = 2; + $this->assertEquals($expected, $result); + + $string = 'МНОПРСРТУФХЦЧШЩЪЫЬРЭЮЯабРвгдежзийклРмнопрстуфхцчшщъыь'; + $find = 'Р'; + $result = Multibyte::substrCount($string, $find); + $expected = 5; + $this->assertEquals($expected, $result); + + $string = 'МНОПРСрТУФХЦЧШЩЪЫрЬЭЮЯабвгдежзийклмнопррстуфхцчшщъыь'; + $find = 'р'; + $result = Multibyte::substrCount($string, $find); + $expected = 4; + $this->assertEquals($expected, $result); + + $string = 'فنقكلنمنهونىينًٌٍَُ'; + $find = 'ن'; + $result = Multibyte::substrCount($string, $find); + $expected = 5; + $this->assertEquals($expected, $result); + + $string = '✰✱✲✳✿✴✵✶✷✸✿✹✺✻✼✽✾✿❀❁❂❃❄❅❆✿❇❈❉❊❋❌❍❎❏❐❑❒❓❔❕❖❗❘❙❚❛❜❝❞'; + $find = '✿'; + $result = Multibyte::substrCount($string, $find); + $expected = 4; + $this->assertEquals($expected, $result); + + $string = '⺀⺁⺂⺃⺄⺅⺆⺇⺈⺉⺐⺊⺋⺌⺍⺎⺏⺐⺑⺒⺓⺔⺕⺖⺗⺘⺙⺛⺜⺝⺞⺟⺠⺡⺢⺣⺤⺥⺦⺧⺨⺐⺩⺪⺫⺬⺭⺮⺯⺰⺱⺲⺳⺴⺵⺶⺷⺸⺹⺺⺻⺼⺽⺾⺿⻀⻁⻂⻃⻄⻅⻆⻇⻈⻉⺐⻊⻋⻌⻍⻎⻏⻐⻑⻒⻓⻔⻕⻖⻗⻘⻙⻚⻛⻜⻝⻞⻟⻠'; + $find = '⺐'; + $result = Multibyte::substrCount($string, $find); + $expected = 4; + $this->assertEquals($expected, $result); + + $string = '⽅⽆⽇⽈⽉⽊⽋⽌⽍⽎⽏⽐⽑⽒⽓⽔⽕⽖⽤⽗⽘⽙⽚⽛⽜⽝⽞⽟⽠⽡⽢⽣⽤⽥⽦⽧⽨⽩⽪⽫⽬⽭⽮⽯⽰⽱⽲⽳⽴⽵⽤⽶⽷⽸⽹⽺⽻⽼⽽⽾⽿'; + $find = '⽤'; + $result = Multibyte::substrCount($string, $find); + $expected = 3; + $this->assertEquals($expected, $result); + + $string = '눡눢눣눤눥눦눺눻눼눧눨눩눪눫눬눭눮눯눰눱눲눳눴눵눶눷눸눹눺눻눼눽눾눿뉀뉁뉂뉃뉄뉅뉆뉇뉈뉉뉊뉋뉌뉍뉎뉏뉐뉑뉒뉓뉔뉕눺눻눼뉖뉗뉘뉙뉚뉛뉜뉝눺눻눼뉞뉟뉠뉡뉢뉣뉤뉥뉦뉧뉨뉩뉪뉫뉬뉭뉮뉯뉰뉱뉲뉳뉴뉵뉶뉷뉸뉹뉺뉻뉼뉽뉾뉿늀늁늂늃늄'; + $find = '눺눻눼'; + $result = Multibyte::substrCount($string, $find); + $expected = 4; + $this->assertEquals($expected, $result); + + $string = 'ﺞﺟﺠﺡﹰﹱﹲﹳﹴ﹵ﹶﹷﹸﹹﹺﹻﹼﹽﹾﹿﺀﺁﺂﺃﺄﺅﺞﺟﺠﺡﺆﺇﺞﺟﺠﺡﺈﺉﺊﺋﺌﺍﺎﺏﺐﺑﺒﺓﺔﺕﺖﺗﺘﺙﺚﺛﺜﺝﺞﺟﺠﺡﺢﺣﺤﺥﺦﺧﺨﺩﺪﺫﺬﺭﺮﺯﺰ'; + $find = 'ﺞﺟﺠﺡ'; + $result = Multibyte::substrCount($string, $find); + $expected = 4; + $this->assertEquals($expected, $result); + + $string = 'ﺱﺲﺳﺴﺵﺶﺷﺸﺹﺺﺻﺼﻞﺽﺾﺿﻀﻁﻂﻃﻄﻅﻆﻇﻈﻉﻊﻋﻌﻍﻎﻏﻐﻑﻒﻓﻔﻞﻕﻖﻗﻘﻙﻚﻛﻜﻝﻞﻟﻠﻡﻢﻣﻤﻥﻦﻧﻨﻩﻪﻫﻬﻭﻮﻯﻰﻱﻲﻳﻴﻵﻶﻷﻞﻸﻹﻺﻞﻻﻼ'; + $find = 'ﻞ'; + $result = Multibyte::substrCount($string, $find); + $expected = 5; + $this->assertEquals($expected, $result); + + $string = 'abcdkefghijklmnopqrstuvwxkyz'; + $find = 'k'; + $result = Multibyte::substrCount($string, $find); + $expected = 3; + $this->assertEquals($expected, $result); + + $string = 'abklmcdefghijklmnopqrstuvklmwxyz'; + $find = 'klm'; + $result = Multibyte::substrCount($string, $find); + $expected = 3; + $this->assertEquals($expected, $result); + + $string = 'abcdppefghijklmnoppqrstuvwxyz'; + $find = 'ppe'; + $result = Multibyte::substrCount($string, $find); + $expected = 1; + $this->assertEquals($expected, $result); + + $string = '。「」、・ヲァィゥェォャュョッーアイウエオカキク'; + $find = 'ア'; + $result = Multibyte::substrCount($string, $find); + $expected = 1; + $this->assertEquals($expected, $result); + + $string = 'ケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン゙'; + $find = 'ハ'; + $result = Multibyte::substrCount($string, $find); + $expected = 1; + $this->assertEquals($expected, $result); + + $string = 'Ĥēĺļŏ, Ŵőřļď!'; + $find = 'ő'; + $result = Multibyte::substrCount($string, $find); + $expected = 1; + $this->assertEquals($expected, $result); + + $string = 'Ĥēĺļŏ, Ŵőřļď!'; + $find = 'ĺļ'; + $result = Multibyte::substrCount($string, $find); + $expected = 1; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'o'; + $result = Multibyte::substrCount($string, $find); + $expected = 2; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $find = 'rl'; + $result = Multibyte::substrCount($string, $find); + $expected = 1; + $this->assertEquals($expected, $result); + + $string = 'čini'; + $find = 'n'; + $result = Multibyte::substrCount($string, $find); + $expected = 1; + $this->assertEquals($expected, $result); + + $string = 'ničiničiini'; + $find = 'n'; + $result = Multibyte::substrCount($string, $find); + $expected = 3; + $this->assertEquals($expected, $result); + + $string = 'moći'; + $find = 'ć'; + $result = Multibyte::substrCount($string, $find); + $expected = 1; + $this->assertEquals($expected, $result); + + $string = 'moćimoćimoćmćioći'; + $find = 'ći'; + $result = Multibyte::substrCount($string, $find); + $expected = 4; + $this->assertEquals($expected, $result); + + $string = 'državni'; + $find = 'ž'; + $result = Multibyte::substrCount($string, $find); + $expected = 1; + $this->assertEquals($expected, $result); + + $string = '把百度设为首页'; + $find = '设'; + $result = Multibyte::substrCount($string, $find); + $expected = 1; + $this->assertEquals($expected, $result); + + $string = '一二三周永龍'; + $find = '周'; + $result = Multibyte::substrCount($string, $find); + $expected = 1; + $this->assertEquals($expected, $result); + + $string = 'Ĥēĺļŏ, Ŵőřļď!'; + $find = 'H'; + $result = Multibyte::substrCount($string, $find); + $expected = 0; + $this->assertEquals($expected, $result); + } + +/** + * testUsingMbSubstr method + * + * @return void + */ + public function testUsingMbSubstr() { + $string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; + $result = mb_substr($string, 4, 7); + $expected = 'EFGHIJK'; + $this->assertEquals($expected, $result); + + $string = 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ'; + $result = mb_substr($string, 4, 7); + $expected = 'ÄÅÆÇÈÉÊ'; + $this->assertEquals($expected, $result); + + $string = 'ĀĂĄĆĈĊČĎĐĒĔĖĘĚĜĞĠĢĤĦĨĪĬĮIJĴĶĹĻĽĿŁŃŅŇŊŌŎŐŒŔŖŘŚŜŞŠŢŤŦŨŪŬŮŰŲŴŶŹŻŽ'; + $result = mb_substr($string, 4, 7); + $expected = 'ĈĊČĎĐĒĔ'; + $this->assertEquals($expected, $result); + + $string = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'; + $result = mb_substr($string, 4, 7); + $expected = '%&\'()*+'; + $this->assertEquals($expected, $result); + + $string = '¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈ'; + $result = mb_substr($string, 4); + $expected = '¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈ'; + $this->assertEquals($expected, $result); + + $string = 'ÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬ'; + $result = mb_substr($string, 4, 7); + $expected = 'ÍÎÏÐÑÒÓ'; + $this->assertEquals($expected, $result); + + $string = 'ĭĮįİıIJijĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏƐ'; + $result = mb_substr($string, 4, 7); + $expected = 'ıIJijĴĵĶķ'; + $this->assertEquals($expected, $result); + + $string = 'ƑƒƓƔƕƖƗƘƙƚƛƜƝƞƟƠơƢƣƤƥƦƧƨƩƪƫƬƭƮƯưƱƲƳƴƵƶƷƸƹƺƻƼƽƾƿǀǁǂǃDŽDždžLJLjljNJNjnjǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰDZDzdzǴ'; + $result = mb_substr($string, 25); + $expected = 'ƪƫƬƭƮƯưƱƲƳƴƵƶƷƸƹƺƻƼƽƾƿǀǁǂǃDŽDždžLJLjljNJNjnjǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰDZDzdzǴ'; + $this->assertEquals($expected, $result); + + $string = 'əɚɛɜɝɞɟɠɡɢɣɤɥɦɧɨɩɪɫɬɭɮɯɰɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿʀʁʂʃʄʅʆʇʈʉʊʋʌʍʎʏʐʑʒʓʔʕʖʗʘʙʚʛʜʝʞʟʠʡʢʣʤʥʦʧʨʩʪʫʬʭʮʯʰʱʲʳʴʵʶʷʸʹʺʻʼ'; + $result = mb_substr($string, 3); + $expected = 'ɜɝɞɟɠɡɢɣɤɥɦɧɨɩɪɫɬɭɮɯɰɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿʀʁʂʃʄʅʆʇʈʉʊʋʌʍʎʏʐʑʒʓʔʕʖʗʘʙʚʛʜʝʞʟʠʡʢʣʤʥʦʧʨʩʪʫʬʭʮʯʰʱʲʳʴʵʶʷʸʹʺʻʼ'; + $this->assertEquals($expected, $result); + + $string = 'ЀЁЂЃЄЅІЇЈЉЊЋЌЍЎЏАБВГДЕЖЗИЙКЛ'; + $result = mb_substr($string, 3); + $expected = 'ЃЄЅІЇЈЉЊЋЌЍЎЏАБВГДЕЖЗИЙКЛ'; + $this->assertEquals($expected, $result); + + $string = 'МНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыь'; + $result = mb_substr($string, 3, 16); + $expected = 'ПРСТУФХЦЧШЩЪЫЬЭЮ'; + $this->assertEquals($expected, $result); + + $string = 'فقكلمنهوىيًٌٍَُ'; + $result = mb_substr($string, 3, 6); + $expected = 'لمنهوى'; + $this->assertEquals($expected, $result); + + $string = '✰✱✲✳✴✵✶✷✸✹✺✻✼✽✾✿❀❁❂❃❄❅❆❇❈❉❊❋❌❍❎❏❐❑❒❓❔❕❖❗❘❙❚❛❜❝❞'; + $result = mb_substr($string, 6, 14); + $expected = '✶✷✸✹✺✻✼✽✾✿❀❁❂❃'; + $this->assertEquals($expected, $result); + + $string = '⺀⺁⺂⺃⺄⺅⺆⺇⺈⺉⺊⺋⺌⺍⺎⺏⺐⺑⺒⺓⺔⺕⺖⺗⺘⺙⺛⺜⺝⺞⺟⺠⺡⺢⺣⺤⺥⺦⺧⺨⺩⺪⺫⺬⺭⺮⺯⺰⺱⺲⺳⺴⺵⺶⺷⺸⺹⺺⺻⺼⺽⺾⺿⻀⻁⻂⻃⻄⻅⻆⻇⻈⻉⻊⻋⻌⻍⻎⻏⻐⻑⻒⻓⻔⻕⻖⻗⻘⻙⻚⻛⻜⻝⻞⻟⻠'; + $result = mb_substr($string, 8, 13); + $expected = '⺈⺉⺊⺋⺌⺍⺎⺏⺐⺑⺒⺓⺔'; + $this->assertEquals($expected, $result); + + $string = '⽅⽆⽇⽈⽉⽊⽋⽌⽍⽎⽏⽐⽑⽒⽓⽔⽕⽖⽗⽘⽙⽚⽛⽜⽝⽞⽟⽠⽡⽢⽣⽤⽥⽦⽧⽨⽩⽪⽫⽬⽭⽮⽯⽰⽱⽲⽳⽴⽵⽶⽷⽸⽹⽺⽻⽼⽽⽾⽿'; + $result = mb_substr($string, 12, 24); + $expected = '⽑⽒⽓⽔⽕⽖⽗⽘⽙⽚⽛⽜⽝⽞⽟⽠⽡⽢⽣⽤⽥⽦⽧⽨'; + $this->assertEquals($expected, $result); + + $string = '눡눢눣눤눥눦눧눨눩눪눫눬눭눮눯눰눱눲눳눴눵눶눷눸눹눺눻눼눽눾눿뉀뉁뉂뉃뉄뉅뉆뉇뉈뉉뉊뉋뉌뉍뉎뉏뉐뉑뉒뉓뉔뉕뉖뉗뉘뉙뉚뉛뉜뉝뉞뉟뉠뉡뉢뉣뉤뉥뉦뉧뉨뉩뉪뉫뉬뉭뉮뉯뉰뉱뉲뉳뉴뉵뉶뉷뉸뉹뉺뉻뉼뉽뉾뉿늀늁늂늃늄'; + $result = mb_substr($string, 12, 24); + $expected = '눭눮눯눰눱눲눳눴눵눶눷눸눹눺눻눼눽눾눿뉀뉁뉂뉃뉄'; + $this->assertEquals($expected, $result); + + $string = 'ﹰﹱﹲﹳﹴ﹵ﹶﹷﹸﹹﹺﹻﹼﹽﹾﹿﺀﺁﺂﺃﺄﺅﺆﺇﺈﺉﺊﺋﺌﺍﺎﺏﺐﺑﺒﺓﺔﺕﺖﺗﺘﺙﺚﺛﺜﺝﺞﺟﺠﺡﺢﺣﺤﺥﺦﺧﺨﺩﺪﺫﺬﺭﺮﺯﺰ'; + $result = mb_substr($string, 12); + $expected = 'ﹼﹽﹾﹿﺀﺁﺂﺃﺄﺅﺆﺇﺈﺉﺊﺋﺌﺍﺎﺏﺐﺑﺒﺓﺔﺕﺖﺗﺘﺙﺚﺛﺜﺝﺞﺟﺠﺡﺢﺣﺤﺥﺦﺧﺨﺩﺪﺫﺬﺭﺮﺯﺰ'; + $this->assertEquals($expected, $result); + + $string = 'ﺱﺲﺳﺴﺵﺶﺷﺸﺹﺺﺻﺼﺽﺾﺿﻀﻁﻂﻃﻄﻅﻆﻇﻈﻉﻊﻋﻌﻍﻎﻏﻐﻑﻒﻓﻔﻕﻖﻗﻘﻙﻚﻛﻜﻝﻞﻟﻠﻡﻢﻣﻤﻥﻦﻧﻨﻩﻪﻫﻬﻭﻮﻯﻰﻱﻲﻳﻴﻵﻶﻷﻸﻹﻺﻻﻼ'; + $result = mb_substr($string, 24, 12); + $expected = 'ﻉﻊﻋﻌﻍﻎﻏﻐﻑﻒﻓﻔ'; + $this->assertEquals($expected, $result); + + $string = 'abcdefghijklmnopqrstuvwxyz'; + $result = mb_substr($string, 11, 2); + $expected = 'lm'; + $this->assertEquals($expected, $result); + + $string = '。「」、・ヲァィゥェォャュョッーアイウエオカキク'; + $result = mb_substr($string, 7, 11); + $expected = 'ィゥェォャュョッーアイ'; + $this->assertEquals($expected, $result); + + $string = 'ケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン゙'; + $result = mb_substr($string, 13, 13); + $expected = 'ニヌネノハヒフヘホマミムメ'; + $this->assertEquals($expected, $result); + + $string = 'Ĥēĺļŏ, Ŵőřļď!'; + $result = mb_substr($string, 3, 4); + $expected = 'ļŏ, '; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $result = mb_substr($string, 3, 4); + $expected = 'lo, '; + $this->assertEquals($expected, $result); + + $string = 'čini'; + $result = mb_substr($string, 3); + $expected = 'i'; + $this->assertEquals($expected, $result); + + $string = 'moći'; + $result = mb_substr($string, 1); + $expected = 'oći'; + $this->assertEquals($expected, $result); + + $string = 'državni'; + $result = mb_substr($string, 0, 2); + $expected = 'dr'; + $this->assertEquals($expected, $result); + + $string = '把百度设为首页'; + $result = mb_substr($string, 3, 3); + $expected = '设为首'; + $this->assertEquals($expected, $result); + + $string = '一二三周永龍'; + $result = mb_substr($string, 0, 1); + $expected = '一'; + $this->assertEquals($expected, $result); + + $string = '一二三周永龍'; + $result = mb_substr($string, 6); + $expected = false; + $this->assertEquals($expected, $result); + + $string = '一二三周永龍'; + $result = mb_substr($string, 0); + $expected = '一二三周永龍'; + $this->assertEquals($expected, $result); + } + +/** + * testMultibyteSubstr method + * + * @return void + */ + public function testMultibyteSubstr() { + $string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; + $result = Multibyte::substr($string, 4, 7); + $expected = 'EFGHIJK'; + $this->assertEquals($expected, $result); + + $string = 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ'; + $result = Multibyte::substr($string, 4, 7); + $expected = 'ÄÅÆÇÈÉÊ'; + $this->assertEquals($expected, $result); + + $string = 'ĀĂĄĆĈĊČĎĐĒĔĖĘĚĜĞĠĢĤĦĨĪĬĮIJĴĶĹĻĽĿŁŃŅŇŊŌŎŐŒŔŖŘŚŜŞŠŢŤŦŨŪŬŮŰŲŴŶŹŻŽ'; + $result = Multibyte::substr($string, 4, 7); + $expected = 'ĈĊČĎĐĒĔ'; + $this->assertEquals($expected, $result); + + $string = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'; + $result = Multibyte::substr($string, 4, 7); + $expected = '%&\'()*+'; + $this->assertEquals($expected, $result); + + $string = '¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈ'; + $result = Multibyte::substr($string, 4); + $expected = '¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈ'; + $this->assertEquals($expected, $result); + + $string = 'ÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬ'; + $result = Multibyte::substr($string, 4, 7); + $expected = 'ÍÎÏÐÑÒÓ'; + $this->assertEquals($expected, $result); + + $string = 'ĭĮįİıIJijĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏƐ'; + $result = Multibyte::substr($string, 4, 7); + $expected = 'ıIJijĴĵĶķ'; + $this->assertEquals($expected, $result); + + $string = 'ƑƒƓƔƕƖƗƘƙƚƛƜƝƞƟƠơƢƣƤƥƦƧƨƩƪƫƬƭƮƯưƱƲƳƴƵƶƷƸƹƺƻƼƽƾƿǀǁǂǃDŽDždžLJLjljNJNjnjǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰDZDzdzǴ'; + $result = Multibyte::substr($string, 25); + $expected = 'ƪƫƬƭƮƯưƱƲƳƴƵƶƷƸƹƺƻƼƽƾƿǀǁǂǃDŽDždžLJLjljNJNjnjǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰDZDzdzǴ'; + $this->assertEquals($expected, $result); + + $string = 'əɚɛɜɝɞɟɠɡɢɣɤɥɦɧɨɩɪɫɬɭɮɯɰɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿʀʁʂʃʄʅʆʇʈʉʊʋʌʍʎʏʐʑʒʓʔʕʖʗʘʙʚʛʜʝʞʟʠʡʢʣʤʥʦʧʨʩʪʫʬʭʮʯʰʱʲʳʴʵʶʷʸʹʺʻʼ'; + $result = Multibyte::substr($string, 3); + $expected = 'ɜɝɞɟɠɡɢɣɤɥɦɧɨɩɪɫɬɭɮɯɰɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿʀʁʂʃʄʅʆʇʈʉʊʋʌʍʎʏʐʑʒʓʔʕʖʗʘʙʚʛʜʝʞʟʠʡʢʣʤʥʦʧʨʩʪʫʬʭʮʯʰʱʲʳʴʵʶʷʸʹʺʻʼ'; + $this->assertEquals($expected, $result); + + $string = 'ЀЁЂЃЄЅІЇЈЉЊЋЌЍЎЏАБВГДЕЖЗИЙКЛ'; + $result = Multibyte::substr($string, 3); + $expected = 'ЃЄЅІЇЈЉЊЋЌЍЎЏАБВГДЕЖЗИЙКЛ'; + $this->assertEquals($expected, $result); + + $string = 'МНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыь'; + $result = Multibyte::substr($string, 3, 16); + $expected = 'ПРСТУФХЦЧШЩЪЫЬЭЮ'; + $this->assertEquals($expected, $result); + + $string = 'فقكلمنهوىيًٌٍَُ'; + $result = Multibyte::substr($string, 3, 6); + $expected = 'لمنهوى'; + $this->assertEquals($expected, $result); + + $string = '✰✱✲✳✴✵✶✷✸✹✺✻✼✽✾✿❀❁❂❃❄❅❆❇❈❉❊❋❌❍❎❏❐❑❒❓❔❕❖❗❘❙❚❛❜❝❞'; + $result = Multibyte::substr($string, 6, 14); + $expected = '✶✷✸✹✺✻✼✽✾✿❀❁❂❃'; + $this->assertEquals($expected, $result); + + $string = '⺀⺁⺂⺃⺄⺅⺆⺇⺈⺉⺊⺋⺌⺍⺎⺏⺐⺑⺒⺓⺔⺕⺖⺗⺘⺙⺛⺜⺝⺞⺟⺠⺡⺢⺣⺤⺥⺦⺧⺨⺩⺪⺫⺬⺭⺮⺯⺰⺱⺲⺳⺴⺵⺶⺷⺸⺹⺺⺻⺼⺽⺾⺿⻀⻁⻂⻃⻄⻅⻆⻇⻈⻉⻊⻋⻌⻍⻎⻏⻐⻑⻒⻓⻔⻕⻖⻗⻘⻙⻚⻛⻜⻝⻞⻟⻠'; + $result = Multibyte::substr($string, 8, 13); + $expected = '⺈⺉⺊⺋⺌⺍⺎⺏⺐⺑⺒⺓⺔'; + $this->assertEquals($expected, $result); + + $string = '⽅⽆⽇⽈⽉⽊⽋⽌⽍⽎⽏⽐⽑⽒⽓⽔⽕⽖⽗⽘⽙⽚⽛⽜⽝⽞⽟⽠⽡⽢⽣⽤⽥⽦⽧⽨⽩⽪⽫⽬⽭⽮⽯⽰⽱⽲⽳⽴⽵⽶⽷⽸⽹⽺⽻⽼⽽⽾⽿'; + $result = Multibyte::substr($string, 12, 24); + $expected = '⽑⽒⽓⽔⽕⽖⽗⽘⽙⽚⽛⽜⽝⽞⽟⽠⽡⽢⽣⽤⽥⽦⽧⽨'; + $this->assertEquals($expected, $result); + + $string = '눡눢눣눤눥눦눧눨눩눪눫눬눭눮눯눰눱눲눳눴눵눶눷눸눹눺눻눼눽눾눿뉀뉁뉂뉃뉄뉅뉆뉇뉈뉉뉊뉋뉌뉍뉎뉏뉐뉑뉒뉓뉔뉕뉖뉗뉘뉙뉚뉛뉜뉝뉞뉟뉠뉡뉢뉣뉤뉥뉦뉧뉨뉩뉪뉫뉬뉭뉮뉯뉰뉱뉲뉳뉴뉵뉶뉷뉸뉹뉺뉻뉼뉽뉾뉿늀늁늂늃늄'; + $result = Multibyte::substr($string, 12, 24); + $expected = '눭눮눯눰눱눲눳눴눵눶눷눸눹눺눻눼눽눾눿뉀뉁뉂뉃뉄'; + $this->assertEquals($expected, $result); + + $string = 'ﹰﹱﹲﹳﹴ﹵ﹶﹷﹸﹹﹺﹻﹼﹽﹾﹿﺀﺁﺂﺃﺄﺅﺆﺇﺈﺉﺊﺋﺌﺍﺎﺏﺐﺑﺒﺓﺔﺕﺖﺗﺘﺙﺚﺛﺜﺝﺞﺟﺠﺡﺢﺣﺤﺥﺦﺧﺨﺩﺪﺫﺬﺭﺮﺯﺰ'; + $result = Multibyte::substr($string, 12); + $expected = 'ﹼﹽﹾﹿﺀﺁﺂﺃﺄﺅﺆﺇﺈﺉﺊﺋﺌﺍﺎﺏﺐﺑﺒﺓﺔﺕﺖﺗﺘﺙﺚﺛﺜﺝﺞﺟﺠﺡﺢﺣﺤﺥﺦﺧﺨﺩﺪﺫﺬﺭﺮﺯﺰ'; + $this->assertEquals($expected, $result); + + $string = 'ﺱﺲﺳﺴﺵﺶﺷﺸﺹﺺﺻﺼﺽﺾﺿﻀﻁﻂﻃﻄﻅﻆﻇﻈﻉﻊﻋﻌﻍﻎﻏﻐﻑﻒﻓﻔﻕﻖﻗﻘﻙﻚﻛﻜﻝﻞﻟﻠﻡﻢﻣﻤﻥﻦﻧﻨﻩﻪﻫﻬﻭﻮﻯﻰﻱﻲﻳﻴﻵﻶﻷﻸﻹﻺﻻﻼ'; + $result = Multibyte::substr($string, 24, 12); + $expected = 'ﻉﻊﻋﻌﻍﻎﻏﻐﻑﻒﻓﻔ'; + $this->assertEquals($expected, $result); + + $string = 'abcdefghijklmnopqrstuvwxyz'; + $result = Multibyte::substr($string, 11, 2); + $expected = 'lm'; + $this->assertEquals($expected, $result); + + $string = '。「」、・ヲァィゥェォャュョッーアイウエオカキク'; + $result = Multibyte::substr($string, 7, 11); + $expected = 'ィゥェォャュョッーアイ'; + $this->assertEquals($expected, $result); + + $string = 'ケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン゙'; + $result = Multibyte::substr($string, 13, 13); + $expected = 'ニヌネノハヒフヘホマミムメ'; + $this->assertEquals($expected, $result); + + $string = 'Ĥēĺļŏ, Ŵőřļď!'; + $result = Multibyte::substr($string, 3, 4); + $expected = 'ļŏ, '; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $result = Multibyte::substr($string, 3, 4); + $expected = 'lo, '; + $this->assertEquals($expected, $result); + + $string = 'čini'; + $result = Multibyte::substr($string, 3); + $expected = 'i'; + $this->assertEquals($expected, $result); + + $string = 'moći'; + $result = Multibyte::substr($string, 1); + $expected = 'oći'; + $this->assertEquals($expected, $result); + + $string = 'državni'; + $result = Multibyte::substr($string, 0, 2); + $expected = 'dr'; + $this->assertEquals($expected, $result); + + $string = '把百度设为首页'; + $result = Multibyte::substr($string, 3, 3); + $expected = '设为首'; + $this->assertEquals($expected, $result); + + $string = '一二三周永龍'; + $result = Multibyte::substr($string, 0, 1); + $expected = '一'; + $this->assertEquals($expected, $result); + + $string = '一二三周永龍'; + $result = Multibyte::substr($string, 6); + $expected = false; + $this->assertEquals($expected, $result); + + $string = '一二三周永龍'; + $result = Multibyte::substr($string, 0); + $expected = '一二三周永龍'; + $this->assertEquals($expected, $result); + } + +/** + * testMultibyteSubstr method + * + * @return void + */ + public function testMultibyteMimeEncode() { + $string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; + $result = Multibyte::mimeEncode($string); + $this->assertEquals($string, $result); + + $string = 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ'; + $result = Multibyte::mimeEncode($string); + $expected = '=?UTF-8?B?w4DDgcOCw4PDhMOFw4bDh8OIw4nDisOLw4zDjcOOw4/DkMORw5LDk8OUw5U=?=' . "\r\n" . + ' =?UTF-8?B?w5bDmMOZw5rDm8Ocw53Dng==?='; + $this->assertEquals($expected, $result); + $result = Multibyte::mimeEncode($string, null, "\n"); + $expected = '=?UTF-8?B?w4DDgcOCw4PDhMOFw4bDh8OIw4nDisOLw4zDjcOOw4/DkMORw5LDk8OUw5U=?=' . "\n" . + ' =?UTF-8?B?w5bDmMOZw5rDm8Ocw53Dng==?='; + $this->assertEquals($expected, $result); + + $string = 'ĀĂĄĆĈĊČĎĐĒĔĖĘĚĜĞĠĢĤĦĨĪĬĮIJĴĶĹĻĽĿŁŃŅŇŊŌŎŐŒŔŖŘŚŜŞŠŢŤŦŨŪŬŮŰŲŴŶŹŻŽ'; + $result = Multibyte::mimeEncode($string); + $expected = '=?UTF-8?B?xIDEgsSExIbEiMSKxIzEjsSQxJLElMSWxJjEmsScxJ7EoMSixKTEpsSoxKo=?=' . "\r\n" . + ' =?UTF-8?B?xKzErsSyxLTEtsS5xLvEvcS/xYHFg8WFxYfFisWMxY7FkMWSxZTFlsWYxZo=?=' . "\r\n" . + ' =?UTF-8?B?xZzFnsWgxaLFpMWmxajFqsWsxa7FsMWyxbTFtsW5xbvFvQ==?='; + $this->assertEquals($expected, $result); + + $string = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'; + $result = Multibyte::mimeEncode($string); + $expected = '=?UTF-8?B?ISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xN?=' . "\r\n" . + ' =?UTF-8?B?Tk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6?=' . "\r\n" . + ' =?UTF-8?B?e3x9fg==?='; + $this->assertEquals($expected, $result); + + $string = '¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈ'; + $result = Multibyte::mimeEncode($string); + $expected = '=?UTF-8?B?wqHCosKjwqTCpcKmwqfCqMKpwqrCq8Kswq3CrsKvwrDCscKywrPCtMK1wrY=?=' . "\r\n" . + ' =?UTF-8?B?wrfCuMK5wrrCu8K8wr3CvsK/w4DDgcOCw4PDhMOFw4bDh8OI?='; + $this->assertEquals($expected, $result); + + $string = 'ÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬ'; + $result = Multibyte::mimeEncode($string); + $expected = '=?UTF-8?B?w4nDisOLw4zDjcOOw4/DkMORw5LDk8OUw5XDlsOXw5jDmcOaw5vDnMOdw54=?=' . "\r\n" . + ' =?UTF-8?B?w5/DoMOhw6LDo8Okw6XDpsOnw6jDqcOqw6vDrMOtw67Dr8Oww7HDssOzw7Q=?=' . "\r\n" . + ' =?UTF-8?B?w7XDtsO3w7jDucO6w7vDvMO9w77Dv8SAxIHEgsSDxITEhcSGxIfEiMSJxIo=?=' . "\r\n" . + ' =?UTF-8?B?xIvEjMSNxI7Ej8SQxJHEksSTxJTElcSWxJfEmMSZxJrEm8ScxJ3EnsSfxKA=?=' . "\r\n" . + ' =?UTF-8?B?xKHEosSjxKTEpcSmxKfEqMSpxKrEq8Ss?='; + $this->assertEquals($expected, $result); + + $string = 'ĭĮįİıIJijĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏƐ'; + $result = Multibyte::mimeEncode($string); + $expected = '=?UTF-8?B?xK3ErsSvxLDEscSyxLPEtMS1xLbEt8S4xLnEusS7xLzEvcS+xL/FgMWBxYI=?=' . "\r\n" . + ' =?UTF-8?B?xYPFhMWFxYbFh8WIxYnFisWLxYzFjcWOxY/FkMWRxZLFk8WUxZXFlsWXxZg=?=' . "\r\n" . + ' =?UTF-8?B?xZnFmsWbxZzFncWexZ/FoMWhxaLFo8WkxaXFpsWnxajFqcWqxavFrMWtxa4=?=' . "\r\n" . + ' =?UTF-8?B?xa/FsMWxxbLFs8W0xbXFtsW3xbjFucW6xbvFvMW9xb7Fv8aAxoHGgsaDxoQ=?=' . "\r\n" . + ' =?UTF-8?B?xoXGhsaHxojGicaKxovGjMaNxo7Gj8aQ?='; + $this->assertEquals($expected, $result); + + $string = 'ƑƒƓƔƕƖƗƘƙƚƛƜƝƞƟƠơƢƣƤƥƦƧƨƩƪƫƬƭƮƯưƱƲƳƴƵƶƷƸƹƺƻƼƽƾƿǀǁǂǃDŽDždžLJLjljNJNjnjǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰDZDzdzǴ'; + $result = Multibyte::mimeEncode($string); + $expected = '=?UTF-8?B?xpHGksaTxpTGlcaWxpfGmMaZxprGm8acxp3GnsafxqDGocaixqPGpMalxqY=?=' . "\r\n" . + ' =?UTF-8?B?xqfGqMapxqrGq8asxq3GrsavxrDGscayxrPGtMa1xrbGt8a4xrnGusa7xrw=?=' . "\r\n" . + ' =?UTF-8?B?xr3Gvsa/x4DHgceCx4PHhMeFx4bHh8eIx4nHiseLx4zHjceOx4/HkMeRx5I=?=' . "\r\n" . + ' =?UTF-8?B?x5PHlMeVx5bHl8eYx5nHmsebx5zHnceex5/HoMehx6LHo8ekx6XHpsenx6g=?=' . "\r\n" . + ' =?UTF-8?B?x6nHqserx6zHrceux6/HsMexx7LHs8e0?='; + $this->assertEquals($expected, $result); + + $string = 'əɚɛɜɝɞɟɠɡɢɣɤɥɦɧɨɩɪɫɬɭɮɯɰɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿʀʁʂʃʄʅʆʇʈʉʊʋʌʍʎʏʐʑʒʓʔʕʖʗʘʙʚʛʜʝʞʟʠʡʢʣʤʥʦʧʨʩʪʫʬʭʮʯʰʱʲʳʴʵʶʷʸʹʺʻʼ'; + $result = Multibyte::mimeEncode($string); + $expected = '=?UTF-8?B?yZnJmsmbyZzJncmeyZ/JoMmhyaLJo8mkyaXJpsmnyajJqcmqyavJrMmtya4=?=' . "\r\n" . + ' =?UTF-8?B?ya/JsMmxybLJs8m0ybXJtsm3ybjJucm6ybvJvMm9yb7Jv8qAyoHKgsqDyoQ=?=' . "\r\n" . + ' =?UTF-8?B?yoXKhsqHyojKicqKyovKjMqNyo7Kj8qQypHKksqTypTKlcqWypfKmMqZypo=?=' . "\r\n" . + ' =?UTF-8?B?ypvKnMqdyp7Kn8qgyqHKosqjyqTKpcqmyqfKqMqpyqrKq8qsyq3KrsqvyrA=?=' . "\r\n" . + ' =?UTF-8?B?yrHKssqzyrTKtcq2yrfKuMq5yrrKu8q8?='; + $this->assertEquals($expected, $result); + + $string = 'ЀЁЂЃЄЅІЇЈЉЊЋЌЍЎЏАБВГДЕЖЗИЙКЛ'; + $result = Multibyte::mimeEncode($string); + $expected = '=?UTF-8?B?0IDQgdCC0IPQhNCF0IbQh9CI0InQitCL0IzQjdCO0I/QkNCR0JLQk9CU0JU=?=' . "\r\n" . + ' =?UTF-8?B?0JbQl9CY0JnQmtCb?='; + $this->assertEquals($expected, $result); + + $string = 'МНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыь'; + $result = Multibyte::mimeEncode($string); + $expected = '=?UTF-8?B?0JzQndCe0J/QoNCh0KLQo9Ck0KXQptCn0KjQqdCq0KvQrNCt0K7Qr9Cw0LE=?=' . "\r\n" . + ' =?UTF-8?B?0LLQs9C00LXQttC30LjQudC60LvQvNC90L7Qv9GA0YHRgtGD0YTRhdGG0Yc=?=' . "\r\n" . + ' =?UTF-8?B?0YjRidGK0YvRjA==?='; + $this->assertEquals($expected, $result); + + $string = 'فقكلمنهوىيًٌٍَُ'; + $result = Multibyte::mimeEncode($string); + $expected = '=?UTF-8?B?2YHZgtmD2YTZhdmG2YfZiNmJ2YrZi9mM2Y3ZjtmP?='; + $this->assertEquals($expected, $result); + + $string = '✰✱✲✳✴✵✶✷✸✹✺✻✼✽✾✿❀❁❂❃❄❅❆❇❈❉❊❋❌❍❎❏❐❑❒❓❔❕❖❗❘❙❚❛❜❝❞'; + $result = Multibyte::mimeEncode($string); + $expected = '=?UTF-8?B?4pyw4pyx4pyy4pyz4py04py14py24py34py44py54py64py74py84py94py+?=' . "\r\n" . + ' =?UTF-8?B?4py/4p2A4p2B4p2C4p2D4p2E4p2F4p2G4p2H4p2I4p2J4p2K4p2L4p2M4p2N?=' . "\r\n" . + ' =?UTF-8?B?4p2O4p2P4p2Q4p2R4p2S4p2T4p2U4p2V4p2W4p2X4p2Y4p2Z4p2a4p2b4p2c?=' . "\r\n" . + ' =?UTF-8?B?4p2d4p2e?='; + $this->assertEquals($expected, $result); + + $string = '⺀⺁⺂⺃⺄⺅⺆⺇⺈⺉⺊⺋⺌⺍⺎⺏⺐⺑⺒⺓⺔⺕⺖⺗⺘⺙⺛⺜⺝⺞⺟⺠⺡⺢⺣⺤⺥⺦⺧⺨⺩⺪⺫⺬⺭⺮⺯⺰⺱⺲⺳⺴⺵⺶⺷⺸⺹⺺⺻⺼⺽⺾⺿⻀⻁⻂⻃⻄⻅⻆⻇⻈⻉⻊⻋⻌⻍⻎⻏⻐⻑⻒⻓⻔⻕⻖⻗⻘⻙⻚⻛⻜⻝⻞⻟⻠'; + $result = Multibyte::mimeEncode($string); + $expected = '=?UTF-8?B?4rqA4rqB4rqC4rqD4rqE4rqF4rqG4rqH4rqI4rqJ4rqK4rqL4rqM4rqN4rqO?=' . "\r\n" . + ' =?UTF-8?B?4rqP4rqQ4rqR4rqS4rqT4rqU4rqV4rqW4rqX4rqY4rqZ4rqb4rqc4rqd4rqe?=' . "\r\n" . + ' =?UTF-8?B?4rqf4rqg4rqh4rqi4rqj4rqk4rql4rqm4rqn4rqo4rqp4rqq4rqr4rqs4rqt?=' . "\r\n" . + ' =?UTF-8?B?4rqu4rqv4rqw4rqx4rqy4rqz4rq04rq14rq24rq34rq44rq54rq64rq74rq8?=' . "\r\n" . + ' =?UTF-8?B?4rq94rq+4rq/4ruA4ruB4ruC4ruD4ruE4ruF4ruG4ruH4ruI4ruJ4ruK4ruL?=' . "\r\n" . + ' =?UTF-8?B?4ruM4ruN4ruO4ruP4ruQ4ruR4ruS4ruT4ruU4ruV4ruW4ruX4ruY4ruZ4rua?=' . "\r\n" . + ' =?UTF-8?B?4rub4ruc4rud4rue4ruf4rug?='; + $this->assertEquals($expected, $result); + + $string = '⽅⽆⽇⽈⽉⽊⽋⽌⽍⽎⽏⽐⽑⽒⽓⽔⽕⽖⽗⽘⽙⽚⽛⽜⽝⽞⽟⽠⽡⽢⽣⽤⽥⽦⽧⽨⽩⽪⽫⽬⽭⽮⽯⽰⽱⽲⽳⽴⽵⽶⽷⽸⽹⽺⽻⽼⽽⽾⽿'; + $result = Multibyte::mimeEncode($string); + $expected = '=?UTF-8?B?4r2F4r2G4r2H4r2I4r2J4r2K4r2L4r2M4r2N4r2O4r2P4r2Q4r2R4r2S4r2T?=' . "\r\n" . + ' =?UTF-8?B?4r2U4r2V4r2W4r2X4r2Y4r2Z4r2a4r2b4r2c4r2d4r2e4r2f4r2g4r2h4r2i?=' . "\r\n" . + ' =?UTF-8?B?4r2j4r2k4r2l4r2m4r2n4r2o4r2p4r2q4r2r4r2s4r2t4r2u4r2v4r2w4r2x?=' . "\r\n" . + ' =?UTF-8?B?4r2y4r2z4r204r214r224r234r244r254r264r274r284r294r2+4r2/?='; + $this->assertEquals($expected, $result); + + $string = '눡눢눣눤눥눦눧눨눩눪눫눬눭눮눯눰눱눲눳눴눵눶눷눸눹눺눻눼눽눾눿뉀뉁뉂뉃뉄뉅뉆뉇뉈뉉뉊뉋뉌뉍뉎뉏뉐뉑뉒뉓뉔뉕뉖뉗뉘뉙뉚뉛뉜뉝뉞뉟뉠뉡뉢뉣뉤뉥뉦뉧뉨뉩뉪뉫뉬뉭뉮뉯뉰뉱뉲뉳뉴뉵뉶뉷뉸뉹뉺뉻뉼뉽뉾뉿늀늁늂늃늄'; + $result = Multibyte::mimeEncode($string); + $expected = '=?UTF-8?B?64ih64ii64ij64ik64il64im64in64io64ip64iq64ir64is64it64iu64iv?=' . "\r\n" . + ' =?UTF-8?B?64iw64ix64iy64iz64i064i164i264i364i464i564i664i764i864i964i+?=' . "\r\n" . + ' =?UTF-8?B?64i/64mA64mB64mC64mD64mE64mF64mG64mH64mI64mJ64mK64mL64mM64mN?=' . "\r\n" . + ' =?UTF-8?B?64mO64mP64mQ64mR64mS64mT64mU64mV64mW64mX64mY64mZ64ma64mb64mc?=' . "\r\n" . + ' =?UTF-8?B?64md64me64mf64mg64mh64mi64mj64mk64ml64mm64mn64mo64mp64mq64mr?=' . "\r\n" . + ' =?UTF-8?B?64ms64mt64mu64mv64mw64mx64my64mz64m064m164m264m364m464m564m6?=' . "\r\n" . + ' =?UTF-8?B?64m764m864m964m+64m/64qA64qB64qC64qD64qE?='; + $this->assertEquals($expected, $result); + + $string = 'ﹰﹱﹲﹳﹴ﹵ﹶﹷﹸﹹﹺﹻﹼﹽﹾﹿﺀﺁﺂﺃﺄﺅﺆﺇﺈﺉﺊﺋﺌﺍﺎﺏﺐﺑﺒﺓﺔﺕﺖﺗﺘﺙﺚﺛﺜﺝﺞﺟﺠﺡﺢﺣﺤﺥﺦﺧﺨﺩﺪﺫﺬﺭﺮﺯﺰ'; + $result = Multibyte::mimeEncode($string); + $expected = '=?UTF-8?B?77mw77mx77my77mz77m077m177m277m377m477m577m677m777m877m977m+?=' . "\r\n" . + ' =?UTF-8?B?77m/77qA77qB77qC77qD77qE77qF77qG77qH77qI77qJ77qK77qL77qM77qN?=' . "\r\n" . + ' =?UTF-8?B?77qO77qP77qQ77qR77qS77qT77qU77qV77qW77qX77qY77qZ77qa77qb77qc?=' . "\r\n" . + ' =?UTF-8?B?77qd77qe77qf77qg77qh77qi77qj77qk77ql77qm77qn77qo77qp77qq77qr?=' . "\r\n" . + ' =?UTF-8?B?77qs77qt77qu77qv77qw?='; + $this->assertEquals($expected, $result); + + $string = 'ﺱﺲﺳﺴﺵﺶﺷﺸﺹﺺﺻﺼﺽﺾﺿﻀﻁﻂﻃﻄﻅﻆﻇﻈﻉﻊﻋﻌﻍﻎﻏﻐﻑﻒﻓﻔﻕﻖﻗﻘﻙﻚﻛﻜﻝﻞﻟﻠﻡﻢﻣﻤﻥﻦﻧﻨﻩﻪﻫﻬﻭﻮﻯﻰﻱﻲﻳﻴﻵﻶﻷﻸﻹﻺﻻﻼ'; + $result = Multibyte::mimeEncode($string); + $expected = '=?UTF-8?B?77qx77qy77qz77q077q177q277q377q477q577q677q777q877q977q+77q/?=' . "\r\n" . + ' =?UTF-8?B?77uA77uB77uC77uD77uE77uF77uG77uH77uI77uJ77uK77uL77uM77uN77uO?=' . "\r\n" . + ' =?UTF-8?B?77uP77uQ77uR77uS77uT77uU77uV77uW77uX77uY77uZ77ua77ub77uc77ud?=' . "\r\n" . + ' =?UTF-8?B?77ue77uf77ug77uh77ui77uj77uk77ul77um77un77uo77up77uq77ur77us?=' . "\r\n" . + ' =?UTF-8?B?77ut77uu77uv77uw77ux77uy77uz77u077u177u277u377u477u577u677u7?=' . "\r\n" . + ' =?UTF-8?B?77u8?='; + $this->assertEquals($expected, $result); + + $string = 'abcdefghijklmnopqrstuvwxyz'; + $result = Multibyte::mimeEncode($string); + $expected = '=?UTF-8?B?772B772C772D772E772F772G772H772I772J772K772L772M772N772O772P?=' . "\r\n" . + ' =?UTF-8?B?772Q772R772S772T772U772V772W772X772Y772Z772a?='; + $this->assertEquals($expected, $result); + + $string = '。「」、・ヲァィゥェォャュョッーアイウエオカキク'; + $result = Multibyte::mimeEncode($string); + $expected = '=?UTF-8?B?772h772i772j772k772l772m772n772o772p772q772r772s772t772u772v?=' . "\r\n" . + ' =?UTF-8?B?772w772x772y772z77207721772277237724?='; + $this->assertEquals($expected, $result); + + $string = 'ケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン゙'; + $result = Multibyte::mimeEncode($string); + $expected = '=?UTF-8?B?77257726772777287729772+772/776A776B776C776D776E776F776G776H?=' . "\r\n" . + ' =?UTF-8?B?776I776J776K776L776M776N776O776P776Q776R776S776T776U776V776W?=' . "\r\n" . + ' =?UTF-8?B?776X776Y776Z776a776b776c776d776e?='; + $this->assertEquals($expected, $result); + + $string = 'Ĥēĺļŏ, Ŵőřļď!'; + $result = Multibyte::mimeEncode($string); + $expected = '=?UTF-8?B?xKTEk8S6xLzFjywgxbTFkcWZxLzEjyE=?='; + $this->assertEquals($expected, $result); + + $string = 'Hello, World!'; + $result = Multibyte::mimeEncode($string); + $this->assertEquals($string, $result); + + $string = 'čini'; + $result = Multibyte::mimeEncode($string); + $expected = '=?UTF-8?B?xI1pbmk=?='; + $this->assertEquals($expected, $result); + + $string = 'moći'; + $result = Multibyte::mimeEncode($string); + $expected = '=?UTF-8?B?bW/Eh2k=?='; + $this->assertEquals($expected, $result); + + $string = 'državni'; + $result = Multibyte::mimeEncode($string); + $expected = '=?UTF-8?B?ZHLFvmF2bmk=?='; + $this->assertEquals($expected, $result); + + $string = '把百度设为首页'; + $result = Multibyte::mimeEncode($string); + $expected = '=?UTF-8?B?5oqK55m+5bqm6K6+5Li66aaW6aG1?='; + $this->assertEquals($expected, $result); + + $string = '一二三周永龍'; + $result = Multibyte::mimeEncode($string); + $expected = '=?UTF-8?B?5LiA5LqM5LiJ5ZGo5rC46b6N?='; + $this->assertEquals($expected, $result); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Log/CakeLogTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Log/CakeLogTest.php new file mode 100644 index 0000000..7e0f05a --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Log/CakeLogTest.php @@ -0,0 +1,676 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Log + * @since CakePHP(tm) v 1.2.0.5432 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ + +App::uses('CakeLog', 'Log'); +App::uses('FileLog', 'Log/Engine'); + +/** + * CakeLogTest class + * + * @package Cake.Test.Case.Log + */ +class CakeLogTest extends CakeTestCase { + +/** + * Start test callback, clears all streams enabled. + * + * @return void + */ + public function setUp() { + parent::setUp(); + $streams = CakeLog::configured(); + foreach ($streams as $stream) { + CakeLog::drop($stream); + } + } + +/** + * test importing loggers from app/libs and plugins. + * + * @return void + */ + public function testImportingLoggers() { + App::build(array( + 'Lib' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Lib' . DS), + 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS) + ), App::RESET); + CakePlugin::load('TestPlugin'); + + $result = CakeLog::config('libtest', array( + 'engine' => 'TestAppLog' + )); + $this->assertTrue($result); + $this->assertEquals(CakeLog::configured(), array('libtest')); + + $result = CakeLog::config('plugintest', array( + 'engine' => 'TestPlugin.TestPluginLog' + )); + $this->assertTrue($result); + $this->assertEquals(CakeLog::configured(), array('libtest', 'plugintest')); + + CakeLog::write(LOG_INFO, 'TestPluginLog is not a BaseLog descendant'); + + App::build(); + CakePlugin::unload(); + } + +/** + * test all the errors from failed logger imports + * + * @expectedException CakeLogException + * @return void + */ + public function testImportingLoggerFailure() { + CakeLog::config('fail', array()); + } + +/** + * test config() with valid key name + * + * @return void + */ + public function testValidKeyName() { + CakeLog::config('valid', array('engine' => 'FileLog')); + $stream = CakeLog::stream('valid'); + $this->assertInstanceOf('FileLog', $stream); + CakeLog::drop('valid'); + } + +/** + * test config() with invalid key name + * + * @expectedException CakeLogException + * @return void + */ + public function testInvalidKeyName() { + CakeLog::config('1nv', array('engine' => 'FileLog')); + } + +/** + * test that loggers have to implement the correct interface. + * + * @expectedException CakeLogException + * @return void + */ + public function testNotImplementingInterface() { + CakeLog::config('fail', array('engine' => 'stdClass')); + } + +/** + * Test that CakeLog autoconfigures itself to use a FileLogger with the LOGS dir. + * When no streams are there. + * + * @return void + */ + public function testAutoConfig() { + if (file_exists(LOGS . 'error.log')) { + unlink(LOGS . 'error.log'); + } + CakeLog::write(LOG_WARNING, 'Test warning'); + $this->assertTrue(file_exists(LOGS . 'error.log')); + + $result = CakeLog::configured(); + $this->assertEquals(array('default'), $result); + + $testMessage = 'custom message'; + CakeLog::write('custom', $testMessage); + $content = file_get_contents(LOGS . 'custom.log'); + $this->assertContains($testMessage, $content); + unlink(LOGS . 'error.log'); + unlink(LOGS . 'custom.log'); + } + +/** + * test configuring log streams + * + * @return void + */ + public function testConfig() { + CakeLog::config('file', array( + 'engine' => 'FileLog', + 'path' => LOGS + )); + $result = CakeLog::configured(); + $this->assertEquals(array('file'), $result); + + if (file_exists(LOGS . 'error.log')) { + @unlink(LOGS . 'error.log'); + } + CakeLog::write(LOG_WARNING, 'Test warning'); + $this->assertTrue(file_exists(LOGS . 'error.log')); + + $result = file_get_contents(LOGS . 'error.log'); + $this->assertRegExp('/^2[0-9]{3}-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+ Warning: Test warning/', $result); + unlink(LOGS . 'error.log'); + } + +/** + * explicit tests for drop() + * + * @return void + **/ + public function testDrop() { + CakeLog::config('file', array( + 'engine' => 'FileLog', + 'path' => LOGS + )); + $result = CakeLog::configured(); + $this->assertEquals(array('file'), $result); + + CakeLog::drop('file'); + $result = CakeLog::configured(); + $this->assertEquals(array(), $result); + } + +/** + * testLogFileWriting method + * + * @return void + */ + public function testLogFileWriting() { + if (file_exists(LOGS . 'error.log')) { + unlink(LOGS . 'error.log'); + } + $result = CakeLog::write(LOG_WARNING, 'Test warning'); + $this->assertTrue($result); + $this->assertTrue(file_exists(LOGS . 'error.log')); + unlink(LOGS . 'error.log'); + + CakeLog::write(LOG_WARNING, 'Test warning 1'); + CakeLog::write(LOG_WARNING, 'Test warning 2'); + $result = file_get_contents(LOGS . 'error.log'); + $this->assertRegExp('/^2[0-9]{3}-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+ Warning: Test warning 1/', $result); + $this->assertRegExp('/2[0-9]{3}-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+ Warning: Test warning 2$/', $result); + unlink(LOGS . 'error.log'); + } + +/** + * test selective logging by level/type + * + * @return void + */ + public function testSelectiveLoggingByLevel() { + if (file_exists(LOGS . 'spam.log')) { + unlink(LOGS . 'spam.log'); + } + if (file_exists(LOGS . 'eggs.log')) { + unlink(LOGS . 'eggs.log'); + } + CakeLog::config('spam', array( + 'engine' => 'FileLog', + 'types' => 'info', + 'file' => 'spam', + )); + CakeLog::config('eggs', array( + 'engine' => 'FileLog', + 'types' => array('eggs', 'info', 'error', 'warning'), + 'file' => 'eggs', + )); + + $testMessage = 'selective logging'; + CakeLog::write(LOG_WARNING, $testMessage); + + $this->assertTrue(file_exists(LOGS . 'eggs.log')); + $this->assertFalse(file_exists(LOGS . 'spam.log')); + + CakeLog::write(LOG_INFO, $testMessage); + $this->assertTrue(file_exists(LOGS . 'spam.log')); + + $contents = file_get_contents(LOGS . 'spam.log'); + $this->assertContains('Info: ' . $testMessage, $contents); + $contents = file_get_contents(LOGS . 'eggs.log'); + $this->assertContains('Info: ' . $testMessage, $contents); + + if (file_exists(LOGS . 'spam.log')) { + unlink(LOGS . 'spam.log'); + } + if (file_exists(LOGS . 'eggs.log')) { + unlink(LOGS . 'eggs.log'); + } + } + +/** + * test enable + * + * @expectedException CakeLogException + */ + public function testStreamEnable() { + CakeLog::config('spam', array( + 'engine' => 'FileLog', + 'file' => 'spam', + )); + $this->assertTrue(CakeLog::enabled('spam')); + CakeLog::drop('spam'); + CakeLog::enable('bogus_stream'); + } + +/** + * test disable + * + * @expectedException CakeLogException + */ + public function testStreamDisable() { + CakeLog::config('spam', array( + 'engine' => 'FileLog', + 'file' => 'spam', + )); + $this->assertTrue(CakeLog::enabled('spam')); + CakeLog::disable('spam'); + $this->assertFalse(CakeLog::enabled('spam')); + CakeLog::drop('spam'); + CakeLog::enable('bogus_stream'); + } + +/** + * test enabled() invalid stream + * + * @expectedException CakeLogException + */ + public function testStreamEnabledInvalid() { + CakeLog::enabled('bogus_stream'); + } + +/** + * test disable invalid stream + * + * @expectedException CakeLogException + */ + public function testStreamDisableInvalid() { + CakeLog::disable('bogus_stream'); + } + + protected function _resetLogConfig() { + CakeLog::config('debug', array( + 'engine' => 'FileLog', + 'types' => array('notice', 'info', 'debug'), + 'file' => 'debug', + )); + CakeLog::config('error', array( + 'engine' => 'FileLog', + 'types' => array('warning', 'error', 'critical', 'alert', 'emergency'), + 'file' => 'error', + )); + } + + protected function _deleteLogs() { + if (file_exists(LOGS . 'shops.log')) { + unlink(LOGS . 'shops.log'); + } + if (file_exists(LOGS . 'error.log')) { + unlink(LOGS . 'error.log'); + } + if (file_exists(LOGS . 'debug.log')) { + unlink(LOGS . 'debug.log'); + } + if (file_exists(LOGS . 'bogus.log')) { + unlink(LOGS . 'bogus.log'); + } + if (file_exists(LOGS . 'spam.log')) { + unlink(LOGS . 'spam.log'); + } + if (file_exists(LOGS . 'eggs.log')) { + unlink(LOGS . 'eggs.log'); + } + } + +/** + * test backward compatible scoped logging + */ + public function testScopedLoggingBC() { + $this->_deleteLogs(); + + $this->_resetLogConfig(); + CakeLog::config('shops', array( + 'engine' => 'FileLog', + 'types' => array('info', 'notice', 'warning'), + 'scopes' => array('transactions', 'orders'), + 'file' => 'shops', + )); + + CakeLog::write('info', 'info message'); + $this->assertFalse(file_exists(LOGS . 'error.log')); + $this->assertTrue(file_exists(LOGS . 'shops.log')); + $this->assertTrue(file_exists(LOGS . 'debug.log')); + + $this->_deleteLogs(); + + CakeLog::write('transactions', 'transaction message'); + $this->assertTrue(file_exists(LOGS . 'shops.log')); + $this->assertFalse(file_exists(LOGS . 'transactions.log')); + $this->assertFalse(file_exists(LOGS . 'error.log')); + $this->assertFalse(file_exists(LOGS . 'debug.log')); + + $this->_deleteLogs(); + + CakeLog::write('error', 'error message'); + $this->assertTrue(file_exists(LOGS . 'error.log')); + $this->assertFalse(file_exists(LOGS . 'debug.log')); + $this->assertFalse(file_exists(LOGS . 'shops.log')); + + $this->_deleteLogs(); + + CakeLog::write('orders', 'order message'); + $this->assertFalse(file_exists(LOGS . 'error.log')); + $this->assertFalse(file_exists(LOGS . 'debug.log')); + $this->assertFalse(file_exists(LOGS . 'orders.log')); + $this->assertTrue(file_exists(LOGS . 'shops.log')); + + $this->_deleteLogs(); + + CakeLog::write('warning', 'warning message'); + $this->assertTrue(file_exists(LOGS . 'error.log')); + $this->assertTrue(file_exists(LOGS . 'shops.log')); + $this->assertFalse(file_exists(LOGS . 'debug.log')); + + $this->_deleteLogs(); + + CakeLog::drop('shops'); + } + +/** + * test scoped logging + * + * @return void + */ + public function testScopedLogging() { + if (file_exists(LOGS . 'shops.log')) { + unlink(LOGS . 'shops.log'); + } + if (file_exists(LOGS . 'error.log')) { + unlink(LOGS . 'error.log'); + } + if (file_exists(LOGS . 'debug.log')) { + unlink(LOGS . 'debug.log'); + } + + $this->_resetLogConfig(); + CakeLog::config('shops', array( + 'engine' => 'FileLog', + 'types' => array('info', 'notice', 'warning'), + 'scopes' => array('transactions', 'orders'), + 'file' => 'shops', + )); + + CakeLog::write('info', 'info message', 'transactions'); + $this->assertFalse(file_exists(LOGS . 'error.log')); + $this->assertTrue(file_exists(LOGS . 'shops.log')); + $this->assertTrue(file_exists(LOGS . 'debug.log')); + + $this->_deleteLogs(); + + CakeLog::write('transactions', 'transaction message', 'orders'); + $this->assertTrue(file_exists(LOGS . 'shops.log')); + $this->assertFalse(file_exists(LOGS . 'transactions.log')); + $this->assertFalse(file_exists(LOGS . 'error.log')); + $this->assertFalse(file_exists(LOGS . 'debug.log')); + + $this->_deleteLogs(); + + CakeLog::write('error', 'error message', 'orders'); + $this->assertTrue(file_exists(LOGS . 'error.log')); + $this->assertFalse(file_exists(LOGS . 'debug.log')); + $this->assertFalse(file_exists(LOGS . 'shops.log')); + + $this->_deleteLogs(); + + CakeLog::write('orders', 'order message', 'transactions'); + $this->assertFalse(file_exists(LOGS . 'error.log')); + $this->assertFalse(file_exists(LOGS . 'debug.log')); + $this->assertFalse(file_exists(LOGS . 'orders.log')); + $this->assertTrue(file_exists(LOGS . 'shops.log')); + + $this->_deleteLogs(); + + CakeLog::write('warning', 'warning message', 'orders'); + $this->assertTrue(file_exists(LOGS . 'error.log')); + $this->assertTrue(file_exists(LOGS . 'shops.log')); + $this->assertFalse(file_exists(LOGS . 'debug.log')); + + $this->_deleteLogs(); + + CakeLog::drop('shops'); + } + +/** + * test bogus type and scope + * + */ + public function testBogusTypeAndScope() { + $this->_resetLogConfig(); + $this->_deleteLogs(); + + CakeLog::write('bogus', 'bogus message'); + $this->assertTrue(file_exists(LOGS . 'bogus.log')); + $this->assertFalse(file_exists(LOGS . 'error.log')); + $this->assertFalse(file_exists(LOGS . 'debug.log')); + $this->_deleteLogs(); + + CakeLog::write('bogus', 'bogus message', 'bogus'); + $this->assertTrue(file_exists(LOGS . 'bogus.log')); + $this->assertFalse(file_exists(LOGS . 'error.log')); + $this->assertFalse(file_exists(LOGS . 'debug.log')); + $this->_deleteLogs(); + + CakeLog::write('error', 'bogus message', 'bogus'); + $this->assertFalse(file_exists(LOGS . 'bogus.log')); + $this->assertTrue(file_exists(LOGS . 'error.log')); + $this->assertFalse(file_exists(LOGS . 'debug.log')); + $this->_deleteLogs(); + } + +/** + * test scoped logging with convenience methods + */ + public function testConvenienceScopedLogging() { + if (file_exists(LOGS . 'shops.log')) { + unlink(LOGS . 'shops.log'); + } + if (file_exists(LOGS . 'error.log')) { + unlink(LOGS . 'error.log'); + } + if (file_exists(LOGS . 'debug.log')) { + unlink(LOGS . 'debug.log'); + } + + $this->_resetLogConfig(); + CakeLog::config('shops', array( + 'engine' => 'FileLog', + 'types' => array('info', 'notice', 'warning'), + 'scopes' => array('transactions', 'orders'), + 'file' => 'shops', + )); + + CakeLog::info('info message', 'transactions'); + $this->assertFalse(file_exists(LOGS . 'error.log')); + $this->assertTrue(file_exists(LOGS . 'shops.log')); + $this->assertTrue(file_exists(LOGS . 'debug.log')); + + $this->_deleteLogs(); + + CakeLog::error('error message', 'orders'); + $this->assertTrue(file_exists(LOGS . 'error.log')); + $this->assertFalse(file_exists(LOGS . 'debug.log')); + $this->assertFalse(file_exists(LOGS . 'shops.log')); + + $this->_deleteLogs(); + + CakeLog::warning('warning message', 'orders'); + $this->assertTrue(file_exists(LOGS . 'error.log')); + $this->assertTrue(file_exists(LOGS . 'shops.log')); + $this->assertFalse(file_exists(LOGS . 'debug.log')); + + $this->_deleteLogs(); + + CakeLog::drop('shops'); + } + +/** + * test convenience methods + */ + public function testConvenienceMethods() { + $this->_deleteLogs(); + + CakeLog::config('debug', array( + 'engine' => 'FileLog', + 'types' => array('notice', 'info', 'debug'), + 'file' => 'debug', + )); + CakeLog::config('error', array( + 'engine' => 'FileLog', + 'types' => array('emergency', 'alert', 'critical', 'error', 'warning'), + 'file' => 'error', + )); + + $testMessage = 'emergency message'; + CakeLog::emergency($testMessage); + $contents = file_get_contents(LOGS . 'error.log'); + $this->assertContains('Emergency: ' . $testMessage, $contents); + $this->assertFalse(file_exists(LOGS . 'debug.log')); + $this->_deleteLogs(); + + $testMessage = 'alert message'; + CakeLog::alert($testMessage); + $contents = file_get_contents(LOGS . 'error.log'); + $this->assertContains('Alert: ' . $testMessage, $contents); + $this->assertFalse(file_exists(LOGS . 'debug.log')); + $this->_deleteLogs(); + + $testMessage = 'critical message'; + CakeLog::critical($testMessage); + $contents = file_get_contents(LOGS . 'error.log'); + $this->assertContains('Critical: ' . $testMessage, $contents); + $this->assertFalse(file_exists(LOGS . 'debug.log')); + $this->_deleteLogs(); + + $testMessage = 'error message'; + CakeLog::error($testMessage); + $contents = file_get_contents(LOGS . 'error.log'); + $this->assertContains('Error: ' . $testMessage, $contents); + $this->assertFalse(file_exists(LOGS . 'debug.log')); + $this->_deleteLogs(); + + $testMessage = 'warning message'; + CakeLog::warning($testMessage); + $contents = file_get_contents(LOGS . 'error.log'); + $this->assertContains('Warning: ' . $testMessage, $contents); + $this->assertFalse(file_exists(LOGS . 'debug.log')); + $this->_deleteLogs(); + + $testMessage = 'notice message'; + CakeLog::notice($testMessage); + $contents = file_get_contents(LOGS . 'debug.log'); + $this->assertContains('Notice: ' . $testMessage, $contents); + $this->assertFalse(file_exists(LOGS . 'error.log')); + $this->_deleteLogs(); + + $testMessage = 'info message'; + CakeLog::info($testMessage); + $contents = file_get_contents(LOGS . 'debug.log'); + $this->assertContains('Info: ' . $testMessage, $contents); + $this->assertFalse(file_exists(LOGS . 'error.log')); + $this->_deleteLogs(); + + $testMessage = 'debug message'; + CakeLog::debug($testMessage); + $contents = file_get_contents(LOGS . 'debug.log'); + $this->assertContains('Debug: ' . $testMessage, $contents); + $this->assertFalse(file_exists(LOGS . 'error.log')); + $this->_deleteLogs(); + } + +/** + * test levels customization + */ + public function testLevelCustomization() { + $this->skipIf(DIRECTORY_SEPARATOR === '\\', 'Log level tests not supported on Windows.'); + + $levels = CakeLog::defaultLevels(); + $this->assertNotEmpty($levels); + $result = array_keys($levels); + $this->assertEquals(array(0, 1, 2, 3, 4, 5, 6, 7), $result); + + $levels = CakeLog::levels(array('foo', 'bar')); + CakeLog::defaultLevels(); + $this->assertEquals('foo', $levels[8]); + $this->assertEquals('bar', $levels[9]); + + $levels = CakeLog::levels(array(11 => 'spam', 'bar' => 'eggs')); + CakeLog::defaultLevels(); + $this->assertEquals('spam', $levels[8]); + $this->assertEquals('eggs', $levels[9]); + + $levels = CakeLog::levels(array(11 => 'spam', 'bar' => 'eggs'), false); + CakeLog::defaultLevels(); + $this->assertEquals(array('spam', 'eggs'), $levels); + + $levels = CakeLog::levels(array('ham', 9 => 'spam', '12' => 'fam'), false); + CakeLog::defaultLevels(); + $this->assertEquals(array('ham', 'spam', 'fam'), $levels); + } + +/** + * Test writing log files with custom levels + */ + public function testCustomLevelWrites() { + $this->_deleteLogs(); + $this->_resetLogConfig(); + + $levels = CakeLog::levels(array('spam', 'eggs')); + + $testMessage = 'error message'; + CakeLog::write('error', $testMessage); + CakeLog::defaultLevels(); + $this->assertTrue(file_exists(LOGS . 'error.log')); + $contents = file_get_contents(LOGS . 'error.log'); + $this->assertContains('Error: ' . $testMessage, $contents); + + CakeLog::config('spam', array( + 'engine' => 'FileLog', + 'file' => 'spam.log', + 'types' => 'spam', + )); + CakeLog::config('eggs', array( + 'engine' => 'FileLog', + 'file' => 'eggs.log', + 'types' => array('spam', 'eggs'), + )); + + $testMessage = 'spam message'; + CakeLog::write('spam', $testMessage); + CakeLog::defaultLevels(); + $this->assertTrue(file_exists(LOGS . 'spam.log')); + $this->assertTrue(file_exists(LOGS . 'eggs.log')); + $contents = file_get_contents(LOGS . 'spam.log'); + $this->assertContains('Spam: ' . $testMessage, $contents); + + $testMessage = 'egg message'; + CakeLog::write('eggs', $testMessage); + CakeLog::defaultLevels(); + $contents = file_get_contents(LOGS . 'spam.log'); + $this->assertNotContains('Eggs: ' . $testMessage, $contents); + $contents = file_get_contents(LOGS . 'eggs.log'); + $this->assertContains('Eggs: ' . $testMessage, $contents); + + CakeLog::drop('spam'); + CakeLog::drop('eggs'); + + $this->_deleteLogs(); + } + +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Log/Engine/ConsoleLogTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Log/Engine/ConsoleLogTest.php new file mode 100644 index 0000000..e786827 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Log/Engine/ConsoleLogTest.php @@ -0,0 +1,136 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Log.Engine + * @since CakePHP(tm) v 1.3 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ +App::uses('ConsoleLog', 'Log/Engine'); + +class TestConsoleLog extends ConsoleLog { + +} + +class TestCakeLog extends CakeLog { + + public static function replace($key, &$engine) { + self::$_Collection->{$key} = $engine; + } + +} + +/** + * ConsoleLogTest class + * + * @package Cake.Test.Case.Log.Engine + */ +class ConsoleLogTest extends CakeTestCase { + + public function setUp() { + parent::setUp(); + CakeLog::config('debug', array( + 'engine' => 'FileLog', + 'types' => array('notice', 'info', 'debug'), + 'file' => 'debug', + )); + CakeLog::config('error', array( + 'engine' => 'FileLog', + 'types' => array('error', 'warning'), + 'file' => 'error', + )); + } + + public function tearDown() { + parent::tearDown(); + if (file_exists(LOGS . 'error.log')) { + unlink(LOGS . 'error.log'); + } + if (file_exists(LOGS . 'debug.log')) { + unlink(LOGS . 'debug.log'); + } + } + +/** + * Test writing to ConsoleOutput + */ + public function testConsoleOutputWrites() { + TestCakeLog::config('test_console_log', array( + 'engine' => 'TestConsoleLog', + )); + + $mock = $this->getMock('TestConsoleLog', array('write'), array( + array('types' => 'error'), + )); + TestCakeLog::replace('test_console_log', $mock); + + $message = 'Test error message'; + $mock->expects($this->once()) + ->method('write'); + TestCakeLog::write(LOG_ERR, $message); + } + +/** + * Test logging to both ConsoleLog and FileLog + */ + public function testCombinedLogWriting() { + TestCakeLog::config('test_console_log', array( + 'engine' => 'TestConsoleLog', + )); + $mock = $this->getMock('TestConsoleLog', array('write'), array( + array('types' => 'error'), + )); + TestCakeLog::replace('test_console_log', $mock); + + // log to both file and console + $message = 'Test error message'; + $mock->expects($this->once()) + ->method('write'); + TestCakeLog::write(LOG_ERR, $message); + $this->assertTrue(file_exists(LOGS . 'error.log'), 'error.log missing'); + $logOutput = file_get_contents(LOGS . 'error.log'); + $this->assertContains($message, $logOutput); + + // TestConsoleLog is only interested in `error` type + $message = 'Test info message'; + $mock->expects($this->never()) + ->method('write'); + TestCakeLog::write(LOG_INFO, $message); + + // checks that output is correctly written in the correct logfile + $this->assertTrue(file_exists(LOGS . 'error.log'), 'error.log missing'); + $this->assertTrue(file_exists(LOGS . 'debug.log'), 'debug.log missing'); + $logOutput = file_get_contents(LOGS . 'error.log'); + $this->assertNotContains($message, $logOutput); + $logOutput = file_get_contents(LOGS . 'debug.log'); + $this->assertContains($message, $logOutput); + } + +/** + * test default value of stream 'outputAs' + */ + public function testDefaultOutputAs() { + TestCakeLog::config('test_console_log', array( + 'engine' => 'TestConsoleLog', + )); + if (DS == '\\' && !(bool)env('ANSICON')) { + $expected = ConsoleOutput::PLAIN; + } else { + $expected = ConsoleOutput::COLOR; + } + $stream = TestCakeLog::stream('test_console_log'); + $config = $stream->config(); + $this->assertEquals($expected, $config['outputAs']); + } + +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Log/Engine/FileLogTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Log/Engine/FileLogTest.php new file mode 100644 index 0000000..b4c13c8 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Log/Engine/FileLogTest.php @@ -0,0 +1,83 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Log.Engine + * @since CakePHP(tm) v 1.3 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ +App::uses('FileLog', 'Log/Engine'); + +/** + * CakeLogTest class + * + * @package Cake.Test.Case.Log.Engine + */ +class FileLogTest extends CakeTestCase { + +/** + * testLogFileWriting method + * + * @return void + */ + public function testLogFileWriting() { + if (file_exists(LOGS . 'error.log')) { + unlink(LOGS . 'error.log'); + } + $log = new FileLog(); + $log->write('warning', 'Test warning'); + $this->assertTrue(file_exists(LOGS . 'error.log')); + + $result = file_get_contents(LOGS . 'error.log'); + $this->assertRegExp('/^2[0-9]{3}-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+ Warning: Test warning/', $result); + unlink(LOGS . 'error.log'); + + if (file_exists(LOGS . 'debug.log')) { + unlink(LOGS . 'debug.log'); + } + $log->write('debug', 'Test warning'); + $this->assertTrue(file_exists(LOGS . 'debug.log')); + + $result = file_get_contents(LOGS . 'debug.log'); + $this->assertRegExp('/^2[0-9]{3}-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+ Debug: Test warning/', $result); + unlink(LOGS . 'debug.log'); + + if (file_exists(LOGS . 'random.log')) { + unlink(LOGS . 'random.log'); + } + $log->write('random', 'Test warning'); + $this->assertTrue(file_exists(LOGS . 'random.log')); + + $result = file_get_contents(LOGS . 'random.log'); + $this->assertRegExp('/^2[0-9]{3}-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+ Random: Test warning/', $result); + unlink(LOGS . 'random.log'); + } + +/** + * test using the path setting to write logs in other places. + * + * @return void + */ + public function testPathSetting() { + $path = TMP . 'tests' . DS; + if (file_exists(LOGS . 'error.log')) { + unlink(LOGS . 'error.log'); + } + + $log = new FileLog(compact('path')); + $log->write('warning', 'Test warning'); + $this->assertTrue(file_exists($path . 'error.log')); + unlink($path . 'error.log'); + } + +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/AclNodeTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/AclNodeTest.php new file mode 100644 index 0000000..cc297ba --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/AclNodeTest.php @@ -0,0 +1,385 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Model + * @since CakePHP(tm) v 1.2.0.4206 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ +App::uses('DbAcl', 'Controller/Component/Acl'); +App::uses('AclNode', 'Model'); + +/** + * DB ACL wrapper test class + * + * @package Cake.Test.Case.Model + */ +class DbAclNodeTestBase extends AclNode { + +/** + * useDbConfig property + * + * @var string 'test' + */ + public $useDbConfig = 'test'; + +/** + * cacheSources property + * + * @var bool false + */ + public $cacheSources = false; +} + +/** + * Aro Test Wrapper + * + * @package Cake.Test.Case.Model + */ +class DbAroTest extends DbAclNodeTestBase { + +/** + * name property + * + * @var string 'DbAroTest' + */ + public $name = 'DbAroTest'; + +/** + * useTable property + * + * @var string 'aros' + */ + public $useTable = 'aros'; + +/** + * hasAndBelongsToMany property + * + * @var array + */ + public $hasAndBelongsToMany = array('DbAcoTest' => array('with' => 'DbPermissionTest')); +} + +/** + * Aco Test Wrapper + * + * @package Cake.Test.Case.Model + */ +class DbAcoTest extends DbAclNodeTestBase { + +/** + * name property + * + * @var string 'DbAcoTest' + */ + public $name = 'DbAcoTest'; + +/** + * useTable property + * + * @var string 'acos' + */ + public $useTable = 'acos'; + +/** + * hasAndBelongsToMany property + * + * @var array + */ + public $hasAndBelongsToMany = array('DbAroTest' => array('with' => 'DbPermissionTest')); +} + +/** + * Permission Test Wrapper + * + * @package Cake.Test.Case.Model + */ +class DbPermissionTest extends CakeTestModel { + +/** + * name property + * + * @var string 'DbPermissionTest' + */ + public $name = 'DbPermissionTest'; + +/** + * useTable property + * + * @var string 'aros_acos' + */ + public $useTable = 'aros_acos'; + +/** + * cacheQueries property + * + * @var bool false + */ + public $cacheQueries = false; + +/** + * belongsTo property + * + * @var array + */ + public $belongsTo = array('DbAroTest' => array('foreignKey' => 'aro_id'), 'DbAcoTest' => array('foreignKey' => 'aco_id')); +} + +/** + * DboActionTest class + * + * @package Cake.Test.Case.Model + */ +class DbAcoActionTest extends CakeTestModel { + +/** + * name property + * + * @var string 'DbAcoActionTest' + */ + public $name = 'DbAcoActionTest'; + +/** + * useTable property + * + * @var string 'aco_actions' + */ + public $useTable = 'aco_actions'; + +/** + * belongsTo property + * + * @var array + */ + public $belongsTo = array('DbAcoTest' => array('foreignKey' => 'aco_id')); +} + +/** + * DbAroUserTest class + * + * @package Cake.Test.Case.Model + */ +class DbAroUserTest extends CakeTestModel { + +/** + * name property + * + * @var string 'AuthUser' + */ + public $name = 'AuthUser'; + +/** + * useTable property + * + * @var string 'auth_users' + */ + public $useTable = 'auth_users'; + +/** + * bindNode method + * + * @param string|array|Model $ref + * @return void + */ + public function bindNode($ref = null) { + if (Configure::read('DbAclbindMode') == 'string') { + return 'ROOT/admins/Gandalf'; + } elseif (Configure::read('DbAclbindMode') == 'array') { + return array('DbAroTest' => array('DbAroTest.model' => 'AuthUser', 'DbAroTest.foreign_key' => 2)); + } + } + +} + +/** + * TestDbAcl class + * + * @package Cake.Test.Case.Model + */ +class TestDbAcl extends DbAcl { + +/** + * construct method + * + * @return void + */ + public function __construct() { + $this->Aro = new DbAroTest(); + $this->Aro->Permission = new DbPermissionTest(); + $this->Aco = new DbAcoTest(); + $this->Aro->Permission = new DbPermissionTest(); + } + +} + +/** + * AclNodeTest class + * + * @package Cake.Test.Case.Model + */ +class AclNodeTest extends CakeTestCase { + +/** + * fixtures property + * + * @var array + */ + public $fixtures = array('core.aro', 'core.aco', 'core.aros_aco', 'core.aco_action', 'core.auth_user'); + +/** + * setUp method + * + * @return void + */ + public function setUp() { + parent::setUp(); + Configure::write('Acl.classname', 'TestDbAcl'); + Configure::write('Acl.database', 'test'); + } + +/** + * testNode method + * + * @return void + */ + public function testNode() { + $Aco = new DbAcoTest(); + $result = Hash::extract($Aco->node('Controller1'), '{n}.DbAcoTest.id'); + $expected = array(2, 1); + $this->assertEquals($expected, $result); + + $result = Hash::extract($Aco->node('Controller1/action1'), '{n}.DbAcoTest.id'); + $expected = array(3, 2, 1); + $this->assertEquals($expected, $result); + + $result = Hash::extract($Aco->node('Controller2/action1'), '{n}.DbAcoTest.id'); + $expected = array(7, 6, 1); + $this->assertEquals($expected, $result); + + $result = Hash::extract($Aco->node('Controller1/action2'), '{n}.DbAcoTest.id'); + $expected = array(5, 2, 1); + $this->assertEquals($expected, $result); + + $result = Hash::extract($Aco->node('Controller1/action1/record1'), '{n}.DbAcoTest.id'); + $expected = array(4, 3, 2, 1); + $this->assertEquals($expected, $result); + + $result = Hash::extract($Aco->node('Controller2/action1/record1'), '{n}.DbAcoTest.id'); + $expected = array(8, 7, 6, 1); + $this->assertEquals($expected, $result); + + $this->assertFalse($Aco->node('Controller2/action3')); + + $this->assertFalse($Aco->node('Controller2/action3/record5')); + + $result = $Aco->node(''); + $this->assertEquals(null, $result); + } + +/** + * test that node() doesn't dig deeper than it should. + * + * @return void + */ + public function testNodeWithDuplicatePathSegments() { + $Aco = new DbAcoTest(); + $nodes = $Aco->node('ROOT/Users'); + $this->assertEquals(1, $nodes[0]['DbAcoTest']['parent_id'], 'Parent id does not point at ROOT. %s'); + } + +/** + * testNodeArrayFind method + * + * @return void + */ + public function testNodeArrayFind() { + $Aro = new DbAroTest(); + Configure::write('DbAclbindMode', 'string'); + $result = Hash::extract($Aro->node(array('DbAroUserTest' => array('id' => '1', 'foreign_key' => '1'))), '{n}.DbAroTest.id'); + $expected = array(3, 2, 1); + $this->assertEquals($expected, $result); + + Configure::write('DbAclbindMode', 'array'); + $result = Hash::extract($Aro->node(array('DbAroUserTest' => array('id' => 4, 'foreign_key' => 2))), '{n}.DbAroTest.id'); + $expected = array(4); + $this->assertEquals($expected, $result); + } + +/** + * testNodeObjectFind method + * + * @return void + */ + public function testNodeObjectFind() { + $Aro = new DbAroTest(); + $Model = new DbAroUserTest(); + $Model->id = 1; + $result = Hash::extract($Aro->node($Model), '{n}.DbAroTest.id'); + $expected = array(3, 2, 1); + $this->assertEquals($expected, $result); + + $Model->id = 2; + $result = Hash::extract($Aro->node($Model), '{n}.DbAroTest.id'); + $expected = array(4, 2, 1); + $this->assertEquals($expected, $result); + } + +/** + * testNodeAliasParenting method + * + * @return void + */ + public function testNodeAliasParenting() { + $Aco = ClassRegistry::init('DbAcoTest'); + $db = $Aco->getDataSource(); + $db->truncate($Aco); + + $Aco->create(array('model' => null, 'foreign_key' => null, 'parent_id' => null, 'alias' => 'Application')); + $Aco->save(); + + $Aco->create(array('model' => null, 'foreign_key' => null, 'parent_id' => $Aco->id, 'alias' => 'Pages')); + $Aco->save(); + + $result = $Aco->find('all'); + $expected = array( + array('DbAcoTest' => array('id' => '1', 'parent_id' => null, 'model' => null, 'foreign_key' => null, 'alias' => 'Application', 'lft' => '1', 'rght' => '4'), 'DbAroTest' => array()), + array('DbAcoTest' => array('id' => '2', 'parent_id' => '1', 'model' => null, 'foreign_key' => null, 'alias' => 'Pages', 'lft' => '2', 'rght' => '3'), 'DbAroTest' => array()) + ); + $this->assertEquals($expected, $result); + } + +/** + * testNodeActionAuthorize method + * + * @return void + */ + public function testNodeActionAuthorize() { + App::build(array( + 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS) + ), App::RESET); + CakePlugin::load('TestPlugin'); + + $Aro = new DbAroTest(); + $Aro->create(); + $Aro->save(array('model' => 'TestPluginAuthUser', 'foreign_key' => 1)); + $result = $Aro->id; + $expected = 5; + $this->assertEquals($expected, $result); + + $node = $Aro->node(array('TestPlugin.TestPluginAuthUser' => array('id' => 1, 'user' => 'mariano'))); + $result = Hash::get($node, '0.DbAroTest.id'); + $expected = $Aro->id; + $this->assertEquals($expected, $result); + CakePlugin::unload('TestPlugin'); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Behavior/AclBehaviorTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Behavior/AclBehaviorTest.php new file mode 100644 index 0000000..f37bcaa --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Behavior/AclBehaviorTest.php @@ -0,0 +1,491 @@ + 'both'); + +/** + * belongsTo property + * + * @var array + */ + public $belongsTo = array( + 'Mother' => array( + 'className' => 'AclPerson', + 'foreignKey' => 'mother_id', + ) + ); + +/** + * hasMany property + * + * @var array + */ + public $hasMany = array( + 'Child' => array( + 'className' => 'AclPerson', + 'foreignKey' => 'mother_id' + ) + ); + +/** + * parentNode method + * + * @return void + */ + public function parentNode() { + if (!$this->id && empty($this->data)) { + return null; + } + if (isset($this->data['AclPerson']['mother_id'])) { + $motherId = $this->data['AclPerson']['mother_id']; + } else { + $motherId = $this->field('mother_id'); + } + if (!$motherId) { + return null; + } else { + return array('AclPerson' => array('id' => $motherId)); + } + } + +} + +/** + * AclUser class + * + * @package Cake.Test.Case.Model.Behavior + */ +class AclUser extends CakeTestModel { + +/** + * name property + * + * @var string + */ + public $name = 'User'; + +/** + * useTable property + * + * @var string + */ + public $useTable = 'users'; + +/** + * actsAs property + * + * @var array + */ + public $actsAs = array('Acl' => array('type' => 'requester')); + +/** + * parentNode + * + */ + public function parentNode() { + return null; + } + +} + +/** + * AclPost class + * + * @package Cake.Test.Case.Model.Behavior + */ +class AclPost extends CakeTestModel { + +/** + * name property + * + * @var string + */ + public $name = 'Post'; + +/** + * useTable property + * + * @var string + */ + public $useTable = 'posts'; + +/** + * actsAs property + * + * @var array + */ + public $actsAs = array('Acl' => array('type' => 'Controlled')); + +/** + * parentNode + * + */ + public function parentNode() { + return null; + } + +} + +/** + * AclBehaviorTest class + * + * @package Cake.Test.Case.Model.Behavior + */ +class AclBehaviorTest extends CakeTestCase { + +/** + * Aco property + * + * @var Aco + */ + public $Aco; + +/** + * Aro property + * + * @var Aro + */ + public $Aro; + +/** + * fixtures property + * + * @var array + */ + public $fixtures = array('core.person', 'core.user', 'core.post', 'core.aco', 'core.aro', 'core.aros_aco'); + +/** + * Set up the test + * + * @return void + */ + public function setUp() { + parent::setUp(); + Configure::write('Acl.database', 'test'); + + $this->Aco = new Aco(); + $this->Aro = new Aro(); + } + +/** + * tearDown method + * + * @return void + */ + public function tearDown() { + parent::tearDown(); + unset($this->Aro, $this->Aco); + } + +/** + * Test Setup of AclBehavior + * + * @return void + */ + public function testSetup() { + $User = new AclUser(); + $this->assertTrue(isset($User->Behaviors->Acl->settings['User'])); + $this->assertEquals('requester', $User->Behaviors->Acl->settings['User']['type']); + $this->assertTrue(is_object($User->Aro)); + + $Post = new AclPost(); + $this->assertTrue(isset($Post->Behaviors->Acl->settings['Post'])); + $this->assertEquals('controlled', $Post->Behaviors->Acl->settings['Post']['type']); + $this->assertTrue(is_object($Post->Aco)); + } + +/** + * Test Setup of AclBehavior as both requester and controlled + * + * @return void + */ + public function testSetupMulti() { + $User = new AclPerson(); + $this->assertTrue(isset($User->Behaviors->Acl->settings['AclPerson'])); + $this->assertEquals('both', $User->Behaviors->Acl->settings['AclPerson']['type']); + $this->assertTrue(is_object($User->Aro)); + $this->assertTrue(is_object($User->Aco)); + } + +/** + * test After Save + * + * @return void + */ + public function testAfterSave() { + $Post = new AclPost(); + $data = array( + 'Post' => array( + 'author_id' => 1, + 'title' => 'Acl Post', + 'body' => 'post body', + 'published' => 1 + ), + ); + $Post->save($data); + $result = $this->Aco->find('first', array( + 'conditions' => array('Aco.model' => 'Post', 'Aco.foreign_key' => $Post->id) + )); + $this->assertTrue(is_array($result)); + $this->assertEquals('Post', $result['Aco']['model']); + $this->assertEquals($Post->id, $result['Aco']['foreign_key']); + + $aroData = array( + 'Aro' => array( + 'model' => 'AclPerson', + 'foreign_key' => 2, + 'parent_id' => null + ) + ); + $this->Aro->save($aroData); + + $acoData = array( + 'Aco' => array( + 'model' => 'AclPerson', + 'foreign_key' => 2, + 'parent_id' => null + ) + ); + $this->Aco->save($acoData); + + $Person = new AclPerson(); + $data = array( + 'AclPerson' => array( + 'name' => 'Trent', + 'mother_id' => 2, + 'father_id' => 3, + ), + ); + $Person->save($data); + $result = $this->Aro->find('first', array( + 'conditions' => array('Aro.model' => 'AclPerson', 'Aro.foreign_key' => $Person->id) + )); + $this->assertTrue(is_array($result)); + $this->assertEquals(5, $result['Aro']['parent_id']); + + $node = $Person->node(array('model' => 'AclPerson', 'foreign_key' => 8), 'Aro'); + $this->assertEquals(2, count($node)); + $this->assertEquals(5, $node[0]['Aro']['parent_id']); + $this->assertEquals(null, $node[1]['Aro']['parent_id']); + + $aroData = array( + 'Aro' => array( + 'model' => 'AclPerson', + 'foreign_key' => 1, + 'parent_id' => null + ) + ); + $this->Aro->create(); + $this->Aro->save($aroData); + $acoData = array( + 'Aco' => array( + 'model' => 'AclPerson', + 'foreign_key' => 1, + 'parent_id' => null + )); + $this->Aco->create(); + $this->Aco->save($acoData); + $Person->read(null, 8); + $Person->set('mother_id', 1); + $Person->save(); + $result = $this->Aro->find('first', array( + 'conditions' => array('Aro.model' => 'AclPerson', 'Aro.foreign_key' => $Person->id) + )); + $this->assertTrue(is_array($result)); + $this->assertEquals(7, $result['Aro']['parent_id']); + + $node = $Person->node(array('model' => 'AclPerson', 'foreign_key' => 8), 'Aro'); + $this->assertEquals(2, count($node)); + $this->assertEquals(7, $node[0]['Aro']['parent_id']); + $this->assertEquals(null, $node[1]['Aro']['parent_id']); + } + +/** + * test that an afterSave on an update does not cause parent_id to become null. + * + * @return void + */ + public function testAfterSaveUpdateParentIdNotNull() { + $aroData = array( + 'Aro' => array( + 'model' => 'AclPerson', + 'foreign_key' => 2, + 'parent_id' => null + ) + ); + $this->Aro->save($aroData); + + $acoData = array( + 'Aco' => array( + 'model' => 'AclPerson', + 'foreign_key' => 2, + 'parent_id' => null + ) + ); + $this->Aco->save($acoData); + + $Person = new AclPerson(); + $data = array( + 'AclPerson' => array( + 'name' => 'Trent', + 'mother_id' => 2, + 'father_id' => 3, + ), + ); + $Person->save($data); + $result = $this->Aro->find('first', array( + 'conditions' => array('Aro.model' => 'AclPerson', 'Aro.foreign_key' => $Person->id) + )); + $this->assertTrue(is_array($result)); + $this->assertEquals(5, $result['Aro']['parent_id']); + + $Person->save(array('id' => $Person->id, 'name' => 'Bruce')); + $result = $this->Aro->find('first', array( + 'conditions' => array('Aro.model' => 'AclPerson', 'Aro.foreign_key' => $Person->id) + )); + $this->assertEquals(5, $result['Aro']['parent_id']); + } + +/** + * Test After Delete + * + * @return void + */ + public function testAfterDelete() { + $aroData = array( + 'Aro' => array( + 'model' => 'AclPerson', + 'foreign_key' => 2, + 'parent_id' => null + ) + ); + $this->Aro->save($aroData); + + $acoData = array( + 'Aco' => array( + 'model' => 'AclPerson', + 'foreign_key' => 2, + 'parent_id' => null + ) + ); + $this->Aco->save($acoData); + $Person = new AclPerson(); + + $data = array( + 'AclPerson' => array( + 'name' => 'Trent', + 'mother_id' => 2, + 'father_id' => 3, + ), + ); + $Person->save($data); + $id = $Person->id; + $node = $Person->node(null, 'Aro'); + $this->assertEquals(2, count($node)); + $this->assertEquals(5, $node[0]['Aro']['parent_id']); + $this->assertEquals(null, $node[1]['Aro']['parent_id']); + + $Person->delete($id); + $result = $this->Aro->find('first', array( + 'conditions' => array('Aro.model' => 'AclPerson', 'Aro.foreign_key' => $id) + )); + $this->assertTrue(empty($result)); + $result = $this->Aro->find('first', array( + 'conditions' => array('Aro.model' => 'AclPerson', 'Aro.foreign_key' => 2) + )); + $this->assertFalse(empty($result)); + + $data = array( + 'AclPerson' => array( + 'name' => 'Trent', + 'mother_id' => 2, + 'father_id' => 3, + ), + ); + $Person->save($data); + $id = $Person->id; + $Person->delete(2); + $result = $this->Aro->find('first', array( + 'conditions' => array('Aro.model' => 'AclPerson', 'Aro.foreign_key' => $id) + )); + $this->assertTrue(empty($result)); + + $result = $this->Aro->find('first', array( + 'conditions' => array('Aro.model' => 'AclPerson', 'Aro.foreign_key' => 2) + )); + $this->assertTrue(empty($result)); + } + +/** + * Test Node() + * + * @return void + */ + public function testNode() { + $Person = new AclPerson(); + $aroData = array( + 'Aro' => array( + 'model' => 'AclPerson', + 'foreign_key' => 2, + 'parent_id' => null + ) + ); + $this->Aro->save($aroData); + + $Person->id = 2; + $result = $Person->node(null, 'Aro'); + $this->assertTrue(is_array($result)); + $this->assertEquals(1, count($result)); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Behavior/ContainableBehaviorTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Behavior/ContainableBehaviorTest.php new file mode 100644 index 0000000..8345c87 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Behavior/ContainableBehaviorTest.php @@ -0,0 +1,3660 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Model.Behavior + * @since CakePHP(tm) v 1.2.0.5669 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ + +App::uses('Model', 'Model'); +App::uses('AppModel', 'Model'); +require_once dirname(dirname(__FILE__)) . DS . 'models.php'; + +/** + * ContainableTest class + * + * @package Cake.Test.Case.Model.Behavior + */ +class ContainableBehaviorTest extends CakeTestCase { + +/** + * Fixtures associated with this test case + * + * @var array + */ + public $fixtures = array( + 'core.article', 'core.article_featured', 'core.article_featureds_tags', + 'core.articles_tag', 'core.attachment', 'core.category', + 'core.comment', 'core.featured', 'core.tag', 'core.user', + 'core.join_a', 'core.join_b', 'core.join_c', 'core.join_a_c', 'core.join_a_b' + ); + +/** + * Method executed before each test + * + */ + public function setUp() { + parent::setUp(); + $this->User = ClassRegistry::init('User'); + $this->Article = ClassRegistry::init('Article'); + $this->Tag = ClassRegistry::init('Tag'); + + $this->User->bindModel(array( + 'hasMany' => array('Article', 'ArticleFeatured', 'Comment') + ), false); + $this->User->ArticleFeatured->unbindModel(array('belongsTo' => array('Category')), false); + $this->User->ArticleFeatured->hasMany['Comment']['foreignKey'] = 'article_id'; + + $this->Tag->bindModel(array( + 'hasAndBelongsToMany' => array('Article') + ), false); + + $this->User->Behaviors->attach('Containable'); + $this->Article->Behaviors->attach('Containable'); + $this->Tag->Behaviors->attach('Containable'); + } + +/** + * Method executed after each test + * + */ + public function tearDown() { + unset($this->Article); + unset($this->User); + unset($this->Tag); + parent::tearDown(); + } + +/** + * testContainments method + * + * @return void + */ + public function testContainments() { + $r = $this->_containments($this->Article, array('Comment' => array('conditions' => array('Comment.user_id' => 2)))); + $this->assertTrue(Set::matches('/Article/keep/Comment/conditions[Comment.user_id=2]', $r)); + + $r = $this->_containments($this->User, array( + 'ArticleFeatured' => array( + 'Featured' => array( + 'id', + 'Category' => 'name' + ) + ))); + $this->assertEquals(array('id'), Hash::extract($r, 'ArticleFeatured.keep.Featured.fields')); + + $r = $this->_containments($this->Article, array( + 'Comment' => array( + 'User', + 'conditions' => array('Comment' => array('user_id' => 2)), + ), + )); + $this->assertTrue(Set::matches('/User', $r)); + $this->assertTrue(Set::matches('/Comment', $r)); + $this->assertTrue(Set::matches('/Article/keep/Comment/conditions/Comment[user_id=2]', $r)); + + $r = $this->_containments($this->Article, array('Comment(comment, published)' => 'Attachment(attachment)', 'User(user)')); + $this->assertTrue(Set::matches('/Comment', $r)); + $this->assertTrue(Set::matches('/User', $r)); + $this->assertTrue(Set::matches('/Article/keep/Comment', $r)); + $this->assertTrue(Set::matches('/Article/keep/User', $r)); + $this->assertEquals(array('comment', 'published'), Hash::extract($r, 'Article.keep.Comment.fields')); + $this->assertEquals(array('user'), Hash::extract($r, 'Article.keep.User.fields')); + $this->assertTrue(Set::matches('/Comment/keep/Attachment', $r)); + $this->assertEquals(array('attachment'), Hash::extract($r, 'Comment.keep.Attachment.fields')); + + $r = $this->_containments($this->Article, array('Comment' => array('limit' => 1))); + $this->assertEquals(array('Comment', 'Article'), array_keys($r)); + $result = Hash::extract($r, 'Comment[keep]'); + $this->assertEquals(array('keep' => array()), array_shift($result)); + $this->assertTrue(Set::matches('/Article/keep/Comment', $r)); + $result = Hash::extract($r, 'Article.keep'); + $this->assertEquals(array('limit' => 1), array_shift($result)); + + $r = $this->_containments($this->Article, array('Comment.User')); + $this->assertEquals(array('User', 'Comment', 'Article'), array_keys($r)); + + $result = Hash::extract($r, 'User[keep]'); + $this->assertEquals(array('keep' => array()), array_shift($result)); + + $result = Hash::extract($r, 'Comment[keep]'); + $this->assertEquals(array('keep' => array('User' => array())), array_shift($result)); + + $result = Hash::extract($r, 'Article[keep]'); + $this->assertEquals(array('keep' => array('Comment' => array())), array_shift($result)); + + $r = $this->_containments($this->Tag, array('Article' => array('User' => array('Comment' => array( + 'Attachment' => array('conditions' => array('Attachment.id >' => 1)) + ))))); + $this->assertTrue(Set::matches('/Attachment', $r)); + $this->assertTrue(Set::matches('/Comment/keep/Attachment/conditions', $r)); + $this->assertEquals(array('Attachment.id >' => 1), $r['Comment']['keep']['Attachment']['conditions']); + $this->assertTrue(Set::matches('/User/keep/Comment', $r)); + $this->assertTrue(Set::matches('/Article/keep/User', $r)); + $this->assertTrue(Set::matches('/Tag/keep/Article', $r)); + } + +/** + * testInvalidContainments method + * + * @expectedException PHPUnit_Framework_Error + * @return void + */ + public function testInvalidContainments() { + $r = $this->_containments($this->Article, array('Comment', 'InvalidBinding')); + } + +/** + * testInvalidContainments method with suppressing error notices + * + * @return void + */ + public function testInvalidContainmentsNoNotices() { + $this->Article->Behaviors->attach('Containable', array('notices' => false)); + $r = $this->_containments($this->Article, array('Comment', 'InvalidBinding')); + } + +/** + * testBeforeFind method + * + * @return void + */ + public function testBeforeFind() { + $r = $this->Article->find('all', array('contain' => array('Comment'))); + $this->assertFalse(Set::matches('/User', $r)); + $this->assertTrue(Set::matches('/Comment', $r)); + $this->assertFalse(Set::matches('/Comment/User', $r)); + + $r = $this->Article->find('all', array('contain' => 'Comment.User')); + $this->assertTrue(Set::matches('/Comment/User', $r)); + $this->assertFalse(Set::matches('/Comment/Article', $r)); + + $r = $this->Article->find('all', array('contain' => array('Comment' => array('User', 'Article')))); + $this->assertTrue(Set::matches('/Comment/User', $r)); + $this->assertTrue(Set::matches('/Comment/Article', $r)); + + $r = $this->Article->find('all', array('contain' => array('Comment' => array('conditions' => array('Comment.user_id' => 2))))); + $this->assertFalse(Set::matches('/Comment[user_id!=2]', $r)); + $this->assertTrue(Set::matches('/Comment[user_id=2]', $r)); + + $r = $this->Article->find('all', array('contain' => array('Comment.user_id = 2'))); + $this->assertFalse(Set::matches('/Comment[user_id!=2]', $r)); + + $r = $this->Article->find('all', array('contain' => 'Comment.id DESC')); + $ids = $descIds = Hash::extract($r, 'Comment[1].id'); + rsort($descIds); + $this->assertEquals($ids, $descIds); + + $r = $this->Article->find('all', array('contain' => 'Comment')); + $this->assertTrue(Set::matches('/Comment[user_id!=2]', $r)); + + $r = $this->Article->find('all', array('contain' => array('Comment' => array('fields' => 'comment')))); + $this->assertFalse(Set::matches('/Comment/created', $r)); + $this->assertTrue(Set::matches('/Comment/comment', $r)); + $this->assertFalse(Set::matches('/Comment/updated', $r)); + + $r = $this->Article->find('all', array('contain' => array('Comment' => array('fields' => array('comment', 'updated'))))); + $this->assertFalse(Set::matches('/Comment/created', $r)); + $this->assertTrue(Set::matches('/Comment/comment', $r)); + $this->assertTrue(Set::matches('/Comment/updated', $r)); + + $r = $this->Article->find('all', array('contain' => array('Comment' => array('comment', 'updated')))); + $this->assertFalse(Set::matches('/Comment/created', $r)); + $this->assertTrue(Set::matches('/Comment/comment', $r)); + $this->assertTrue(Set::matches('/Comment/updated', $r)); + + $r = $this->Article->find('all', array('contain' => array('Comment(comment,updated)'))); + $this->assertFalse(Set::matches('/Comment/created', $r)); + $this->assertTrue(Set::matches('/Comment/comment', $r)); + $this->assertTrue(Set::matches('/Comment/updated', $r)); + + $r = $this->Article->find('all', array('contain' => 'Comment.created')); + $this->assertTrue(Set::matches('/Comment/created', $r)); + $this->assertFalse(Set::matches('/Comment/comment', $r)); + + $r = $this->Article->find('all', array('contain' => array('User.Article(title)', 'Comment(comment)'))); + $this->assertFalse(Set::matches('/Comment/Article', $r)); + $this->assertFalse(Set::matches('/Comment/User', $r)); + $this->assertTrue(Set::matches('/Comment/comment', $r)); + $this->assertFalse(Set::matches('/Comment/created', $r)); + $this->assertTrue(Set::matches('/User/Article/title', $r)); + $this->assertFalse(Set::matches('/User/Article/created', $r)); + + $r = $this->Article->find('all', array('contain' => array())); + $this->assertFalse(Set::matches('/User', $r)); + $this->assertFalse(Set::matches('/Comment', $r)); + } + +/** + * testBeforeFindWithNonExistingBinding method + * + * @expectedException PHPUnit_Framework_Error + * @return void + */ + public function testBeforeFindWithNonExistingBinding() { + $r = $this->Article->find('all', array('contain' => array('Comment' => 'NonExistingBinding'))); + } + +/** + * testContain method + * + * @return void + */ + public function testContain() { + $this->Article->contain('Comment.User'); + $r = $this->Article->find('all'); + $this->assertTrue(Set::matches('/Comment/User', $r)); + $this->assertFalse(Set::matches('/Comment/Article', $r)); + + $r = $this->Article->find('all'); + $this->assertFalse(Set::matches('/Comment/User', $r)); + } + +/** + * testFindEmbeddedNoBindings method + * + * @return void + */ + public function testFindEmbeddedNoBindings() { + $result = $this->Article->find('all', array('contain' => false)); + $expected = array( + array('Article' => array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + )), + array('Article' => array( + 'id' => 2, 'user_id' => 3, 'title' => 'Second Article', 'body' => 'Second Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:41:23', 'updated' => '2007-03-18 10:43:31' + )), + array('Article' => array( + 'id' => 3, 'user_id' => 1, 'title' => 'Third Article', 'body' => 'Third Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:43:23', 'updated' => '2007-03-18 10:45:31' + )) + ); + $this->assertEquals($expected, $result); + } + +/** + * testFindFirstLevel method + * + * @return void + */ + public function testFindFirstLevel() { + $this->Article->contain('User'); + $result = $this->Article->find('all', array('recursive' => 1)); + $expected = array( + array( + 'Article' => array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ), + 'User' => array( + 'id' => 1, 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31' + ) + ), + array( + 'Article' => array( + 'id' => 2, 'user_id' => 3, 'title' => 'Second Article', 'body' => 'Second Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:41:23', 'updated' => '2007-03-18 10:43:31' + ), + 'User' => array( + 'id' => 3, 'user' => 'larry', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:20:23', 'updated' => '2007-03-17 01:22:31' + ) + ), + array( + 'Article' => array( + 'id' => 3, 'user_id' => 1, 'title' => 'Third Article', 'body' => 'Third Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:43:23', 'updated' => '2007-03-18 10:45:31' + ), + 'User' => array( + 'id' => 1, 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31' + ) + ) + ); + $this->assertEquals($expected, $result); + + $this->Article->contain('User', 'Comment'); + $result = $this->Article->find('all', array('recursive' => 1)); + $expected = array( + array( + 'Article' => array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ), + 'User' => array( + 'id' => 1, 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31' + ), + 'Comment' => array( + array( + 'id' => 1, 'article_id' => 1, 'user_id' => 2, 'comment' => 'First Comment for First Article', + 'published' => 'Y', 'created' => '2007-03-18 10:45:23', 'updated' => '2007-03-18 10:47:31' + ), + array( + 'id' => 2, 'article_id' => 1, 'user_id' => 4, 'comment' => 'Second Comment for First Article', + 'published' => 'Y', 'created' => '2007-03-18 10:47:23', 'updated' => '2007-03-18 10:49:31' + ), + array( + 'id' => 3, 'article_id' => 1, 'user_id' => 1, 'comment' => 'Third Comment for First Article', + 'published' => 'Y', 'created' => '2007-03-18 10:49:23', 'updated' => '2007-03-18 10:51:31' + ), + array( + 'id' => 4, 'article_id' => 1, 'user_id' => 1, 'comment' => 'Fourth Comment for First Article', + 'published' => 'N', 'created' => '2007-03-18 10:51:23', 'updated' => '2007-03-18 10:53:31' + ) + ) + ), + array( + 'Article' => array( + 'id' => 2, 'user_id' => 3, 'title' => 'Second Article', 'body' => 'Second Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:41:23', 'updated' => '2007-03-18 10:43:31' + ), + 'User' => array( + 'id' => 3, 'user' => 'larry', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:20:23', 'updated' => '2007-03-17 01:22:31' + ), + 'Comment' => array( + array( + 'id' => 5, 'article_id' => 2, 'user_id' => 1, 'comment' => 'First Comment for Second Article', + 'published' => 'Y', 'created' => '2007-03-18 10:53:23', 'updated' => '2007-03-18 10:55:31' + ), + array( + 'id' => 6, 'article_id' => 2, 'user_id' => 2, 'comment' => 'Second Comment for Second Article', + 'published' => 'Y', 'created' => '2007-03-18 10:55:23', 'updated' => '2007-03-18 10:57:31' + ) + ) + ), + array( + 'Article' => array( + 'id' => 3, 'user_id' => 1, 'title' => 'Third Article', 'body' => 'Third Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:43:23', 'updated' => '2007-03-18 10:45:31' + ), + 'User' => array( + 'id' => 1, 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31' + ), + 'Comment' => array() + ) + ); + $this->assertEquals($expected, $result); + } + +/** + * testFindEmbeddedFirstLevel method + * + * @return void + */ + public function testFindEmbeddedFirstLevel() { + $result = $this->Article->find('all', array('contain' => array('User'))); + $expected = array( + array( + 'Article' => array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ), + 'User' => array( + 'id' => 1, 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31' + ) + ), + array( + 'Article' => array( + 'id' => 2, 'user_id' => 3, 'title' => 'Second Article', 'body' => 'Second Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:41:23', 'updated' => '2007-03-18 10:43:31' + ), + 'User' => array( + 'id' => 3, 'user' => 'larry', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:20:23', 'updated' => '2007-03-17 01:22:31' + ) + ), + array( + 'Article' => array( + 'id' => 3, 'user_id' => 1, 'title' => 'Third Article', 'body' => 'Third Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:43:23', 'updated' => '2007-03-18 10:45:31' + ), + 'User' => array( + 'id' => 1, 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31' + ) + ) + ); + $this->assertEquals($expected, $result); + + $result = $this->Article->find('all', array('contain' => array('User', 'Comment'))); + $expected = array( + array( + 'Article' => array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ), + 'User' => array( + 'id' => 1, 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31' + ), + 'Comment' => array( + array( + 'id' => 1, 'article_id' => 1, 'user_id' => 2, 'comment' => 'First Comment for First Article', + 'published' => 'Y', 'created' => '2007-03-18 10:45:23', 'updated' => '2007-03-18 10:47:31' + ), + array( + 'id' => 2, 'article_id' => 1, 'user_id' => 4, 'comment' => 'Second Comment for First Article', + 'published' => 'Y', 'created' => '2007-03-18 10:47:23', 'updated' => '2007-03-18 10:49:31' + ), + array( + 'id' => 3, 'article_id' => 1, 'user_id' => 1, 'comment' => 'Third Comment for First Article', + 'published' => 'Y', 'created' => '2007-03-18 10:49:23', 'updated' => '2007-03-18 10:51:31' + ), + array( + 'id' => 4, 'article_id' => 1, 'user_id' => 1, 'comment' => 'Fourth Comment for First Article', + 'published' => 'N', 'created' => '2007-03-18 10:51:23', 'updated' => '2007-03-18 10:53:31' + ) + ) + ), + array( + 'Article' => array( + 'id' => 2, 'user_id' => 3, 'title' => 'Second Article', 'body' => 'Second Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:41:23', 'updated' => '2007-03-18 10:43:31' + ), + 'User' => array( + 'id' => 3, 'user' => 'larry', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:20:23', 'updated' => '2007-03-17 01:22:31' + ), + 'Comment' => array( + array( + 'id' => 5, 'article_id' => 2, 'user_id' => 1, 'comment' => 'First Comment for Second Article', + 'published' => 'Y', 'created' => '2007-03-18 10:53:23', 'updated' => '2007-03-18 10:55:31' + ), + array( + 'id' => 6, 'article_id' => 2, 'user_id' => 2, 'comment' => 'Second Comment for Second Article', + 'published' => 'Y', 'created' => '2007-03-18 10:55:23', 'updated' => '2007-03-18 10:57:31' + ) + ) + ), + array( + 'Article' => array( + 'id' => 3, 'user_id' => 1, 'title' => 'Third Article', 'body' => 'Third Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:43:23', 'updated' => '2007-03-18 10:45:31' + ), + 'User' => array( + 'id' => 1, 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31' + ), + 'Comment' => array() + ) + ); + $this->assertEquals($expected, $result); + } + +/** + * testFindSecondLevel method + * + * @return void + */ + public function testFindSecondLevel() { + $this->Article->contain(array('Comment' => 'User')); + $result = $this->Article->find('all', array('recursive' => 2)); + $expected = array( + array( + 'Article' => array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ), + 'Comment' => array( + array( + 'id' => 1, 'article_id' => 1, 'user_id' => 2, 'comment' => 'First Comment for First Article', + 'published' => 'Y', 'created' => '2007-03-18 10:45:23', 'updated' => '2007-03-18 10:47:31', + 'User' => array( + 'id' => 2, 'user' => 'nate', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:18:23', 'updated' => '2007-03-17 01:20:31' + ) + ), + array( + 'id' => 2, 'article_id' => 1, 'user_id' => 4, 'comment' => 'Second Comment for First Article', + 'published' => 'Y', 'created' => '2007-03-18 10:47:23', 'updated' => '2007-03-18 10:49:31', + 'User' => array( + 'id' => 4, 'user' => 'garrett', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:22:23', 'updated' => '2007-03-17 01:24:31' + ) + ), + array( + 'id' => 3, 'article_id' => 1, 'user_id' => 1, 'comment' => 'Third Comment for First Article', + 'published' => 'Y', 'created' => '2007-03-18 10:49:23', 'updated' => '2007-03-18 10:51:31', + 'User' => array( + 'id' => 1, 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31' + ) + ), + array( + 'id' => 4, 'article_id' => 1, 'user_id' => 1, 'comment' => 'Fourth Comment for First Article', + 'published' => 'N', 'created' => '2007-03-18 10:51:23', 'updated' => '2007-03-18 10:53:31', + 'User' => array( + 'id' => 1, 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31' + ) + ) + ) + ), + array( + 'Article' => array( + 'id' => 2, 'user_id' => 3, 'title' => 'Second Article', 'body' => 'Second Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:41:23', 'updated' => '2007-03-18 10:43:31' + ), + 'Comment' => array( + array( + 'id' => 5, 'article_id' => 2, 'user_id' => 1, 'comment' => 'First Comment for Second Article', + 'published' => 'Y', 'created' => '2007-03-18 10:53:23', 'updated' => '2007-03-18 10:55:31', + 'User' => array( + 'id' => 1, 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31' + ) + ), + array( + 'id' => 6, 'article_id' => 2, 'user_id' => 2, 'comment' => 'Second Comment for Second Article', + 'published' => 'Y', 'created' => '2007-03-18 10:55:23', 'updated' => '2007-03-18 10:57:31', + 'User' => array( + 'id' => 2, 'user' => 'nate', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:18:23', 'updated' => '2007-03-17 01:20:31' + ) + ) + ) + ), + array( + 'Article' => array( + 'id' => 3, 'user_id' => 1, 'title' => 'Third Article', 'body' => 'Third Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:43:23', 'updated' => '2007-03-18 10:45:31' + ), + 'Comment' => array() + ) + ); + $this->assertEquals($expected, $result); + + $this->Article->contain(array('User' => 'ArticleFeatured')); + $result = $this->Article->find('all', array('recursive' => 2)); + $expected = array( + array( + 'Article' => array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ), + 'User' => array( + 'id' => 1, 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31', + 'ArticleFeatured' => array( + array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ), + array( + 'id' => 3, 'user_id' => 1, 'title' => 'Third Article', 'body' => 'Third Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:43:23', 'updated' => '2007-03-18 10:45:31' + ) + ) + ) + ), + array( + 'Article' => array( + 'id' => 2, 'user_id' => 3, 'title' => 'Second Article', 'body' => 'Second Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:41:23', 'updated' => '2007-03-18 10:43:31' + ), + 'User' => array( + 'id' => 3, 'user' => 'larry', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:20:23', 'updated' => '2007-03-17 01:22:31', + 'ArticleFeatured' => array( + array( + 'id' => 2, 'user_id' => 3, 'title' => 'Second Article', 'body' => 'Second Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:41:23', 'updated' => '2007-03-18 10:43:31' + ) + ) + ) + ), + array( + 'Article' => array( + 'id' => 3, 'user_id' => 1, 'title' => 'Third Article', 'body' => 'Third Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:43:23', 'updated' => '2007-03-18 10:45:31' + ), + 'User' => array( + 'id' => 1, 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31', + 'ArticleFeatured' => array( + array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ), + array( + 'id' => 3, 'user_id' => 1, 'title' => 'Third Article', 'body' => 'Third Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:43:23', 'updated' => '2007-03-18 10:45:31' + ) + ) + ) + ) + ); + $this->assertEquals($expected, $result); + + $this->Article->contain(array('User' => array('ArticleFeatured', 'Comment'))); + $result = $this->Article->find('all', array('recursive' => 2)); + $expected = array( + array( + 'Article' => array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ), + 'User' => array( + 'id' => 1, 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31', + 'ArticleFeatured' => array( + array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ), + array( + 'id' => 3, 'user_id' => 1, 'title' => 'Third Article', 'body' => 'Third Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:43:23', 'updated' => '2007-03-18 10:45:31' + ) + ), + 'Comment' => array( + array( + 'id' => 3, 'article_id' => 1, 'user_id' => 1, 'comment' => 'Third Comment for First Article', + 'published' => 'Y', 'created' => '2007-03-18 10:49:23', 'updated' => '2007-03-18 10:51:31' + ), + array( + 'id' => 4, 'article_id' => 1, 'user_id' => 1, 'comment' => 'Fourth Comment for First Article', + 'published' => 'N', 'created' => '2007-03-18 10:51:23', 'updated' => '2007-03-18 10:53:31' + ), + array( + 'id' => 5, 'article_id' => 2, 'user_id' => 1, 'comment' => 'First Comment for Second Article', + 'published' => 'Y', 'created' => '2007-03-18 10:53:23', 'updated' => '2007-03-18 10:55:31' + ) + ) + ) + ), + array( + 'Article' => array( + 'id' => 2, 'user_id' => 3, 'title' => 'Second Article', 'body' => 'Second Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:41:23', 'updated' => '2007-03-18 10:43:31' + ), + 'User' => array( + 'id' => 3, 'user' => 'larry', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:20:23', 'updated' => '2007-03-17 01:22:31', + 'ArticleFeatured' => array( + array( + 'id' => 2, 'user_id' => 3, 'title' => 'Second Article', 'body' => 'Second Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:41:23', 'updated' => '2007-03-18 10:43:31' + ) + ), + 'Comment' => array() + ) + ), + array( + 'Article' => array( + 'id' => 3, 'user_id' => 1, 'title' => 'Third Article', 'body' => 'Third Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:43:23', 'updated' => '2007-03-18 10:45:31' + ), + 'User' => array( + 'id' => 1, 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31', + 'ArticleFeatured' => array( + array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ), + array( + 'id' => 3, 'user_id' => 1, 'title' => 'Third Article', 'body' => 'Third Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:43:23', 'updated' => '2007-03-18 10:45:31' + ) + ), + 'Comment' => array( + array( + 'id' => 3, 'article_id' => 1, 'user_id' => 1, 'comment' => 'Third Comment for First Article', + 'published' => 'Y', 'created' => '2007-03-18 10:49:23', 'updated' => '2007-03-18 10:51:31' + ), + array( + 'id' => 4, 'article_id' => 1, 'user_id' => 1, 'comment' => 'Fourth Comment for First Article', + 'published' => 'N', 'created' => '2007-03-18 10:51:23', 'updated' => '2007-03-18 10:53:31' + ), + array( + 'id' => 5, 'article_id' => 2, 'user_id' => 1, 'comment' => 'First Comment for Second Article', + 'published' => 'Y', 'created' => '2007-03-18 10:53:23', 'updated' => '2007-03-18 10:55:31' + ) + ) + ) + ) + ); + $this->assertEquals($expected, $result); + + $this->Article->contain(array('User' => array('ArticleFeatured')), 'Tag', array('Comment' => 'Attachment')); + $result = $this->Article->find('all', array('recursive' => 2)); + $expected = array( + array( + 'Article' => array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ), + 'User' => array( + 'id' => 1, 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31', + 'ArticleFeatured' => array( + array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ), + array( + 'id' => 3, 'user_id' => 1, 'title' => 'Third Article', 'body' => 'Third Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:43:23', 'updated' => '2007-03-18 10:45:31' + ) + ) + ), + 'Comment' => array( + array( + 'id' => 1, 'article_id' => 1, 'user_id' => 2, 'comment' => 'First Comment for First Article', + 'published' => 'Y', 'created' => '2007-03-18 10:45:23', 'updated' => '2007-03-18 10:47:31', + 'Attachment' => array() + ), + array( + 'id' => 2, 'article_id' => 1, 'user_id' => 4, 'comment' => 'Second Comment for First Article', + 'published' => 'Y', 'created' => '2007-03-18 10:47:23', 'updated' => '2007-03-18 10:49:31', + 'Attachment' => array() + ), + array( + 'id' => 3, 'article_id' => 1, 'user_id' => 1, 'comment' => 'Third Comment for First Article', + 'published' => 'Y', 'created' => '2007-03-18 10:49:23', 'updated' => '2007-03-18 10:51:31', + 'Attachment' => array() + ), + array( + 'id' => 4, 'article_id' => 1, 'user_id' => 1, 'comment' => 'Fourth Comment for First Article', + 'published' => 'N', 'created' => '2007-03-18 10:51:23', 'updated' => '2007-03-18 10:53:31', + 'Attachment' => array() + ) + ), + 'Tag' => array( + array('id' => 1, 'tag' => 'tag1', 'created' => '2007-03-18 12:22:23', 'updated' => '2007-03-18 12:24:31'), + array('id' => 2, 'tag' => 'tag2', 'created' => '2007-03-18 12:24:23', 'updated' => '2007-03-18 12:26:31') + ) + ), + array( + 'Article' => array( + 'id' => 2, 'user_id' => 3, 'title' => 'Second Article', 'body' => 'Second Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:41:23', 'updated' => '2007-03-18 10:43:31' + ), + 'User' => array( + 'id' => 3, 'user' => 'larry', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:20:23', 'updated' => '2007-03-17 01:22:31', + 'ArticleFeatured' => array( + array( + 'id' => 2, 'user_id' => 3, 'title' => 'Second Article', 'body' => 'Second Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:41:23', 'updated' => '2007-03-18 10:43:31' + ) + ) + ), + 'Comment' => array( + array( + 'id' => 5, 'article_id' => 2, 'user_id' => 1, 'comment' => 'First Comment for Second Article', + 'published' => 'Y', 'created' => '2007-03-18 10:53:23', 'updated' => '2007-03-18 10:55:31', + 'Attachment' => array( + 'id' => 1, 'comment_id' => 5, 'attachment' => 'attachment.zip', + 'created' => '2007-03-18 10:51:23', 'updated' => '2007-03-18 10:53:31' + ) + ), + array( + 'id' => 6, 'article_id' => 2, 'user_id' => 2, 'comment' => 'Second Comment for Second Article', + 'published' => 'Y', 'created' => '2007-03-18 10:55:23', 'updated' => '2007-03-18 10:57:31', + 'Attachment' => array() + ) + ), + 'Tag' => array( + array('id' => 1, 'tag' => 'tag1', 'created' => '2007-03-18 12:22:23', 'updated' => '2007-03-18 12:24:31'), + array('id' => 3, 'tag' => 'tag3', 'created' => '2007-03-18 12:26:23', 'updated' => '2007-03-18 12:28:31') + ) + ), + array( + 'Article' => array( + 'id' => 3, 'user_id' => 1, 'title' => 'Third Article', 'body' => 'Third Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:43:23', 'updated' => '2007-03-18 10:45:31' + ), + 'User' => array( + 'id' => 1, 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31', + 'ArticleFeatured' => array( + array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ), + array( + 'id' => 3, 'user_id' => 1, 'title' => 'Third Article', 'body' => 'Third Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:43:23', 'updated' => '2007-03-18 10:45:31' + ) + ) + ), + 'Comment' => array(), + 'Tag' => array() + ) + ); + $this->assertEquals($expected, $result); + } + +/** + * testFindEmbeddedSecondLevel method + * + * @return void + */ + public function testFindEmbeddedSecondLevel() { + $result = $this->Article->find('all', array('contain' => array('Comment' => 'User'))); + $expected = array( + array( + 'Article' => array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ), + 'Comment' => array( + array( + 'id' => 1, 'article_id' => 1, 'user_id' => 2, 'comment' => 'First Comment for First Article', + 'published' => 'Y', 'created' => '2007-03-18 10:45:23', 'updated' => '2007-03-18 10:47:31', + 'User' => array( + 'id' => 2, 'user' => 'nate', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:18:23', 'updated' => '2007-03-17 01:20:31' + ) + ), + array( + 'id' => 2, 'article_id' => 1, 'user_id' => 4, 'comment' => 'Second Comment for First Article', + 'published' => 'Y', 'created' => '2007-03-18 10:47:23', 'updated' => '2007-03-18 10:49:31', + 'User' => array( + 'id' => 4, 'user' => 'garrett', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:22:23', 'updated' => '2007-03-17 01:24:31' + ) + ), + array( + 'id' => 3, 'article_id' => 1, 'user_id' => 1, 'comment' => 'Third Comment for First Article', + 'published' => 'Y', 'created' => '2007-03-18 10:49:23', 'updated' => '2007-03-18 10:51:31', + 'User' => array( + 'id' => 1, 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31' + ) + ), + array( + 'id' => 4, 'article_id' => 1, 'user_id' => 1, 'comment' => 'Fourth Comment for First Article', + 'published' => 'N', 'created' => '2007-03-18 10:51:23', 'updated' => '2007-03-18 10:53:31', + 'User' => array( + 'id' => 1, 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31' + ) + ) + ) + ), + array( + 'Article' => array( + 'id' => 2, 'user_id' => 3, 'title' => 'Second Article', 'body' => 'Second Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:41:23', 'updated' => '2007-03-18 10:43:31' + ), + 'Comment' => array( + array( + 'id' => 5, 'article_id' => 2, 'user_id' => 1, 'comment' => 'First Comment for Second Article', + 'published' => 'Y', 'created' => '2007-03-18 10:53:23', 'updated' => '2007-03-18 10:55:31', + 'User' => array( + 'id' => 1, 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31' + ) + ), + array( + 'id' => 6, 'article_id' => 2, 'user_id' => 2, 'comment' => 'Second Comment for Second Article', + 'published' => 'Y', 'created' => '2007-03-18 10:55:23', 'updated' => '2007-03-18 10:57:31', + 'User' => array( + 'id' => 2, 'user' => 'nate', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:18:23', 'updated' => '2007-03-17 01:20:31' + ) + ) + ) + ), + array( + 'Article' => array( + 'id' => 3, 'user_id' => 1, 'title' => 'Third Article', 'body' => 'Third Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:43:23', 'updated' => '2007-03-18 10:45:31' + ), + 'Comment' => array() + ) + ); + $this->assertEquals($expected, $result); + + $result = $this->Article->find('all', array('contain' => array('User' => 'ArticleFeatured'))); + $expected = array( + array( + 'Article' => array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ), + 'User' => array( + 'id' => 1, 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31', + 'ArticleFeatured' => array( + array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ), + array( + 'id' => 3, 'user_id' => 1, 'title' => 'Third Article', 'body' => 'Third Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:43:23', 'updated' => '2007-03-18 10:45:31' + ) + ) + ) + ), + array( + 'Article' => array( + 'id' => 2, 'user_id' => 3, 'title' => 'Second Article', 'body' => 'Second Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:41:23', 'updated' => '2007-03-18 10:43:31' + ), + 'User' => array( + 'id' => 3, 'user' => 'larry', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:20:23', 'updated' => '2007-03-17 01:22:31', + 'ArticleFeatured' => array( + array( + 'id' => 2, 'user_id' => 3, 'title' => 'Second Article', 'body' => 'Second Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:41:23', 'updated' => '2007-03-18 10:43:31' + ) + ) + ) + ), + array( + 'Article' => array( + 'id' => 3, 'user_id' => 1, 'title' => 'Third Article', 'body' => 'Third Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:43:23', 'updated' => '2007-03-18 10:45:31' + ), + 'User' => array( + 'id' => 1, 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31', + 'ArticleFeatured' => array( + array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ), + array( + 'id' => 3, 'user_id' => 1, 'title' => 'Third Article', 'body' => 'Third Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:43:23', 'updated' => '2007-03-18 10:45:31' + ) + ) + ) + ) + ); + $this->assertEquals($expected, $result); + + $result = $this->Article->find('all', array('contain' => array('User' => array('ArticleFeatured', 'Comment')))); + $expected = array( + array( + 'Article' => array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ), + 'User' => array( + 'id' => 1, 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31', + 'ArticleFeatured' => array( + array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ), + array( + 'id' => 3, 'user_id' => 1, 'title' => 'Third Article', 'body' => 'Third Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:43:23', 'updated' => '2007-03-18 10:45:31' + ) + ), + 'Comment' => array( + array( + 'id' => 3, 'article_id' => 1, 'user_id' => 1, 'comment' => 'Third Comment for First Article', + 'published' => 'Y', 'created' => '2007-03-18 10:49:23', 'updated' => '2007-03-18 10:51:31' + ), + array( + 'id' => 4, 'article_id' => 1, 'user_id' => 1, 'comment' => 'Fourth Comment for First Article', + 'published' => 'N', 'created' => '2007-03-18 10:51:23', 'updated' => '2007-03-18 10:53:31' + ), + array( + 'id' => 5, 'article_id' => 2, 'user_id' => 1, 'comment' => 'First Comment for Second Article', + 'published' => 'Y', 'created' => '2007-03-18 10:53:23', 'updated' => '2007-03-18 10:55:31' + ) + ) + ) + ), + array( + 'Article' => array( + 'id' => 2, 'user_id' => 3, 'title' => 'Second Article', 'body' => 'Second Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:41:23', 'updated' => '2007-03-18 10:43:31' + ), + 'User' => array( + 'id' => 3, 'user' => 'larry', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:20:23', 'updated' => '2007-03-17 01:22:31', + 'ArticleFeatured' => array( + array( + 'id' => 2, 'user_id' => 3, 'title' => 'Second Article', 'body' => 'Second Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:41:23', 'updated' => '2007-03-18 10:43:31' + ) + ), + 'Comment' => array() + ) + ), + array( + 'Article' => array( + 'id' => 3, 'user_id' => 1, 'title' => 'Third Article', 'body' => 'Third Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:43:23', 'updated' => '2007-03-18 10:45:31' + ), + 'User' => array( + 'id' => 1, 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31', + 'ArticleFeatured' => array( + array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ), + array( + 'id' => 3, 'user_id' => 1, 'title' => 'Third Article', 'body' => 'Third Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:43:23', 'updated' => '2007-03-18 10:45:31' + ) + ), + 'Comment' => array( + array( + 'id' => 3, 'article_id' => 1, 'user_id' => 1, 'comment' => 'Third Comment for First Article', + 'published' => 'Y', 'created' => '2007-03-18 10:49:23', 'updated' => '2007-03-18 10:51:31' + ), + array( + 'id' => 4, 'article_id' => 1, 'user_id' => 1, 'comment' => 'Fourth Comment for First Article', + 'published' => 'N', 'created' => '2007-03-18 10:51:23', 'updated' => '2007-03-18 10:53:31' + ), + array( + 'id' => 5, 'article_id' => 2, 'user_id' => 1, 'comment' => 'First Comment for Second Article', + 'published' => 'Y', 'created' => '2007-03-18 10:53:23', 'updated' => '2007-03-18 10:55:31' + ) + ) + ) + ) + ); + $this->assertEquals($expected, $result); + + $result = $this->Article->find('all', array('contain' => array('User' => 'ArticleFeatured', 'Tag', 'Comment' => 'Attachment'))); + $expected = array( + array( + 'Article' => array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ), + 'User' => array( + 'id' => 1, 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31', + 'ArticleFeatured' => array( + array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ), + array( + 'id' => 3, 'user_id' => 1, 'title' => 'Third Article', 'body' => 'Third Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:43:23', 'updated' => '2007-03-18 10:45:31' + ) + ) + ), + 'Comment' => array( + array( + 'id' => 1, 'article_id' => 1, 'user_id' => 2, 'comment' => 'First Comment for First Article', + 'published' => 'Y', 'created' => '2007-03-18 10:45:23', 'updated' => '2007-03-18 10:47:31', + 'Attachment' => array() + ), + array( + 'id' => 2, 'article_id' => 1, 'user_id' => 4, 'comment' => 'Second Comment for First Article', + 'published' => 'Y', 'created' => '2007-03-18 10:47:23', 'updated' => '2007-03-18 10:49:31', + 'Attachment' => array() + ), + array( + 'id' => 3, 'article_id' => 1, 'user_id' => 1, 'comment' => 'Third Comment for First Article', + 'published' => 'Y', 'created' => '2007-03-18 10:49:23', 'updated' => '2007-03-18 10:51:31', + 'Attachment' => array() + ), + array( + 'id' => 4, 'article_id' => 1, 'user_id' => 1, 'comment' => 'Fourth Comment for First Article', + 'published' => 'N', 'created' => '2007-03-18 10:51:23', 'updated' => '2007-03-18 10:53:31', + 'Attachment' => array() + ) + ), + 'Tag' => array( + array('id' => 1, 'tag' => 'tag1', 'created' => '2007-03-18 12:22:23', 'updated' => '2007-03-18 12:24:31'), + array('id' => 2, 'tag' => 'tag2', 'created' => '2007-03-18 12:24:23', 'updated' => '2007-03-18 12:26:31') + ) + ), + array( + 'Article' => array( + 'id' => 2, 'user_id' => 3, 'title' => 'Second Article', 'body' => 'Second Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:41:23', 'updated' => '2007-03-18 10:43:31' + ), + 'User' => array( + 'id' => 3, 'user' => 'larry', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:20:23', 'updated' => '2007-03-17 01:22:31', + 'ArticleFeatured' => array( + array( + 'id' => 2, 'user_id' => 3, 'title' => 'Second Article', 'body' => 'Second Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:41:23', 'updated' => '2007-03-18 10:43:31' + ) + ) + ), + 'Comment' => array( + array( + 'id' => 5, 'article_id' => 2, 'user_id' => 1, 'comment' => 'First Comment for Second Article', + 'published' => 'Y', 'created' => '2007-03-18 10:53:23', 'updated' => '2007-03-18 10:55:31', + 'Attachment' => array( + 'id' => 1, 'comment_id' => 5, 'attachment' => 'attachment.zip', + 'created' => '2007-03-18 10:51:23', 'updated' => '2007-03-18 10:53:31' + ) + ), + array( + 'id' => 6, 'article_id' => 2, 'user_id' => 2, 'comment' => 'Second Comment for Second Article', + 'published' => 'Y', 'created' => '2007-03-18 10:55:23', 'updated' => '2007-03-18 10:57:31', + 'Attachment' => array() + ) + ), + 'Tag' => array( + array('id' => 1, 'tag' => 'tag1', 'created' => '2007-03-18 12:22:23', 'updated' => '2007-03-18 12:24:31'), + array('id' => 3, 'tag' => 'tag3', 'created' => '2007-03-18 12:26:23', 'updated' => '2007-03-18 12:28:31') + ) + ), + array( + 'Article' => array( + 'id' => 3, 'user_id' => 1, 'title' => 'Third Article', 'body' => 'Third Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:43:23', 'updated' => '2007-03-18 10:45:31' + ), + 'User' => array( + 'id' => 1, 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31', + 'ArticleFeatured' => array( + array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ), + array( + 'id' => 3, 'user_id' => 1, 'title' => 'Third Article', 'body' => 'Third Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:43:23', 'updated' => '2007-03-18 10:45:31' + ) + ) + ), + 'Comment' => array(), + 'Tag' => array() + ) + ); + $this->assertEquals($expected, $result); + } + +/** + * testFindThirdLevel method + * + * @return void + */ + public function testFindThirdLevel() { + $this->User->contain(array('ArticleFeatured' => array('Featured' => 'Category'))); + $result = $this->User->find('all', array('recursive' => 3)); + $expected = array( + array( + 'User' => array( + 'id' => 1, 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31' + ), + 'ArticleFeatured' => array( + array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31', + 'Featured' => array( + 'id' => 1, 'article_featured_id' => 1, 'category_id' => 1, 'published_date' => '2007-03-31 10:39:23', + 'end_date' => '2007-05-15 10:39:23', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31', + 'Category' => array( + 'id' => 1, 'parent_id' => 0, 'name' => 'Category 1', + 'created' => '2007-03-18 15:30:23', 'updated' => '2007-03-18 15:32:31' + ) + ) + ), + array( + 'id' => 3, 'user_id' => 1, 'title' => 'Third Article', 'body' => 'Third Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:43:23', 'updated' => '2007-03-18 10:45:31', + 'Featured' => array() + ) + ) + ), + array( + 'User' => array( + 'id' => 2, 'user' => 'nate', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:18:23', 'updated' => '2007-03-17 01:20:31' + ), + 'ArticleFeatured' => array() + ), + array( + 'User' => array( + 'id' => 3, 'user' => 'larry', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:20:23', 'updated' => '2007-03-17 01:22:31' + ), + 'ArticleFeatured' => array( + array( + 'id' => 2, 'user_id' => 3, 'title' => 'Second Article', 'body' => 'Second Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:41:23', 'updated' => '2007-03-18 10:43:31', + 'Featured' => array( + 'id' => 2, 'article_featured_id' => 2, 'category_id' => 1, 'published_date' => '2007-03-31 10:39:23', + 'end_date' => '2007-05-15 10:39:23', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31', + 'Category' => array( + 'id' => 1, 'parent_id' => 0, 'name' => 'Category 1', + 'created' => '2007-03-18 15:30:23', 'updated' => '2007-03-18 15:32:31' + ) + ) + ) + ) + ), + array( + 'User' => array( + 'id' => 4, 'user' => 'garrett', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:22:23', 'updated' => '2007-03-17 01:24:31' + ), + 'ArticleFeatured' => array() + ) + ); + $this->assertEquals($expected, $result); + + $this->User->contain(array('ArticleFeatured' => array('Featured' => 'Category', 'Comment' => array('Article', 'Attachment')))); + $result = $this->User->find('all', array('recursive' => 3)); + $expected = array( + array( + 'User' => array( + 'id' => 1, 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31' + ), + 'ArticleFeatured' => array( + array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31', + 'Featured' => array( + 'id' => 1, 'article_featured_id' => 1, 'category_id' => 1, 'published_date' => '2007-03-31 10:39:23', + 'end_date' => '2007-05-15 10:39:23', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31', + 'Category' => array( + 'id' => 1, 'parent_id' => 0, 'name' => 'Category 1', + 'created' => '2007-03-18 15:30:23', 'updated' => '2007-03-18 15:32:31' + ) + ), + 'Comment' => array( + array( + 'id' => 1, 'article_id' => 1, 'user_id' => 2, 'comment' => 'First Comment for First Article', + 'published' => 'Y', 'created' => '2007-03-18 10:45:23', 'updated' => '2007-03-18 10:47:31', + 'Article' => array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ), + 'Attachment' => array() + ), + array( + 'id' => 2, 'article_id' => 1, 'user_id' => 4, 'comment' => 'Second Comment for First Article', + 'published' => 'Y', 'created' => '2007-03-18 10:47:23', 'updated' => '2007-03-18 10:49:31', + 'Article' => array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ), + 'Attachment' => array() + ), + array( + 'id' => 3, 'article_id' => 1, 'user_id' => 1, 'comment' => 'Third Comment for First Article', + 'published' => 'Y', 'created' => '2007-03-18 10:49:23', 'updated' => '2007-03-18 10:51:31', + 'Article' => array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ), + 'Attachment' => array() + ), + array( + 'id' => 4, 'article_id' => 1, 'user_id' => 1, 'comment' => 'Fourth Comment for First Article', + 'published' => 'N', 'created' => '2007-03-18 10:51:23', 'updated' => '2007-03-18 10:53:31', + 'Article' => array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ), + 'Attachment' => array() + ) + ) + ), + array( + 'id' => 3, 'user_id' => 1, 'title' => 'Third Article', 'body' => 'Third Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:43:23', 'updated' => '2007-03-18 10:45:31', + 'Featured' => array(), + 'Comment' => array() + ) + ) + ), + array( + 'User' => array( + 'id' => 2, 'user' => 'nate', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:18:23', 'updated' => '2007-03-17 01:20:31' + ), + 'ArticleFeatured' => array() + ), + array( + 'User' => array( + 'id' => 3, 'user' => 'larry', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:20:23', 'updated' => '2007-03-17 01:22:31' + ), + 'ArticleFeatured' => array( + array( + 'id' => 2, 'user_id' => 3, 'title' => 'Second Article', 'body' => 'Second Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:41:23', 'updated' => '2007-03-18 10:43:31', + 'Featured' => array( + 'id' => 2, 'article_featured_id' => 2, 'category_id' => 1, 'published_date' => '2007-03-31 10:39:23', + 'end_date' => '2007-05-15 10:39:23', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31', + 'Category' => array( + 'id' => 1, 'parent_id' => 0, 'name' => 'Category 1', + 'created' => '2007-03-18 15:30:23', 'updated' => '2007-03-18 15:32:31' + ) + ), + 'Comment' => array( + array( + 'id' => 5, 'article_id' => 2, 'user_id' => 1, 'comment' => 'First Comment for Second Article', + 'published' => 'Y', 'created' => '2007-03-18 10:53:23', 'updated' => '2007-03-18 10:55:31', + 'Article' => array( + 'id' => 2, 'user_id' => 3, 'title' => 'Second Article', 'body' => 'Second Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:41:23', 'updated' => '2007-03-18 10:43:31' + ), + 'Attachment' => array( + 'id' => 1, 'comment_id' => 5, 'attachment' => 'attachment.zip', + 'created' => '2007-03-18 10:51:23', 'updated' => '2007-03-18 10:53:31' + ) + ), + array( + 'id' => 6, 'article_id' => 2, 'user_id' => 2, 'comment' => 'Second Comment for Second Article', + 'published' => 'Y', 'created' => '2007-03-18 10:55:23', 'updated' => '2007-03-18 10:57:31', + 'Article' => array( + 'id' => 2, 'user_id' => 3, 'title' => 'Second Article', 'body' => 'Second Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:41:23', 'updated' => '2007-03-18 10:43:31' + ), + 'Attachment' => array() + ) + ) + ) + ) + ), + array( + 'User' => array( + 'id' => 4, 'user' => 'garrett', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:22:23', 'updated' => '2007-03-17 01:24:31' + ), + 'ArticleFeatured' => array() + ) + ); + $this->assertEquals($expected, $result); + + $this->User->contain(array('ArticleFeatured' => array('Featured' => 'Category', 'Comment' => 'Attachment'), 'Article')); + $result = $this->User->find('all', array('recursive' => 3)); + $expected = array( + array( + 'User' => array( + 'id' => 1, 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31' + ), + 'Article' => array( + array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ), + array( + 'id' => 3, 'user_id' => 1, 'title' => 'Third Article', 'body' => 'Third Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:43:23', 'updated' => '2007-03-18 10:45:31' + ) + ), + 'ArticleFeatured' => array( + array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31', + 'Featured' => array( + 'id' => 1, 'article_featured_id' => 1, 'category_id' => 1, 'published_date' => '2007-03-31 10:39:23', + 'end_date' => '2007-05-15 10:39:23', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31', + 'Category' => array( + 'id' => 1, 'parent_id' => 0, 'name' => 'Category 1', + 'created' => '2007-03-18 15:30:23', 'updated' => '2007-03-18 15:32:31' + ) + ), + 'Comment' => array( + array( + 'id' => 1, 'article_id' => 1, 'user_id' => 2, 'comment' => 'First Comment for First Article', + 'published' => 'Y', 'created' => '2007-03-18 10:45:23', 'updated' => '2007-03-18 10:47:31', + 'Attachment' => array() + ), + array( + 'id' => 2, 'article_id' => 1, 'user_id' => 4, 'comment' => 'Second Comment for First Article', + 'published' => 'Y', 'created' => '2007-03-18 10:47:23', 'updated' => '2007-03-18 10:49:31', + 'Attachment' => array() + ), + array( + 'id' => 3, 'article_id' => 1, 'user_id' => 1, 'comment' => 'Third Comment for First Article', + 'published' => 'Y', 'created' => '2007-03-18 10:49:23', 'updated' => '2007-03-18 10:51:31', + 'Attachment' => array() + ), + array( + 'id' => 4, 'article_id' => 1, 'user_id' => 1, 'comment' => 'Fourth Comment for First Article', + 'published' => 'N', 'created' => '2007-03-18 10:51:23', 'updated' => '2007-03-18 10:53:31', + 'Attachment' => array() + ) + ) + ), + array( + 'id' => 3, 'user_id' => 1, 'title' => 'Third Article', 'body' => 'Third Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:43:23', 'updated' => '2007-03-18 10:45:31', + 'Featured' => array(), + 'Comment' => array() + ) + ) + ), + array( + 'User' => array( + 'id' => 2, 'user' => 'nate', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:18:23', 'updated' => '2007-03-17 01:20:31' + ), + 'Article' => array(), + 'ArticleFeatured' => array() + ), + array( + 'User' => array( + 'id' => 3, 'user' => 'larry', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:20:23', 'updated' => '2007-03-17 01:22:31' + ), + 'Article' => array( + array( + 'id' => 2, 'user_id' => 3, 'title' => 'Second Article', 'body' => 'Second Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:41:23', 'updated' => '2007-03-18 10:43:31' + ) + ), + 'ArticleFeatured' => array( + array( + 'id' => 2, 'user_id' => 3, 'title' => 'Second Article', 'body' => 'Second Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:41:23', 'updated' => '2007-03-18 10:43:31', + 'Featured' => array( + 'id' => 2, 'article_featured_id' => 2, 'category_id' => 1, 'published_date' => '2007-03-31 10:39:23', + 'end_date' => '2007-05-15 10:39:23', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31', + 'Category' => array( + 'id' => 1, 'parent_id' => 0, 'name' => 'Category 1', + 'created' => '2007-03-18 15:30:23', 'updated' => '2007-03-18 15:32:31' + ) + ), + 'Comment' => array( + array( + 'id' => 5, 'article_id' => 2, 'user_id' => 1, 'comment' => 'First Comment for Second Article', + 'published' => 'Y', 'created' => '2007-03-18 10:53:23', 'updated' => '2007-03-18 10:55:31', + 'Attachment' => array( + 'id' => 1, 'comment_id' => 5, 'attachment' => 'attachment.zip', + 'created' => '2007-03-18 10:51:23', 'updated' => '2007-03-18 10:53:31' + ) + ), + array( + 'id' => 6, 'article_id' => 2, 'user_id' => 2, 'comment' => 'Second Comment for Second Article', + 'published' => 'Y', 'created' => '2007-03-18 10:55:23', 'updated' => '2007-03-18 10:57:31', + 'Attachment' => array() + ) + ) + ) + ) + ), + array( + 'User' => array( + 'id' => 4, 'user' => 'garrett', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:22:23', 'updated' => '2007-03-17 01:24:31' + ), + 'Article' => array(), + 'ArticleFeatured' => array() + ) + ); + $this->assertEquals($expected, $result); + } + +/** + * testFindEmbeddedThirdLevel method + * + * @return void + */ + public function testFindEmbeddedThirdLevel() { + $result = $this->User->find('all', array('contain' => array('ArticleFeatured' => array('Featured' => 'Category')))); + $expected = array( + array( + 'User' => array( + 'id' => 1, 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31' + ), + 'ArticleFeatured' => array( + array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31', + 'Featured' => array( + 'id' => 1, 'article_featured_id' => 1, 'category_id' => 1, 'published_date' => '2007-03-31 10:39:23', + 'end_date' => '2007-05-15 10:39:23', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31', + 'Category' => array( + 'id' => 1, 'parent_id' => 0, 'name' => 'Category 1', + 'created' => '2007-03-18 15:30:23', 'updated' => '2007-03-18 15:32:31' + ) + ) + ), + array( + 'id' => 3, 'user_id' => 1, 'title' => 'Third Article', 'body' => 'Third Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:43:23', 'updated' => '2007-03-18 10:45:31', + 'Featured' => array() + ) + ) + ), + array( + 'User' => array( + 'id' => 2, 'user' => 'nate', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:18:23', 'updated' => '2007-03-17 01:20:31' + ), + 'ArticleFeatured' => array() + ), + array( + 'User' => array( + 'id' => 3, 'user' => 'larry', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:20:23', 'updated' => '2007-03-17 01:22:31' + ), + 'ArticleFeatured' => array( + array( + 'id' => 2, 'user_id' => 3, 'title' => 'Second Article', 'body' => 'Second Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:41:23', 'updated' => '2007-03-18 10:43:31', + 'Featured' => array( + 'id' => 2, 'article_featured_id' => 2, 'category_id' => 1, 'published_date' => '2007-03-31 10:39:23', + 'end_date' => '2007-05-15 10:39:23', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31', + 'Category' => array( + 'id' => 1, 'parent_id' => 0, 'name' => 'Category 1', + 'created' => '2007-03-18 15:30:23', 'updated' => '2007-03-18 15:32:31' + ) + ) + ) + ) + ), + array( + 'User' => array( + 'id' => 4, 'user' => 'garrett', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:22:23', 'updated' => '2007-03-17 01:24:31' + ), + 'ArticleFeatured' => array() + ) + ); + $this->assertEquals($expected, $result); + + $result = $this->User->find('all', array('contain' => array('ArticleFeatured' => array('Featured' => 'Category', 'Comment' => array('Article', 'Attachment'))))); + $expected = array( + array( + 'User' => array( + 'id' => 1, 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31' + ), + 'ArticleFeatured' => array( + array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31', + 'Featured' => array( + 'id' => 1, 'article_featured_id' => 1, 'category_id' => 1, 'published_date' => '2007-03-31 10:39:23', + 'end_date' => '2007-05-15 10:39:23', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31', + 'Category' => array( + 'id' => 1, 'parent_id' => 0, 'name' => 'Category 1', + 'created' => '2007-03-18 15:30:23', 'updated' => '2007-03-18 15:32:31' + ) + ), + 'Comment' => array( + array( + 'id' => 1, 'article_id' => 1, 'user_id' => 2, 'comment' => 'First Comment for First Article', + 'published' => 'Y', 'created' => '2007-03-18 10:45:23', 'updated' => '2007-03-18 10:47:31', + 'Article' => array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ), + 'Attachment' => array() + ), + array( + 'id' => 2, 'article_id' => 1, 'user_id' => 4, 'comment' => 'Second Comment for First Article', + 'published' => 'Y', 'created' => '2007-03-18 10:47:23', 'updated' => '2007-03-18 10:49:31', + 'Article' => array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ), + 'Attachment' => array() + ), + array( + 'id' => 3, 'article_id' => 1, 'user_id' => 1, 'comment' => 'Third Comment for First Article', + 'published' => 'Y', 'created' => '2007-03-18 10:49:23', 'updated' => '2007-03-18 10:51:31', + 'Article' => array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ), + 'Attachment' => array() + ), + array( + 'id' => 4, 'article_id' => 1, 'user_id' => 1, 'comment' => 'Fourth Comment for First Article', + 'published' => 'N', 'created' => '2007-03-18 10:51:23', 'updated' => '2007-03-18 10:53:31', + 'Article' => array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ), + 'Attachment' => array() + ) + ) + ), + array( + 'id' => 3, 'user_id' => 1, 'title' => 'Third Article', 'body' => 'Third Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:43:23', 'updated' => '2007-03-18 10:45:31', + 'Featured' => array(), + 'Comment' => array() + ) + ) + ), + array( + 'User' => array( + 'id' => 2, 'user' => 'nate', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:18:23', 'updated' => '2007-03-17 01:20:31' + ), + 'ArticleFeatured' => array() + ), + array( + 'User' => array( + 'id' => 3, 'user' => 'larry', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:20:23', 'updated' => '2007-03-17 01:22:31' + ), + 'ArticleFeatured' => array( + array( + 'id' => 2, 'user_id' => 3, 'title' => 'Second Article', 'body' => 'Second Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:41:23', 'updated' => '2007-03-18 10:43:31', + 'Featured' => array( + 'id' => 2, 'article_featured_id' => 2, 'category_id' => 1, 'published_date' => '2007-03-31 10:39:23', + 'end_date' => '2007-05-15 10:39:23', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31', + 'Category' => array( + 'id' => 1, 'parent_id' => 0, 'name' => 'Category 1', + 'created' => '2007-03-18 15:30:23', 'updated' => '2007-03-18 15:32:31' + ) + ), + 'Comment' => array( + array( + 'id' => 5, 'article_id' => 2, 'user_id' => 1, 'comment' => 'First Comment for Second Article', + 'published' => 'Y', 'created' => '2007-03-18 10:53:23', 'updated' => '2007-03-18 10:55:31', + 'Article' => array( + 'id' => 2, 'user_id' => 3, 'title' => 'Second Article', 'body' => 'Second Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:41:23', 'updated' => '2007-03-18 10:43:31' + ), + 'Attachment' => array( + 'id' => 1, 'comment_id' => 5, 'attachment' => 'attachment.zip', + 'created' => '2007-03-18 10:51:23', 'updated' => '2007-03-18 10:53:31' + ) + ), + array( + 'id' => 6, 'article_id' => 2, 'user_id' => 2, 'comment' => 'Second Comment for Second Article', + 'published' => 'Y', 'created' => '2007-03-18 10:55:23', 'updated' => '2007-03-18 10:57:31', + 'Article' => array( + 'id' => 2, 'user_id' => 3, 'title' => 'Second Article', 'body' => 'Second Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:41:23', 'updated' => '2007-03-18 10:43:31' + ), + 'Attachment' => array() + ) + ) + ) + ) + ), + array( + 'User' => array( + 'id' => 4, 'user' => 'garrett', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:22:23', 'updated' => '2007-03-17 01:24:31' + ), + 'ArticleFeatured' => array() + ) + ); + $this->assertEquals($expected, $result); + + $result = $this->User->find('all', array('contain' => array('ArticleFeatured' => array('Featured' => 'Category', 'Comment' => 'Attachment'), 'Article'))); + $expected = array( + array( + 'User' => array( + 'id' => 1, 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31' + ), + 'Article' => array( + array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ), + array( + 'id' => 3, 'user_id' => 1, 'title' => 'Third Article', 'body' => 'Third Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:43:23', 'updated' => '2007-03-18 10:45:31' + ) + ), + 'ArticleFeatured' => array( + array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31', + 'Featured' => array( + 'id' => 1, 'article_featured_id' => 1, 'category_id' => 1, 'published_date' => '2007-03-31 10:39:23', + 'end_date' => '2007-05-15 10:39:23', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31', + 'Category' => array( + 'id' => 1, 'parent_id' => 0, 'name' => 'Category 1', + 'created' => '2007-03-18 15:30:23', 'updated' => '2007-03-18 15:32:31' + ) + ), + 'Comment' => array( + array( + 'id' => 1, 'article_id' => 1, 'user_id' => 2, 'comment' => 'First Comment for First Article', + 'published' => 'Y', 'created' => '2007-03-18 10:45:23', 'updated' => '2007-03-18 10:47:31', + 'Attachment' => array() + ), + array( + 'id' => 2, 'article_id' => 1, 'user_id' => 4, 'comment' => 'Second Comment for First Article', + 'published' => 'Y', 'created' => '2007-03-18 10:47:23', 'updated' => '2007-03-18 10:49:31', + 'Attachment' => array() + ), + array( + 'id' => 3, 'article_id' => 1, 'user_id' => 1, 'comment' => 'Third Comment for First Article', + 'published' => 'Y', 'created' => '2007-03-18 10:49:23', 'updated' => '2007-03-18 10:51:31', + 'Attachment' => array() + ), + array( + 'id' => 4, 'article_id' => 1, 'user_id' => 1, 'comment' => 'Fourth Comment for First Article', + 'published' => 'N', 'created' => '2007-03-18 10:51:23', 'updated' => '2007-03-18 10:53:31', + 'Attachment' => array() + ) + ) + ), + array( + 'id' => 3, 'user_id' => 1, 'title' => 'Third Article', 'body' => 'Third Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:43:23', 'updated' => '2007-03-18 10:45:31', + 'Featured' => array(), + 'Comment' => array() + ) + ) + ), + array( + 'User' => array( + 'id' => 2, 'user' => 'nate', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:18:23', 'updated' => '2007-03-17 01:20:31' + ), + 'Article' => array(), + 'ArticleFeatured' => array() + ), + array( + 'User' => array( + 'id' => 3, 'user' => 'larry', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:20:23', 'updated' => '2007-03-17 01:22:31' + ), + 'Article' => array( + array( + 'id' => 2, 'user_id' => 3, 'title' => 'Second Article', 'body' => 'Second Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:41:23', 'updated' => '2007-03-18 10:43:31' + ) + ), + 'ArticleFeatured' => array( + array( + 'id' => 2, 'user_id' => 3, 'title' => 'Second Article', 'body' => 'Second Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:41:23', 'updated' => '2007-03-18 10:43:31', + 'Featured' => array( + 'id' => 2, 'article_featured_id' => 2, 'category_id' => 1, 'published_date' => '2007-03-31 10:39:23', + 'end_date' => '2007-05-15 10:39:23', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31', + 'Category' => array( + 'id' => 1, 'parent_id' => 0, 'name' => 'Category 1', + 'created' => '2007-03-18 15:30:23', 'updated' => '2007-03-18 15:32:31' + ) + ), + 'Comment' => array( + array( + 'id' => 5, 'article_id' => 2, 'user_id' => 1, 'comment' => 'First Comment for Second Article', + 'published' => 'Y', 'created' => '2007-03-18 10:53:23', 'updated' => '2007-03-18 10:55:31', + 'Attachment' => array( + 'id' => 1, 'comment_id' => 5, 'attachment' => 'attachment.zip', + 'created' => '2007-03-18 10:51:23', 'updated' => '2007-03-18 10:53:31' + ) + ), + array( + 'id' => 6, 'article_id' => 2, 'user_id' => 2, 'comment' => 'Second Comment for Second Article', + 'published' => 'Y', 'created' => '2007-03-18 10:55:23', 'updated' => '2007-03-18 10:57:31', + 'Attachment' => array() + ) + ) + ) + ) + ), + array( + 'User' => array( + 'id' => 4, 'user' => 'garrett', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:22:23', 'updated' => '2007-03-17 01:24:31' + ), + 'Article' => array(), + 'ArticleFeatured' => array() + ) + ); + $this->assertEquals($expected, $result); + } + +/** + * testSettingsThirdLevel method + * + * @return void + */ + public function testSettingsThirdLevel() { + $result = $this->User->find('all', array('contain' => array('ArticleFeatured' => array('Featured' => array('Category' => array('id', 'name')))))); + $expected = array( + array( + 'User' => array( + 'id' => 1, 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31' + ), + 'ArticleFeatured' => array( + array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31', + 'Featured' => array( + 'id' => 1, 'article_featured_id' => 1, 'category_id' => 1, 'published_date' => '2007-03-31 10:39:23', + 'end_date' => '2007-05-15 10:39:23', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31', + 'Category' => array( + 'id' => 1, 'name' => 'Category 1' + ) + ) + ), + array( + 'id' => 3, 'user_id' => 1, 'title' => 'Third Article', 'body' => 'Third Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:43:23', 'updated' => '2007-03-18 10:45:31', + 'Featured' => array() + ) + ) + ), + array( + 'User' => array( + 'id' => 2, 'user' => 'nate', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:18:23', 'updated' => '2007-03-17 01:20:31' + ), + 'ArticleFeatured' => array() + ), + array( + 'User' => array( + 'id' => 3, 'user' => 'larry', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:20:23', 'updated' => '2007-03-17 01:22:31' + ), + 'ArticleFeatured' => array( + array( + 'id' => 2, 'user_id' => 3, 'title' => 'Second Article', 'body' => 'Second Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:41:23', 'updated' => '2007-03-18 10:43:31', + 'Featured' => array( + 'id' => 2, 'article_featured_id' => 2, 'category_id' => 1, 'published_date' => '2007-03-31 10:39:23', + 'end_date' => '2007-05-15 10:39:23', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31', + 'Category' => array( + 'id' => 1, 'name' => 'Category 1' + ) + ) + ) + ) + ), + array( + 'User' => array( + 'id' => 4, 'user' => 'garrett', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:22:23', 'updated' => '2007-03-17 01:24:31' + ), + 'ArticleFeatured' => array() + ) + ); + $this->assertEquals($expected, $result); + + $r = $this->User->find('all', array('contain' => array( + 'ArticleFeatured' => array( + 'id', 'title', + 'Featured' => array( + 'id', 'category_id', + 'Category' => array('id', 'name') + ) + ) + ))); + + $this->assertTrue(Set::matches('/User[id=1]', $r)); + $this->assertFalse(Set::matches('/Article', $r) || Set::matches('/Comment', $r)); + $this->assertTrue(Set::matches('/ArticleFeatured', $r)); + $this->assertFalse(Set::matches('/ArticleFeatured/User', $r) || Set::matches('/ArticleFeatured/Comment', $r) || Set::matches('/ArticleFeatured/Tag', $r)); + $this->assertTrue(Set::matches('/ArticleFeatured/Featured', $r)); + $this->assertFalse(Set::matches('/ArticleFeatured/Featured/ArticleFeatured', $r)); + $this->assertTrue(Set::matches('/ArticleFeatured/Featured/Category', $r)); + $this->assertTrue(Set::matches('/ArticleFeatured/Featured[id=1]', $r)); + $this->assertTrue(Set::matches('/ArticleFeatured/Featured[id=1]/Category[id=1]', $r)); + $this->assertTrue(Set::matches('/ArticleFeatured/Featured[id=1]/Category[name=Category 1]', $r)); + + $r = $this->User->find('all', array('contain' => array( + 'ArticleFeatured' => array( + 'title', + 'Featured' => array( + 'id', + 'Category' => 'name' + ) + ) + ))); + + $this->assertTrue(Set::matches('/User[id=1]', $r)); + $this->assertFalse(Set::matches('/Article', $r) || Set::matches('/Comment', $r)); + $this->assertTrue(Set::matches('/ArticleFeatured', $r)); + $this->assertFalse(Set::matches('/ArticleFeatured/User', $r) || Set::matches('/ArticleFeatured/Comment', $r) || Set::matches('/ArticleFeatured/Tag', $r)); + $this->assertTrue(Set::matches('/ArticleFeatured/Featured', $r)); + $this->assertFalse(Set::matches('/ArticleFeatured/Featured/ArticleFeatured', $r)); + $this->assertTrue(Set::matches('/ArticleFeatured/Featured/Category', $r)); + $this->assertTrue(Set::matches('/ArticleFeatured/Featured[id=1]', $r)); + $this->assertTrue(Set::matches('/ArticleFeatured/Featured[id=1]/Category[name=Category 1]', $r)); + + $result = $this->User->find('all', array('contain' => array( + 'ArticleFeatured' => array( + 'title', + 'Featured' => array( + 'category_id', + 'Category' => 'name' + ) + ) + ))); + $expected = array( + array( + 'User' => array( + 'id' => 1, 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31' + ), + 'ArticleFeatured' => array( + array( + 'title' => 'First Article', 'id' => 1, 'user_id' => 1, + 'Featured' => array( + 'category_id' => 1, 'id' => 1, + 'Category' => array( + 'name' => 'Category 1' + ) + ) + ), + array( + 'title' => 'Third Article', 'id' => 3, 'user_id' => 1, + 'Featured' => array() + ) + ) + ), + array( + 'User' => array( + 'id' => 2, 'user' => 'nate', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:18:23', 'updated' => '2007-03-17 01:20:31' + ), + 'ArticleFeatured' => array() + ), + array( + 'User' => array( + 'id' => 3, 'user' => 'larry', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:20:23', 'updated' => '2007-03-17 01:22:31' + ), + 'ArticleFeatured' => array( + array( + 'title' => 'Second Article', 'id' => 2, 'user_id' => 3, + 'Featured' => array( + 'category_id' => 1, 'id' => 2, + 'Category' => array( + 'name' => 'Category 1' + ) + ) + ) + ) + ), + array( + 'User' => array( + 'id' => 4, 'user' => 'garrett', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:22:23', 'updated' => '2007-03-17 01:24:31' + ), + 'ArticleFeatured' => array() + ) + ); + $this->assertEquals($expected, $result); + + $orders = array( + 'title DESC', 'title DESC, published DESC', + array('title' => 'DESC'), array('title' => 'DESC', 'published' => 'DESC'), + ); + foreach ($orders as $order) { + $result = $this->User->find('all', array('contain' => array( + 'ArticleFeatured' => array( + 'title', 'order' => $order, + 'Featured' => array( + 'category_id', + 'Category' => 'name' + ) + ) + ))); + $expected = array( + array( + 'User' => array( + 'id' => 1, 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31' + ), + 'ArticleFeatured' => array( + array( + 'title' => 'Third Article', 'id' => 3, 'user_id' => 1, + 'Featured' => array() + ), + array( + 'title' => 'First Article', 'id' => 1, 'user_id' => 1, + 'Featured' => array( + 'category_id' => 1, 'id' => 1, + 'Category' => array( + 'name' => 'Category 1' + ) + ) + ) + ) + ), + array( + 'User' => array( + 'id' => 2, 'user' => 'nate', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:18:23', 'updated' => '2007-03-17 01:20:31' + ), + 'ArticleFeatured' => array() + ), + array( + 'User' => array( + 'id' => 3, 'user' => 'larry', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:20:23', 'updated' => '2007-03-17 01:22:31' + ), + 'ArticleFeatured' => array( + array( + 'title' => 'Second Article', 'id' => 2, 'user_id' => 3, + 'Featured' => array( + 'category_id' => 1, 'id' => 2, + 'Category' => array( + 'name' => 'Category 1' + ) + ) + ) + ) + ), + array( + 'User' => array( + 'id' => 4, 'user' => 'garrett', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:22:23', 'updated' => '2007-03-17 01:24:31' + ), + 'ArticleFeatured' => array() + ) + ); + $this->assertEquals($expected, $result); + } + } + +/** + * testFindThirdLevelNonReset method + * + * @return void + */ + public function testFindThirdLevelNonReset() { + $this->User->contain(false, array('ArticleFeatured' => array('Featured' => 'Category'))); + $result = $this->User->find('all', array('recursive' => 3)); + $expected = array( + array( + 'User' => array( + 'id' => 1, 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31' + ), + 'ArticleFeatured' => array( + array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31', + 'Featured' => array( + 'id' => 1, 'article_featured_id' => 1, 'category_id' => 1, 'published_date' => '2007-03-31 10:39:23', + 'end_date' => '2007-05-15 10:39:23', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31', + 'Category' => array( + 'id' => 1, 'parent_id' => 0, 'name' => 'Category 1', + 'created' => '2007-03-18 15:30:23', 'updated' => '2007-03-18 15:32:31' + ) + ) + ), + array( + 'id' => 3, 'user_id' => 1, 'title' => 'Third Article', 'body' => 'Third Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:43:23', 'updated' => '2007-03-18 10:45:31', + 'Featured' => array() + ) + ) + ), + array( + 'User' => array( + 'id' => 2, 'user' => 'nate', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:18:23', 'updated' => '2007-03-17 01:20:31' + ), + 'ArticleFeatured' => array() + ), + array( + 'User' => array( + 'id' => 3, 'user' => 'larry', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:20:23', 'updated' => '2007-03-17 01:22:31' + ), + 'ArticleFeatured' => array( + array( + 'id' => 2, 'user_id' => 3, 'title' => 'Second Article', 'body' => 'Second Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:41:23', 'updated' => '2007-03-18 10:43:31', + 'Featured' => array( + 'id' => 2, 'article_featured_id' => 2, 'category_id' => 1, 'published_date' => '2007-03-31 10:39:23', + 'end_date' => '2007-05-15 10:39:23', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31', + 'Category' => array( + 'id' => 1, 'parent_id' => 0, 'name' => 'Category 1', + 'created' => '2007-03-18 15:30:23', 'updated' => '2007-03-18 15:32:31' + ) + ) + ) + ) + ), + array( + 'User' => array( + 'id' => 4, 'user' => 'garrett', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:22:23', 'updated' => '2007-03-17 01:24:31' + ), + 'ArticleFeatured' => array() + ) + ); + $this->assertEquals($expected, $result); + + $this->User->resetBindings(); + + $this->User->contain(false, array('ArticleFeatured' => array('Featured' => 'Category', 'Comment' => array('Article', 'Attachment')))); + $result = $this->User->find('all', array('recursive' => 3)); + $expected = array( + array( + 'User' => array( + 'id' => 1, 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31' + ), + 'ArticleFeatured' => array( + array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31', + 'Featured' => array( + 'id' => 1, 'article_featured_id' => 1, 'category_id' => 1, 'published_date' => '2007-03-31 10:39:23', + 'end_date' => '2007-05-15 10:39:23', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31', + 'Category' => array( + 'id' => 1, 'parent_id' => 0, 'name' => 'Category 1', + 'created' => '2007-03-18 15:30:23', 'updated' => '2007-03-18 15:32:31' + ) + ), + 'Comment' => array( + array( + 'id' => 1, 'article_id' => 1, 'user_id' => 2, 'comment' => 'First Comment for First Article', + 'published' => 'Y', 'created' => '2007-03-18 10:45:23', 'updated' => '2007-03-18 10:47:31', + 'Article' => array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ), + 'Attachment' => array() + ), + array( + 'id' => 2, 'article_id' => 1, 'user_id' => 4, 'comment' => 'Second Comment for First Article', + 'published' => 'Y', 'created' => '2007-03-18 10:47:23', 'updated' => '2007-03-18 10:49:31', + 'Article' => array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ), + 'Attachment' => array() + ), + array( + 'id' => 3, 'article_id' => 1, 'user_id' => 1, 'comment' => 'Third Comment for First Article', + 'published' => 'Y', 'created' => '2007-03-18 10:49:23', 'updated' => '2007-03-18 10:51:31', + 'Article' => array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ), + 'Attachment' => array() + ), + array( + 'id' => 4, 'article_id' => 1, 'user_id' => 1, 'comment' => 'Fourth Comment for First Article', + 'published' => 'N', 'created' => '2007-03-18 10:51:23', 'updated' => '2007-03-18 10:53:31', + 'Article' => array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ), + 'Attachment' => array() + ) + ) + ), + array( + 'id' => 3, 'user_id' => 1, 'title' => 'Third Article', 'body' => 'Third Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:43:23', 'updated' => '2007-03-18 10:45:31', + 'Featured' => array(), + 'Comment' => array() + ) + ) + ), + array( + 'User' => array( + 'id' => 2, 'user' => 'nate', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:18:23', 'updated' => '2007-03-17 01:20:31' + ), + 'ArticleFeatured' => array() + ), + array( + 'User' => array( + 'id' => 3, 'user' => 'larry', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:20:23', 'updated' => '2007-03-17 01:22:31' + ), + 'ArticleFeatured' => array( + array( + 'id' => 2, 'user_id' => 3, 'title' => 'Second Article', 'body' => 'Second Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:41:23', 'updated' => '2007-03-18 10:43:31', + 'Featured' => array( + 'id' => 2, 'article_featured_id' => 2, 'category_id' => 1, 'published_date' => '2007-03-31 10:39:23', + 'end_date' => '2007-05-15 10:39:23', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31', + 'Category' => array( + 'id' => 1, 'parent_id' => 0, 'name' => 'Category 1', + 'created' => '2007-03-18 15:30:23', 'updated' => '2007-03-18 15:32:31' + ) + ), + 'Comment' => array( + array( + 'id' => 5, 'article_id' => 2, 'user_id' => 1, 'comment' => 'First Comment for Second Article', + 'published' => 'Y', 'created' => '2007-03-18 10:53:23', 'updated' => '2007-03-18 10:55:31', + 'Article' => array( + 'id' => 2, 'user_id' => 3, 'title' => 'Second Article', 'body' => 'Second Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:41:23', 'updated' => '2007-03-18 10:43:31' + ), + 'Attachment' => array( + 'id' => 1, 'comment_id' => 5, 'attachment' => 'attachment.zip', + 'created' => '2007-03-18 10:51:23', 'updated' => '2007-03-18 10:53:31' + ) + ), + array( + 'id' => 6, 'article_id' => 2, 'user_id' => 2, 'comment' => 'Second Comment for Second Article', + 'published' => 'Y', 'created' => '2007-03-18 10:55:23', 'updated' => '2007-03-18 10:57:31', + 'Article' => array( + 'id' => 2, 'user_id' => 3, 'title' => 'Second Article', 'body' => 'Second Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:41:23', 'updated' => '2007-03-18 10:43:31' + ), + 'Attachment' => array() + ) + ) + ) + ) + ), + array( + 'User' => array( + 'id' => 4, 'user' => 'garrett', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:22:23', 'updated' => '2007-03-17 01:24:31' + ), + 'ArticleFeatured' => array() + ) + ); + $this->assertEquals($expected, $result); + + $this->User->resetBindings(); + + $this->User->contain(false, array('ArticleFeatured' => array('Featured' => 'Category', 'Comment' => 'Attachment'), 'Article')); + $result = $this->User->find('all', array('recursive' => 3)); + $expected = array( + array( + 'User' => array( + 'id' => 1, 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31' + ), + 'Article' => array( + array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ), + array( + 'id' => 3, 'user_id' => 1, 'title' => 'Third Article', 'body' => 'Third Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:43:23', 'updated' => '2007-03-18 10:45:31' + ) + ), + 'ArticleFeatured' => array( + array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31', + 'Featured' => array( + 'id' => 1, 'article_featured_id' => 1, 'category_id' => 1, 'published_date' => '2007-03-31 10:39:23', + 'end_date' => '2007-05-15 10:39:23', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31', + 'Category' => array( + 'id' => 1, 'parent_id' => 0, 'name' => 'Category 1', + 'created' => '2007-03-18 15:30:23', 'updated' => '2007-03-18 15:32:31' + ) + ), + 'Comment' => array( + array( + 'id' => 1, 'article_id' => 1, 'user_id' => 2, 'comment' => 'First Comment for First Article', + 'published' => 'Y', 'created' => '2007-03-18 10:45:23', 'updated' => '2007-03-18 10:47:31', + 'Attachment' => array() + ), + array( + 'id' => 2, 'article_id' => 1, 'user_id' => 4, 'comment' => 'Second Comment for First Article', + 'published' => 'Y', 'created' => '2007-03-18 10:47:23', 'updated' => '2007-03-18 10:49:31', + 'Attachment' => array() + ), + array( + 'id' => 3, 'article_id' => 1, 'user_id' => 1, 'comment' => 'Third Comment for First Article', + 'published' => 'Y', 'created' => '2007-03-18 10:49:23', 'updated' => '2007-03-18 10:51:31', + 'Attachment' => array() + ), + array( + 'id' => 4, 'article_id' => 1, 'user_id' => 1, 'comment' => 'Fourth Comment for First Article', + 'published' => 'N', 'created' => '2007-03-18 10:51:23', 'updated' => '2007-03-18 10:53:31', + 'Attachment' => array() + ) + ) + ), + array( + 'id' => 3, 'user_id' => 1, 'title' => 'Third Article', 'body' => 'Third Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:43:23', 'updated' => '2007-03-18 10:45:31', + 'Featured' => array(), + 'Comment' => array() + ) + ) + ), + array( + 'User' => array( + 'id' => 2, 'user' => 'nate', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:18:23', 'updated' => '2007-03-17 01:20:31' + ), + 'Article' => array(), + 'ArticleFeatured' => array() + ), + array( + 'User' => array( + 'id' => 3, 'user' => 'larry', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:20:23', 'updated' => '2007-03-17 01:22:31' + ), + 'Article' => array( + array( + 'id' => 2, 'user_id' => 3, 'title' => 'Second Article', 'body' => 'Second Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:41:23', 'updated' => '2007-03-18 10:43:31' + ) + ), + 'ArticleFeatured' => array( + array( + 'id' => 2, 'user_id' => 3, 'title' => 'Second Article', 'body' => 'Second Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:41:23', 'updated' => '2007-03-18 10:43:31', + 'Featured' => array( + 'id' => 2, 'article_featured_id' => 2, 'category_id' => 1, 'published_date' => '2007-03-31 10:39:23', + 'end_date' => '2007-05-15 10:39:23', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31', + 'Category' => array( + 'id' => 1, 'parent_id' => 0, 'name' => 'Category 1', + 'created' => '2007-03-18 15:30:23', 'updated' => '2007-03-18 15:32:31' + ) + ), + 'Comment' => array( + array( + 'id' => 5, 'article_id' => 2, 'user_id' => 1, 'comment' => 'First Comment for Second Article', + 'published' => 'Y', 'created' => '2007-03-18 10:53:23', 'updated' => '2007-03-18 10:55:31', + 'Attachment' => array( + 'id' => 1, 'comment_id' => 5, 'attachment' => 'attachment.zip', + 'created' => '2007-03-18 10:51:23', 'updated' => '2007-03-18 10:53:31' + ) + ), + array( + 'id' => 6, 'article_id' => 2, 'user_id' => 2, 'comment' => 'Second Comment for Second Article', + 'published' => 'Y', 'created' => '2007-03-18 10:55:23', 'updated' => '2007-03-18 10:57:31', + 'Attachment' => array() + ) + ) + ) + ) + ), + array( + 'User' => array( + 'id' => 4, 'user' => 'garrett', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:22:23', 'updated' => '2007-03-17 01:24:31' + ), + 'Article' => array(), + 'ArticleFeatured' => array() + ) + ); + $this->assertEquals($expected, $result); + } + +/** + * testFindEmbeddedThirdLevelNonReset method + * + * @return void + */ + public function testFindEmbeddedThirdLevelNonReset() { + $result = $this->User->find('all', array('reset' => false, 'contain' => array('ArticleFeatured' => array('Featured' => 'Category')))); + $expected = array( + array( + 'User' => array( + 'id' => 1, 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31' + ), + 'ArticleFeatured' => array( + array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31', + 'Featured' => array( + 'id' => 1, 'article_featured_id' => 1, 'category_id' => 1, 'published_date' => '2007-03-31 10:39:23', + 'end_date' => '2007-05-15 10:39:23', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31', + 'Category' => array( + 'id' => 1, 'parent_id' => 0, 'name' => 'Category 1', + 'created' => '2007-03-18 15:30:23', 'updated' => '2007-03-18 15:32:31' + ) + ) + ), + array( + 'id' => 3, 'user_id' => 1, 'title' => 'Third Article', 'body' => 'Third Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:43:23', 'updated' => '2007-03-18 10:45:31', + 'Featured' => array() + ) + ) + ), + array( + 'User' => array( + 'id' => 2, 'user' => 'nate', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:18:23', 'updated' => '2007-03-17 01:20:31' + ), + 'ArticleFeatured' => array() + ), + array( + 'User' => array( + 'id' => 3, 'user' => 'larry', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:20:23', 'updated' => '2007-03-17 01:22:31' + ), + 'ArticleFeatured' => array( + array( + 'id' => 2, 'user_id' => 3, 'title' => 'Second Article', 'body' => 'Second Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:41:23', 'updated' => '2007-03-18 10:43:31', + 'Featured' => array( + 'id' => 2, 'article_featured_id' => 2, 'category_id' => 1, 'published_date' => '2007-03-31 10:39:23', + 'end_date' => '2007-05-15 10:39:23', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31', + 'Category' => array( + 'id' => 1, 'parent_id' => 0, 'name' => 'Category 1', + 'created' => '2007-03-18 15:30:23', 'updated' => '2007-03-18 15:32:31' + ) + ) + ) + ) + ), + array( + 'User' => array( + 'id' => 4, 'user' => 'garrett', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:22:23', 'updated' => '2007-03-17 01:24:31' + ), + 'ArticleFeatured' => array() + ) + ); + $this->assertEquals($expected, $result); + + $this->_assertBindings($this->User, array('hasMany' => array('ArticleFeatured'))); + $this->_assertBindings($this->User->ArticleFeatured, array('hasOne' => array('Featured'))); + $this->_assertBindings($this->User->ArticleFeatured->Featured, array('belongsTo' => array('Category'))); + + $this->User->resetBindings(); + + $this->_assertBindings($this->User, array('hasMany' => array('Article', 'ArticleFeatured', 'Comment'))); + $this->_assertBindings($this->User->ArticleFeatured, array('belongsTo' => array('User'), 'hasOne' => array('Featured'), 'hasMany' => array('Comment'), 'hasAndBelongsToMany' => array('Tag'))); + $this->_assertBindings($this->User->ArticleFeatured->Featured, array('belongsTo' => array('ArticleFeatured', 'Category'))); + $this->_assertBindings($this->User->ArticleFeatured->Comment, array('belongsTo' => array('Article', 'User'), 'hasOne' => array('Attachment'))); + + $result = $this->User->find('all', array('reset' => false, 'contain' => array('ArticleFeatured' => array('Featured' => 'Category', 'Comment' => array('Article', 'Attachment'))))); + $expected = array( + array( + 'User' => array( + 'id' => 1, 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31' + ), + 'ArticleFeatured' => array( + array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31', + 'Featured' => array( + 'id' => 1, 'article_featured_id' => 1, 'category_id' => 1, 'published_date' => '2007-03-31 10:39:23', + 'end_date' => '2007-05-15 10:39:23', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31', + 'Category' => array( + 'id' => 1, 'parent_id' => 0, 'name' => 'Category 1', + 'created' => '2007-03-18 15:30:23', 'updated' => '2007-03-18 15:32:31' + ) + ), + 'Comment' => array( + array( + 'id' => 1, 'article_id' => 1, 'user_id' => 2, 'comment' => 'First Comment for First Article', + 'published' => 'Y', 'created' => '2007-03-18 10:45:23', 'updated' => '2007-03-18 10:47:31', + 'Article' => array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ), + 'Attachment' => array() + ), + array( + 'id' => 2, 'article_id' => 1, 'user_id' => 4, 'comment' => 'Second Comment for First Article', + 'published' => 'Y', 'created' => '2007-03-18 10:47:23', 'updated' => '2007-03-18 10:49:31', + 'Article' => array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ), + 'Attachment' => array() + ), + array( + 'id' => 3, 'article_id' => 1, 'user_id' => 1, 'comment' => 'Third Comment for First Article', + 'published' => 'Y', 'created' => '2007-03-18 10:49:23', 'updated' => '2007-03-18 10:51:31', + 'Article' => array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ), + 'Attachment' => array() + ), + array( + 'id' => 4, 'article_id' => 1, 'user_id' => 1, 'comment' => 'Fourth Comment for First Article', + 'published' => 'N', 'created' => '2007-03-18 10:51:23', 'updated' => '2007-03-18 10:53:31', + 'Article' => array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ), + 'Attachment' => array() + ) + ) + ), + array( + 'id' => 3, 'user_id' => 1, 'title' => 'Third Article', 'body' => 'Third Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:43:23', 'updated' => '2007-03-18 10:45:31', + 'Featured' => array(), + 'Comment' => array() + ) + ) + ), + array( + 'User' => array( + 'id' => 2, 'user' => 'nate', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:18:23', 'updated' => '2007-03-17 01:20:31' + ), + 'ArticleFeatured' => array() + ), + array( + 'User' => array( + 'id' => 3, 'user' => 'larry', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:20:23', 'updated' => '2007-03-17 01:22:31' + ), + 'ArticleFeatured' => array( + array( + 'id' => 2, 'user_id' => 3, 'title' => 'Second Article', 'body' => 'Second Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:41:23', 'updated' => '2007-03-18 10:43:31', + 'Featured' => array( + 'id' => 2, 'article_featured_id' => 2, 'category_id' => 1, 'published_date' => '2007-03-31 10:39:23', + 'end_date' => '2007-05-15 10:39:23', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31', + 'Category' => array( + 'id' => 1, 'parent_id' => 0, 'name' => 'Category 1', + 'created' => '2007-03-18 15:30:23', 'updated' => '2007-03-18 15:32:31' + ) + ), + 'Comment' => array( + array( + 'id' => 5, 'article_id' => 2, 'user_id' => 1, 'comment' => 'First Comment for Second Article', + 'published' => 'Y', 'created' => '2007-03-18 10:53:23', 'updated' => '2007-03-18 10:55:31', + 'Article' => array( + 'id' => 2, 'user_id' => 3, 'title' => 'Second Article', 'body' => 'Second Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:41:23', 'updated' => '2007-03-18 10:43:31' + ), + 'Attachment' => array( + 'id' => 1, 'comment_id' => 5, 'attachment' => 'attachment.zip', + 'created' => '2007-03-18 10:51:23', 'updated' => '2007-03-18 10:53:31' + ) + ), + array( + 'id' => 6, 'article_id' => 2, 'user_id' => 2, 'comment' => 'Second Comment for Second Article', + 'published' => 'Y', 'created' => '2007-03-18 10:55:23', 'updated' => '2007-03-18 10:57:31', + 'Article' => array( + 'id' => 2, 'user_id' => 3, 'title' => 'Second Article', 'body' => 'Second Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:41:23', 'updated' => '2007-03-18 10:43:31' + ), + 'Attachment' => array() + ) + ) + ) + ) + ), + array( + 'User' => array( + 'id' => 4, 'user' => 'garrett', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:22:23', 'updated' => '2007-03-17 01:24:31' + ), + 'ArticleFeatured' => array() + ) + ); + $this->assertEquals($expected, $result); + + $this->_assertBindings($this->User, array('hasMany' => array('ArticleFeatured'))); + $this->_assertBindings($this->User->ArticleFeatured, array('hasOne' => array('Featured'), 'hasMany' => array('Comment'))); + $this->_assertBindings($this->User->ArticleFeatured->Featured, array('belongsTo' => array('Category'))); + $this->_assertBindings($this->User->ArticleFeatured->Comment, array('belongsTo' => array('Article'), 'hasOne' => array('Attachment'))); + + $this->User->resetBindings(); + $this->_assertBindings($this->User, array('hasMany' => array('Article', 'ArticleFeatured', 'Comment'))); + $this->_assertBindings($this->User->ArticleFeatured, array('belongsTo' => array('User'), 'hasOne' => array('Featured'), 'hasMany' => array('Comment'), 'hasAndBelongsToMany' => array('Tag'))); + $this->_assertBindings($this->User->ArticleFeatured->Featured, array('belongsTo' => array('ArticleFeatured', 'Category'))); + $this->_assertBindings($this->User->ArticleFeatured->Comment, array('belongsTo' => array('Article', 'User'), 'hasOne' => array('Attachment'))); + + $result = $this->User->find('all', array('contain' => array('ArticleFeatured' => array('Featured' => 'Category', 'Comment' => array('Article', 'Attachment')), false))); + $expected = array( + array( + 'User' => array( + 'id' => 1, 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31' + ), + 'ArticleFeatured' => array( + array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31', + 'Featured' => array( + 'id' => 1, 'article_featured_id' => 1, 'category_id' => 1, 'published_date' => '2007-03-31 10:39:23', + 'end_date' => '2007-05-15 10:39:23', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31', + 'Category' => array( + 'id' => 1, 'parent_id' => 0, 'name' => 'Category 1', + 'created' => '2007-03-18 15:30:23', 'updated' => '2007-03-18 15:32:31' + ) + ), + 'Comment' => array( + array( + 'id' => 1, 'article_id' => 1, 'user_id' => 2, 'comment' => 'First Comment for First Article', + 'published' => 'Y', 'created' => '2007-03-18 10:45:23', 'updated' => '2007-03-18 10:47:31', + 'Article' => array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ), + 'Attachment' => array() + ), + array( + 'id' => 2, 'article_id' => 1, 'user_id' => 4, 'comment' => 'Second Comment for First Article', + 'published' => 'Y', 'created' => '2007-03-18 10:47:23', 'updated' => '2007-03-18 10:49:31', + 'Article' => array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ), + 'Attachment' => array() + ), + array( + 'id' => 3, 'article_id' => 1, 'user_id' => 1, 'comment' => 'Third Comment for First Article', + 'published' => 'Y', 'created' => '2007-03-18 10:49:23', 'updated' => '2007-03-18 10:51:31', + 'Article' => array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ), + 'Attachment' => array() + ), + array( + 'id' => 4, 'article_id' => 1, 'user_id' => 1, 'comment' => 'Fourth Comment for First Article', + 'published' => 'N', 'created' => '2007-03-18 10:51:23', 'updated' => '2007-03-18 10:53:31', + 'Article' => array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ), + 'Attachment' => array() + ) + ) + ), + array( + 'id' => 3, 'user_id' => 1, 'title' => 'Third Article', 'body' => 'Third Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:43:23', 'updated' => '2007-03-18 10:45:31', + 'Featured' => array(), + 'Comment' => array() + ) + ) + ), + array( + 'User' => array( + 'id' => 2, 'user' => 'nate', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:18:23', 'updated' => '2007-03-17 01:20:31' + ), + 'ArticleFeatured' => array() + ), + array( + 'User' => array( + 'id' => 3, 'user' => 'larry', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:20:23', 'updated' => '2007-03-17 01:22:31' + ), + 'ArticleFeatured' => array( + array( + 'id' => 2, 'user_id' => 3, 'title' => 'Second Article', 'body' => 'Second Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:41:23', 'updated' => '2007-03-18 10:43:31', + 'Featured' => array( + 'id' => 2, 'article_featured_id' => 2, 'category_id' => 1, 'published_date' => '2007-03-31 10:39:23', + 'end_date' => '2007-05-15 10:39:23', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31', + 'Category' => array( + 'id' => 1, 'parent_id' => 0, 'name' => 'Category 1', + 'created' => '2007-03-18 15:30:23', 'updated' => '2007-03-18 15:32:31' + ) + ), + 'Comment' => array( + array( + 'id' => 5, 'article_id' => 2, 'user_id' => 1, 'comment' => 'First Comment for Second Article', + 'published' => 'Y', 'created' => '2007-03-18 10:53:23', 'updated' => '2007-03-18 10:55:31', + 'Article' => array( + 'id' => 2, 'user_id' => 3, 'title' => 'Second Article', 'body' => 'Second Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:41:23', 'updated' => '2007-03-18 10:43:31' + ), + 'Attachment' => array( + 'id' => 1, 'comment_id' => 5, 'attachment' => 'attachment.zip', + 'created' => '2007-03-18 10:51:23', 'updated' => '2007-03-18 10:53:31' + ) + ), + array( + 'id' => 6, 'article_id' => 2, 'user_id' => 2, 'comment' => 'Second Comment for Second Article', + 'published' => 'Y', 'created' => '2007-03-18 10:55:23', 'updated' => '2007-03-18 10:57:31', + 'Article' => array( + 'id' => 2, 'user_id' => 3, 'title' => 'Second Article', 'body' => 'Second Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:41:23', 'updated' => '2007-03-18 10:43:31' + ), + 'Attachment' => array() + ) + ) + ) + ) + ), + array( + 'User' => array( + 'id' => 4, 'user' => 'garrett', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:22:23', 'updated' => '2007-03-17 01:24:31' + ), + 'ArticleFeatured' => array() + ) + ); + $this->assertEquals($expected, $result); + + $this->_assertBindings($this->User, array('hasMany' => array('ArticleFeatured'))); + $this->_assertBindings($this->User->ArticleFeatured, array('hasOne' => array('Featured'), 'hasMany' => array('Comment'))); + $this->_assertBindings($this->User->ArticleFeatured->Featured, array('belongsTo' => array('Category'))); + $this->_assertBindings($this->User->ArticleFeatured->Comment, array('belongsTo' => array('Article'), 'hasOne' => array('Attachment'))); + + $this->User->resetBindings(); + $this->_assertBindings($this->User, array('hasMany' => array('Article', 'ArticleFeatured', 'Comment'))); + $this->_assertBindings($this->User->ArticleFeatured, array('belongsTo' => array('User'), 'hasOne' => array('Featured'), 'hasMany' => array('Comment'), 'hasAndBelongsToMany' => array('Tag'))); + $this->_assertBindings($this->User->ArticleFeatured->Featured, array('belongsTo' => array('ArticleFeatured', 'Category'))); + $this->_assertBindings($this->User->ArticleFeatured->Comment, array('belongsTo' => array('Article', 'User'), 'hasOne' => array('Attachment'))); + + $result = $this->User->find('all', array('reset' => false, 'contain' => array('ArticleFeatured' => array('Featured' => 'Category', 'Comment' => 'Attachment'), 'Article'))); + $expected = array( + array( + 'User' => array( + 'id' => 1, 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31' + ), + 'Article' => array( + array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ), + array( + 'id' => 3, 'user_id' => 1, 'title' => 'Third Article', 'body' => 'Third Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:43:23', 'updated' => '2007-03-18 10:45:31' + ) + ), + 'ArticleFeatured' => array( + array( + 'id' => 1, 'user_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31', + 'Featured' => array( + 'id' => 1, 'article_featured_id' => 1, 'category_id' => 1, 'published_date' => '2007-03-31 10:39:23', + 'end_date' => '2007-05-15 10:39:23', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31', + 'Category' => array( + 'id' => 1, 'parent_id' => 0, 'name' => 'Category 1', + 'created' => '2007-03-18 15:30:23', 'updated' => '2007-03-18 15:32:31' + ) + ), + 'Comment' => array( + array( + 'id' => 1, 'article_id' => 1, 'user_id' => 2, 'comment' => 'First Comment for First Article', + 'published' => 'Y', 'created' => '2007-03-18 10:45:23', 'updated' => '2007-03-18 10:47:31', + 'Attachment' => array() + ), + array( + 'id' => 2, 'article_id' => 1, 'user_id' => 4, 'comment' => 'Second Comment for First Article', + 'published' => 'Y', 'created' => '2007-03-18 10:47:23', 'updated' => '2007-03-18 10:49:31', + 'Attachment' => array() + ), + array( + 'id' => 3, 'article_id' => 1, 'user_id' => 1, 'comment' => 'Third Comment for First Article', + 'published' => 'Y', 'created' => '2007-03-18 10:49:23', 'updated' => '2007-03-18 10:51:31', + 'Attachment' => array() + ), + array( + 'id' => 4, 'article_id' => 1, 'user_id' => 1, 'comment' => 'Fourth Comment for First Article', + 'published' => 'N', 'created' => '2007-03-18 10:51:23', 'updated' => '2007-03-18 10:53:31', + 'Attachment' => array() + ) + ) + ), + array( + 'id' => 3, 'user_id' => 1, 'title' => 'Third Article', 'body' => 'Third Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:43:23', 'updated' => '2007-03-18 10:45:31', + 'Featured' => array(), + 'Comment' => array() + ) + ) + ), + array( + 'User' => array( + 'id' => 2, 'user' => 'nate', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:18:23', 'updated' => '2007-03-17 01:20:31' + ), + 'Article' => array(), + 'ArticleFeatured' => array() + ), + array( + 'User' => array( + 'id' => 3, 'user' => 'larry', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:20:23', 'updated' => '2007-03-17 01:22:31' + ), + 'Article' => array( + array( + 'id' => 2, 'user_id' => 3, 'title' => 'Second Article', 'body' => 'Second Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:41:23', 'updated' => '2007-03-18 10:43:31' + ) + ), + 'ArticleFeatured' => array( + array( + 'id' => 2, 'user_id' => 3, 'title' => 'Second Article', 'body' => 'Second Article Body', + 'published' => 'Y', 'created' => '2007-03-18 10:41:23', 'updated' => '2007-03-18 10:43:31', + 'Featured' => array( + 'id' => 2, 'article_featured_id' => 2, 'category_id' => 1, 'published_date' => '2007-03-31 10:39:23', + 'end_date' => '2007-05-15 10:39:23', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31', + 'Category' => array( + 'id' => 1, 'parent_id' => 0, 'name' => 'Category 1', + 'created' => '2007-03-18 15:30:23', 'updated' => '2007-03-18 15:32:31' + ) + ), + 'Comment' => array( + array( + 'id' => 5, 'article_id' => 2, 'user_id' => 1, 'comment' => 'First Comment for Second Article', + 'published' => 'Y', 'created' => '2007-03-18 10:53:23', 'updated' => '2007-03-18 10:55:31', + 'Attachment' => array( + 'id' => 1, 'comment_id' => 5, 'attachment' => 'attachment.zip', + 'created' => '2007-03-18 10:51:23', 'updated' => '2007-03-18 10:53:31' + ) + ), + array( + 'id' => 6, 'article_id' => 2, 'user_id' => 2, 'comment' => 'Second Comment for Second Article', + 'published' => 'Y', 'created' => '2007-03-18 10:55:23', 'updated' => '2007-03-18 10:57:31', + 'Attachment' => array() + ) + ) + ) + ) + ), + array( + 'User' => array( + 'id' => 4, 'user' => 'garrett', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:22:23', 'updated' => '2007-03-17 01:24:31' + ), + 'Article' => array(), + 'ArticleFeatured' => array() + ) + ); + $this->assertEquals($expected, $result); + + $this->_assertBindings($this->User, array('hasMany' => array('Article', 'ArticleFeatured'))); + $this->_assertBindings($this->User->Article); + $this->_assertBindings($this->User->ArticleFeatured, array('hasOne' => array('Featured'), 'hasMany' => array('Comment'))); + $this->_assertBindings($this->User->ArticleFeatured->Featured, array('belongsTo' => array('Category'))); + $this->_assertBindings($this->User->ArticleFeatured->Comment, array('hasOne' => array('Attachment'))); + + $this->User->resetBindings(); + $this->_assertBindings($this->User, array('hasMany' => array('Article', 'ArticleFeatured', 'Comment'))); + $this->_assertBindings($this->User->Article, array('belongsTo' => array('User'), 'hasMany' => array('Comment'), 'hasAndBelongsToMany' => array('Tag'))); + $this->_assertBindings($this->User->ArticleFeatured, array('belongsTo' => array('User'), 'hasOne' => array('Featured'), 'hasMany' => array('Comment'), 'hasAndBelongsToMany' => array('Tag'))); + $this->_assertBindings($this->User->ArticleFeatured->Featured, array('belongsTo' => array('ArticleFeatured', 'Category'))); + $this->_assertBindings($this->User->ArticleFeatured->Comment, array('belongsTo' => array('Article', 'User'), 'hasOne' => array('Attachment'))); + } + +/** + * testEmbeddedFindFields method + * + * @return void + */ + public function testEmbeddedFindFields() { + $result = $this->Article->find('all', array( + 'contain' => array('User(user)'), + 'fields' => array('title'), + 'order' => array('Article.id' => 'ASC') + )); + $expected = array( + array('Article' => array('title' => 'First Article'), 'User' => array('user' => 'mariano', 'id' => 1)), + array('Article' => array('title' => 'Second Article'), 'User' => array('user' => 'larry', 'id' => 3)), + array('Article' => array('title' => 'Third Article'), 'User' => array('user' => 'mariano', 'id' => 1)), + ); + $this->assertEquals($expected, $result); + + $result = $this->Article->find('all', array( + 'contain' => array('User(id, user)'), + 'fields' => array('title'), + 'order' => array('Article.id' => 'ASC') + )); + $expected = array( + array('Article' => array('title' => 'First Article'), 'User' => array('user' => 'mariano', 'id' => 1)), + array('Article' => array('title' => 'Second Article'), 'User' => array('user' => 'larry', 'id' => 3)), + array('Article' => array('title' => 'Third Article'), 'User' => array('user' => 'mariano', 'id' => 1)), + ); + $this->assertEquals($expected, $result); + + $result = $this->Article->find('all', array( + 'contain' => array( + 'Comment(comment, published)' => 'Attachment(attachment)', 'User(user)' + ), + 'fields' => array('title'), + 'order' => array('Article.id' => 'ASC') + )); + if (!empty($result)) { + foreach ($result as $i => $article) { + foreach ($article['Comment'] as $j => $comment) { + $result[$i]['Comment'][$j] = array_diff_key($comment, array('id' => true)); + } + } + } + $expected = array( + array( + 'Article' => array('title' => 'First Article', 'id' => 1), + 'User' => array('user' => 'mariano', 'id' => 1), + 'Comment' => array( + array('comment' => 'First Comment for First Article', 'published' => 'Y', 'article_id' => 1, 'Attachment' => array()), + array('comment' => 'Second Comment for First Article', 'published' => 'Y', 'article_id' => 1, 'Attachment' => array()), + array('comment' => 'Third Comment for First Article', 'published' => 'Y', 'article_id' => 1, 'Attachment' => array()), + array('comment' => 'Fourth Comment for First Article', 'published' => 'N', 'article_id' => 1, 'Attachment' => array()), + ) + ), + array( + 'Article' => array('title' => 'Second Article', 'id' => 2), + 'User' => array('user' => 'larry', 'id' => 3), + 'Comment' => array( + array('comment' => 'First Comment for Second Article', 'published' => 'Y', 'article_id' => 2, 'Attachment' => array( + 'attachment' => 'attachment.zip', 'id' => 1 + )), + array('comment' => 'Second Comment for Second Article', 'published' => 'Y', 'article_id' => 2, 'Attachment' => array()) + ) + ), + array( + 'Article' => array('title' => 'Third Article', 'id' => 3), + 'User' => array('user' => 'mariano', 'id' => 1), + 'Comment' => array() + ), + ); + $this->assertEquals($expected, $result); + } + +/** + * test that hasOne and belongsTo fields act the same in a contain array. + * + * @return void + */ + public function testHasOneFieldsInContain() { + $this->Article->unbindModel(array( + 'hasMany' => array('Comment') + ), true); + unset($this->Article->Comment); + $this->Article->bindModel(array( + 'hasOne' => array('Comment') + )); + + $result = $this->Article->find('all', array( + 'fields' => array('title', 'body'), + 'contain' => array( + 'Comment' => array( + 'fields' => array('comment') + ), + 'User' => array( + 'fields' => array('user') + ) + ) + )); + $this->assertTrue(isset($result[0]['Article']['title']), 'title missing %s'); + $this->assertTrue(isset($result[0]['Article']['body']), 'body missing %s'); + $this->assertTrue(isset($result[0]['Comment']['comment']), 'comment missing %s'); + $this->assertTrue(isset($result[0]['User']['user']), 'body missing %s'); + $this->assertFalse(isset($result[0]['Comment']['published']), 'published found %s'); + $this->assertFalse(isset($result[0]['User']['password']), 'password found %s'); + } + +/** + * testFindConditionalBinding method + * + * @return void + */ + public function testFindConditionalBinding() { + $this->Article->contain(array( + 'User(user)', + 'Tag' => array( + 'fields' => array('tag', 'created'), + 'conditions' => array('created >=' => '2007-03-18 12:24') + ) + )); + $result = $this->Article->find('all', array('fields' => array('title'), 'order' => array('Article.id' => 'ASC'))); + $expected = array( + array( + 'Article' => array('id' => 1, 'title' => 'First Article'), + 'User' => array('id' => 1, 'user' => 'mariano'), + 'Tag' => array(array('tag' => 'tag2', 'created' => '2007-03-18 12:24:23')) + ), + array( + 'Article' => array('id' => 2, 'title' => 'Second Article'), + 'User' => array('id' => 3, 'user' => 'larry'), + 'Tag' => array(array('tag' => 'tag3', 'created' => '2007-03-18 12:26:23')) + ), + array( + 'Article' => array('id' => 3, 'title' => 'Third Article'), + 'User' => array('id' => 1, 'user' => 'mariano'), + 'Tag' => array() + ) + ); + $this->assertEquals($expected, $result); + + $this->Article->contain(array('User(id,user)', 'Tag' => array('fields' => array('tag', 'created')))); + $result = $this->Article->find('all', array('fields' => array('title'), 'order' => array('Article.id' => 'ASC'))); + $expected = array( + array( + 'Article' => array('id' => 1, 'title' => 'First Article'), + 'User' => array('id' => 1, 'user' => 'mariano'), + 'Tag' => array( + array('tag' => 'tag1', 'created' => '2007-03-18 12:22:23'), + array('tag' => 'tag2', 'created' => '2007-03-18 12:24:23') + ) + ), + array( + 'Article' => array('id' => 2, 'title' => 'Second Article'), + 'User' => array('id' => 3, 'user' => 'larry'), + 'Tag' => array( + array('tag' => 'tag1', 'created' => '2007-03-18 12:22:23'), + array('tag' => 'tag3', 'created' => '2007-03-18 12:26:23') + ) + ), + array( + 'Article' => array('id' => 3, 'title' => 'Third Article'), + 'User' => array('id' => 1, 'user' => 'mariano'), + 'Tag' => array() + ) + ); + $this->assertEquals($expected, $result); + + $result = $this->Article->find('all', array( + 'fields' => array('title'), + 'contain' => array('User(id,user)', 'Tag' => array('fields' => array('tag', 'created'))), + 'order' => array('Article.id' => 'ASC') + )); + $expected = array( + array( + 'Article' => array('id' => 1, 'title' => 'First Article'), + 'User' => array('id' => 1, 'user' => 'mariano'), + 'Tag' => array( + array('tag' => 'tag1', 'created' => '2007-03-18 12:22:23'), + array('tag' => 'tag2', 'created' => '2007-03-18 12:24:23') + ) + ), + array( + 'Article' => array('id' => 2, 'title' => 'Second Article'), + 'User' => array('id' => 3, 'user' => 'larry'), + 'Tag' => array( + array('tag' => 'tag1', 'created' => '2007-03-18 12:22:23'), + array('tag' => 'tag3', 'created' => '2007-03-18 12:26:23') + ) + ), + array( + 'Article' => array('id' => 3, 'title' => 'Third Article'), + 'User' => array('id' => 1, 'user' => 'mariano'), + 'Tag' => array() + ) + ); + $this->assertEquals($expected, $result); + + $this->Article->contain(array( + 'User(id,user)', + 'Tag' => array( + 'fields' => array('tag', 'created'), + 'conditions' => array('created >=' => '2007-03-18 12:24') + ) + )); + $result = $this->Article->find('all', array('fields' => array('title'), 'order' => array('Article.id' => 'ASC'))); + $expected = array( + array( + 'Article' => array('id' => 1, 'title' => 'First Article'), + 'User' => array('id' => 1, 'user' => 'mariano'), + 'Tag' => array(array('tag' => 'tag2', 'created' => '2007-03-18 12:24:23')) + ), + array( + 'Article' => array('id' => 2, 'title' => 'Second Article'), + 'User' => array('id' => 3, 'user' => 'larry'), + 'Tag' => array(array('tag' => 'tag3', 'created' => '2007-03-18 12:26:23')) + ), + array( + 'Article' => array('id' => 3, 'title' => 'Third Article'), + 'User' => array('id' => 1, 'user' => 'mariano'), + 'Tag' => array() + ) + ); + $this->assertEquals($expected, $result); + + $this->assertTrue(empty($this->User->Article->hasAndBelongsToMany['Tag']['conditions'])); + + $result = $this->User->find('all', array('contain' => array( + 'Article.Tag' => array('conditions' => array('created >=' => '2007-03-18 12:24')) + ))); + + $this->assertTrue(Set::matches('/User[id=1]', $result)); + $this->assertFalse(Set::matches('/Article[id=1]/Tag[id=1]', $result)); + $this->assertTrue(Set::matches('/Article[id=1]/Tag[id=2]', $result)); + $this->assertTrue(empty($this->User->Article->hasAndBelongsToMany['Tag']['conditions'])); + + $this->assertTrue(empty($this->User->Article->hasAndBelongsToMany['Tag']['order'])); + + $result = $this->User->find('all', array('contain' => array( + 'Article.Tag' => array('order' => 'created DESC') + ))); + + $this->assertTrue(Set::matches('/User[id=1]', $result)); + $this->assertTrue(Set::matches('/Article[id=1]/Tag[id=1]', $result)); + $this->assertTrue(Set::matches('/Article[id=1]/Tag[id=2]', $result)); + $this->assertTrue(empty($this->User->Article->hasAndBelongsToMany['Tag']['order'])); + } + +/** + * testOtherFinds method + * + * @return void + */ + public function testOtherFinds() { + $result = $this->Article->find('count'); + $expected = 3; + $this->assertEquals($expected, $result); + + $result = $this->Article->find('count', array('conditions' => array('Article.id >' => '1'))); + $expected = 2; + $this->assertEquals($expected, $result); + + $result = $this->Article->find('count', array('contain' => array())); + $expected = 3; + $this->assertEquals($expected, $result); + + $this->Article->contain(array('User(id,user)', 'Tag' => array('fields' => array('tag', 'created'), 'conditions' => array('created >=' => '2007-03-18 12:24')))); + $result = $this->Article->find('first', array('fields' => array('title'))); + $expected = array( + 'Article' => array('id' => 1, 'title' => 'First Article'), + 'User' => array('id' => 1, 'user' => 'mariano'), + 'Tag' => array(array('tag' => 'tag2', 'created' => '2007-03-18 12:24:23')) + ); + $this->assertEquals($expected, $result); + + $this->Article->contain(array('User(id,user)', 'Tag' => array('fields' => array('tag', 'created')))); + $result = $this->Article->find('first', array('fields' => array('title'))); + $expected = array( + 'Article' => array('id' => 1, 'title' => 'First Article'), + 'User' => array('id' => 1, 'user' => 'mariano'), + 'Tag' => array( + array('tag' => 'tag1', 'created' => '2007-03-18 12:22:23'), + array('tag' => 'tag2', 'created' => '2007-03-18 12:24:23') + ) + ); + $this->assertEquals($expected, $result); + + $result = $this->Article->find('first', array( + 'fields' => array('title'), + 'order' => 'Article.id DESC', + 'contain' => array('User(id,user)', 'Tag' => array('fields' => array('tag', 'created'))) + )); + $expected = array( + 'Article' => array('id' => 3, 'title' => 'Third Article'), + 'User' => array('id' => 1, 'user' => 'mariano'), + 'Tag' => array() + ); + $this->assertEquals($expected, $result); + + $result = $this->Article->find('list', array( + 'contain' => array('User(id,user)'), + 'fields' => array('Article.id', 'Article.title') + )); + $expected = array( + 1 => 'First Article', + 2 => 'Second Article', + 3 => 'Third Article' + ); + $this->assertEquals($expected, $result); + } + +/** + * testOriginalAssociations method + * + * @return void + */ + public function testOriginalAssociations() { + $this->Article->Comment->Behaviors->attach('Containable'); + + $options = array( + 'conditions' => array( + 'Comment.published' => 'Y', + ), + 'contain' => 'User', + 'recursive' => 1 + ); + + $firstResult = $this->Article->Comment->find('all', $options); + + $dummyResult = $this->Article->Comment->find('all', array( + 'conditions' => array( + 'User.user' => 'mariano' + ), + 'fields' => array('User.password'), + 'contain' => array('User.password'), + )); + + $result = $this->Article->Comment->find('all', $options); + $this->assertEquals($firstResult, $result); + + $this->Article->unbindModel(array('hasMany' => array('Comment'), 'belongsTo' => array('User'), 'hasAndBelongsToMany' => array('Tag')), false); + $this->Article->bindModel(array('hasMany' => array('Comment'), 'belongsTo' => array('User')), false); + + $r = $this->Article->find('all', array('contain' => array('Comment(comment)', 'User(user)'), 'fields' => array('title'))); + $this->assertTrue(Set::matches('/Article[id=1]', $r)); + $this->assertTrue(Set::matches('/User[id=1]', $r)); + $this->assertTrue(Set::matches('/Comment[article_id=1]', $r)); + $this->assertFalse(Set::matches('/Comment[id=1]', $r)); + + $r = $this->Article->find('all'); + $this->assertTrue(Set::matches('/Article[id=1]', $r)); + $this->assertTrue(Set::matches('/User[id=1]', $r)); + $this->assertTrue(Set::matches('/Comment[article_id=1]', $r)); + $this->assertTrue(Set::matches('/Comment[id=1]', $r)); + + $this->Article->bindModel(array('hasAndBelongsToMany' => array('Tag')), false); + + $this->Article->contain(false, array('User(id,user)', 'Comment' => array('fields' => array('comment'), 'conditions' => array('created >=' => '2007-03-18 10:49')))); + $result = $this->Article->find('all', array('fields' => array('title'), 'limit' => 1, 'page' => 1, 'order' => 'Article.id ASC')); + $expected = array(array( + 'Article' => array('id' => 1, 'title' => 'First Article'), + 'User' => array('id' => 1, 'user' => 'mariano'), + 'Comment' => array( + array('comment' => 'Third Comment for First Article', 'article_id' => 1), + array('comment' => 'Fourth Comment for First Article', 'article_id' => 1) + ) + )); + $this->assertEquals($expected, $result); + + $result = $this->Article->find('all', array('fields' => array('title', 'User.id', 'User.user'), 'limit' => 1, 'page' => 2, 'order' => 'Article.id ASC')); + $expected = array(array( + 'Article' => array('id' => 2, 'title' => 'Second Article'), + 'User' => array('id' => 3, 'user' => 'larry'), + 'Comment' => array( + array('comment' => 'First Comment for Second Article', 'article_id' => 2), + array('comment' => 'Second Comment for Second Article', 'article_id' => 2) + ) + )); + $this->assertEquals($expected, $result); + + $result = $this->Article->find('all', array('fields' => array('title', 'User.id', 'User.user'), 'limit' => 1, 'page' => 3, 'order' => 'Article.id ASC')); + $expected = array(array( + 'Article' => array('id' => 3, 'title' => 'Third Article'), + 'User' => array('id' => 1, 'user' => 'mariano'), + 'Comment' => array() + )); + $this->assertEquals($expected, $result); + + $this->Article->contain(false, array('User' => array('fields' => 'user'), 'Comment')); + $result = $this->Article->find('all'); + $this->assertTrue(Set::matches('/Article[id=1]', $result)); + $this->assertTrue(Set::matches('/User[user=mariano]', $result)); + $this->assertTrue(Set::matches('/Comment[article_id=1]', $result)); + $this->Article->resetBindings(); + + $this->Article->contain(false, array('User' => array('fields' => array('user')), 'Comment')); + $result = $this->Article->find('all'); + $this->assertTrue(Set::matches('/Article[id=1]', $result)); + $this->assertTrue(Set::matches('/User[user=mariano]', $result)); + $this->assertTrue(Set::matches('/Comment[article_id=1]', $result)); + $this->Article->resetBindings(); + } + +/** + * testResetAddedAssociation method + * + */ + public function testResetAddedAssociation() { + $this->assertTrue(empty($this->Article->hasMany['ArticlesTag'])); + + $this->Article->bindModel(array( + 'hasMany' => array('ArticlesTag') + )); + $this->assertTrue(!empty($this->Article->hasMany['ArticlesTag'])); + + $result = $this->Article->find('first', array( + 'conditions' => array('Article.id' => 1), + 'contain' => array('ArticlesTag') + )); + + $expected = array('Article', 'ArticlesTag'); + $this->assertTrue(!empty($result)); + $this->assertEquals('First Article', $result['Article']['title']); + $this->assertTrue(!empty($result['ArticlesTag'])); + $this->assertEquals($expected, array_keys($result)); + + $this->assertTrue(empty($this->Article->hasMany['ArticlesTag'])); + + $this->JoinA = ClassRegistry::init('JoinA'); + $this->JoinB = ClassRegistry::init('JoinB'); + $this->JoinC = ClassRegistry::init('JoinC'); + + $this->JoinA->Behaviors->attach('Containable'); + $this->JoinB->Behaviors->attach('Containable'); + $this->JoinC->Behaviors->attach('Containable'); + + $this->JoinA->JoinB->find('all', array('contain' => array('JoinA'))); + $this->JoinA->bindModel(array('hasOne' => array('JoinAsJoinC' => array('joinTable' => 'as_cs'))), false); + $result = $this->JoinA->hasOne; + $this->JoinA->find('all'); + $resultAfter = $this->JoinA->hasOne; + $this->assertEquals($result, $resultAfter); + } + +/** + * testResetAssociation method + * + */ + public function testResetAssociation() { + $this->Article->Behaviors->attach('Containable'); + $this->Article->Comment->Behaviors->attach('Containable'); + $this->Article->User->Behaviors->attach('Containable'); + + $initialOptions = array( + 'conditions' => array( + 'Comment.published' => 'Y', + ), + 'contain' => 'User', + 'recursive' => 1, + ); + + $initialModels = $this->Article->Comment->find('all', $initialOptions); + + $findOptions = array( + 'conditions' => array( + 'User.user' => 'mariano', + ), + 'fields' => array('User.password'), + 'contain' => array('User.password') + ); + $result = $this->Article->Comment->find('all', $findOptions); + $result = $this->Article->Comment->find('all', $initialOptions); + $this->assertEquals($initialModels, $result); + } + +/** + * testResetDeeperHasOneAssociations method + * + */ + public function testResetDeeperHasOneAssociations() { + $this->Article->User->unbindModel(array( + 'hasMany' => array('ArticleFeatured', 'Comment') + ), false); + $userHasOne = array('hasOne' => array('ArticleFeatured', 'Comment')); + + $this->Article->User->bindModel($userHasOne, false); + $expected = $this->Article->User->hasOne; + $this->Article->find('all'); + $this->assertEquals($expected, $this->Article->User->hasOne); + + $this->Article->User->bindModel($userHasOne, false); + $expected = $this->Article->User->hasOne; + $this->Article->find('all', array( + 'contain' => array( + 'User' => array('ArticleFeatured', 'Comment') + ) + )); + $this->assertEquals($expected, $this->Article->User->hasOne); + + $this->Article->User->bindModel($userHasOne, false); + $expected = $this->Article->User->hasOne; + $this->Article->find('all', array( + 'contain' => array( + 'User' => array( + 'ArticleFeatured', + 'Comment' => array('fields' => array('created')) + ) + ) + )); + $this->assertEquals($expected, $this->Article->User->hasOne); + + $this->Article->User->bindModel($userHasOne, false); + $expected = $this->Article->User->hasOne; + $this->Article->find('all', array( + 'contain' => array( + 'User' => array( + 'Comment' => array('fields' => array('created')) + ) + ) + )); + $this->assertEquals($expected, $this->Article->User->hasOne); + + $this->Article->User->bindModel($userHasOne, false); + $expected = $this->Article->User->hasOne; + $this->Article->find('all', array( + 'contain' => array( + 'User.ArticleFeatured' => array( + 'conditions' => array('ArticleFeatured.published' => 'Y') + ), + 'User.Comment' + ) + )); + $this->assertEquals($expected, $this->Article->User->hasOne); + } + +/** + * testResetMultipleHabtmAssociations method + * + */ + public function testResetMultipleHabtmAssociations() { + $articleHabtm = array( + 'hasAndBelongsToMany' => array( + 'Tag' => array( + 'className' => 'Tag', + 'joinTable' => 'articles_tags', + 'foreignKey' => 'article_id', + 'associationForeignKey' => 'tag_id' + ), + 'ShortTag' => array( + 'className' => 'Tag', + 'joinTable' => 'articles_tags', + 'foreignKey' => 'article_id', + 'associationForeignKey' => 'tag_id', + // LENGHT function mysql-only, using LIKE does almost the same + 'conditions' => "ShortTag.tag LIKE '???'" + ) + ) + ); + + $this->Article->resetBindings(); + $this->Article->bindModel($articleHabtm, false); + $expected = $this->Article->hasAndBelongsToMany; + $this->Article->find('all'); + $this->assertEquals($expected, $this->Article->hasAndBelongsToMany); + + $this->Article->resetBindings(); + $this->Article->bindModel($articleHabtm, false); + $expected = $this->Article->hasAndBelongsToMany; + $this->Article->find('all', array('contain' => 'Tag.tag')); + $this->assertEquals($expected, $this->Article->hasAndBelongsToMany); + + $this->Article->resetBindings(); + $this->Article->bindModel($articleHabtm, false); + $expected = $this->Article->hasAndBelongsToMany; + $this->Article->find('all', array('contain' => 'Tag')); + $this->assertEquals($expected, $this->Article->hasAndBelongsToMany); + + $this->Article->resetBindings(); + $this->Article->bindModel($articleHabtm, false); + $expected = $this->Article->hasAndBelongsToMany; + $this->Article->find('all', array('contain' => array('Tag' => array('fields' => array(null))))); + $this->assertEquals($expected, $this->Article->hasAndBelongsToMany); + + $this->Article->resetBindings(); + $this->Article->bindModel($articleHabtm, false); + $expected = $this->Article->hasAndBelongsToMany; + $this->Article->find('all', array('contain' => array('Tag' => array('fields' => array('Tag.tag'))))); + $this->assertEquals($expected, $this->Article->hasAndBelongsToMany); + + $this->Article->resetBindings(); + $this->Article->bindModel($articleHabtm, false); + $expected = $this->Article->hasAndBelongsToMany; + $this->Article->find('all', array('contain' => array('Tag' => array('fields' => array('Tag.tag', 'Tag.created'))))); + $this->assertEquals($expected, $this->Article->hasAndBelongsToMany); + + $this->Article->resetBindings(); + $this->Article->bindModel($articleHabtm, false); + $expected = $this->Article->hasAndBelongsToMany; + $this->Article->find('all', array('contain' => 'ShortTag.tag')); + $this->assertEquals($expected, $this->Article->hasAndBelongsToMany); + + $this->Article->resetBindings(); + $this->Article->bindModel($articleHabtm, false); + $expected = $this->Article->hasAndBelongsToMany; + $this->Article->find('all', array('contain' => 'ShortTag')); + $this->assertEquals($expected, $this->Article->hasAndBelongsToMany); + + $this->Article->resetBindings(); + $this->Article->bindModel($articleHabtm, false); + $expected = $this->Article->hasAndBelongsToMany; + $this->Article->find('all', array('contain' => array('ShortTag' => array('fields' => array(null))))); + $this->assertEquals($expected, $this->Article->hasAndBelongsToMany); + + $this->Article->resetBindings(); + $this->Article->bindModel($articleHabtm, false); + $expected = $this->Article->hasAndBelongsToMany; + $this->Article->find('all', array('contain' => array('ShortTag' => array('fields' => array('ShortTag.tag'))))); + $this->assertEquals($expected, $this->Article->hasAndBelongsToMany); + + $this->Article->resetBindings(); + $this->Article->bindModel($articleHabtm, false); + $expected = $this->Article->hasAndBelongsToMany; + $this->Article->find('all', array('contain' => array('ShortTag' => array('fields' => array('ShortTag.tag', 'ShortTag.created'))))); + $this->assertEquals($expected, $this->Article->hasAndBelongsToMany); + } + +/** + * test that bindModel and unbindModel work with find() calls in between. + */ + public function testBindMultipleTimesWithFind() { + $binding = array( + 'hasOne' => array( + 'ArticlesTag' => array( + 'foreignKey' => false, + 'type' => 'INNER', + 'conditions' => array( + 'ArticlesTag.article_id = Article.id' + ) + ), + 'Tag' => array( + 'type' => 'INNER', + 'foreignKey' => false, + 'conditions' => array( + 'ArticlesTag.tag_id = Tag.id' + ) + ) + ) + ); + $this->Article->unbindModel(array('hasAndBelongsToMany' => array('Tag'))); + $this->Article->bindModel($binding); + $result = $this->Article->find('all', array('limit' => 1, 'contain' => array('ArticlesTag', 'Tag'))); + + $this->Article->unbindModel(array('hasAndBelongsToMany' => array('Tag'))); + $this->Article->bindModel($binding); + $result = $this->Article->find('all', array('limit' => 1, 'contain' => array('ArticlesTag', 'Tag'))); + + $associated = $this->Article->getAssociated(); + $this->assertEquals('hasAndBelongsToMany', $associated['Tag']); + $this->assertFalse(isset($associated['ArticleTag'])); + } + +/** + * test that autoFields doesn't splice in fields from other databases. + * + * @return void + */ + public function testAutoFieldsWithMultipleDatabases() { + $config = new DATABASE_CONFIG(); + + $this->skipIf( + !isset($config->test) || !isset($config->test2), + 'Primary and secondary test databases not configured, ' . + 'skipping cross-database join tests. ' . + ' To run these tests, you must define $test and $test2 ' . + 'in your database configuration.' + ); + + $db = ConnectionManager::getDataSource('test2'); + $this->fixtureManager->loadSingle('User', $db); + + $this->Article->User->setDataSource('test2'); + + $result = $this->Article->find('all', array( + 'fields' => array('Article.title'), + 'contain' => array('User') + )); + $this->assertTrue(isset($result[0]['Article'])); + $this->assertTrue(isset($result[0]['User'])); + } + +/** + * test that autoFields doesn't splice in columns that aren't part of the join. + * + * @return void + */ + public function testAutoFieldsWithRecursiveNegativeOne() { + $this->Article->recursive = -1; + $result = $this->Article->field('title', array('Article.title' => 'First Article')); + $this->assertNoErrors(); + $this->assertEquals('First Article', $result, 'Field is wrong'); + } + +/** + * test that find(all) doesn't return incorrect values when mixed with containable. + * + * @return void + */ + public function testFindAllReturn() { + $result = $this->Article->find('all', array( + 'conditions' => array('Article.id' => 999999999) + )); + $this->assertEmpty($result, 'Should be empty.'); + } + +/** + * testLazyLoad method + * + * @return void + */ + public function testLazyLoad() { + // Local set up + $this->User = ClassRegistry::init('User'); + $this->User->bindModel(array( + 'hasMany' => array('Article', 'ArticleFeatured', 'Comment') + ), false); + + try { + $this->User->find('first', array( + 'contain' => 'Comment', + 'lazyLoad' => true + )); + } catch (Exception $e) { + $exceptions = true; + } + $this->assertTrue(empty($exceptions)); + } + +/** + * _containments method + * + * @param Model $Model + * @param array $contain + * @return void + */ + protected function _containments($Model, $contain = array()) { + if (!is_array($Model)) { + $result = $Model->containments($contain); + return $this->_containments($result['models']); + } else { + $result = $Model; + foreach ($result as $i => $containment) { + $result[$i] = array_diff_key($containment, array('instance' => true)); + } + } + return $result; + } + +/** + * _assertBindings method + * + * @param Model $Model + * @param array $expected + * @return void + */ + protected function _assertBindings(Model $Model, $expected = array()) { + $expected = array_merge(array( + 'belongsTo' => array(), + 'hasOne' => array(), + 'hasMany' => array(), + 'hasAndBelongsToMany' => array() + ), $expected); + foreach ($expected as $binding => $expect) { + $this->assertEquals(array_keys($Model->$binding), $expect); + } + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Behavior/TranslateBehaviorTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Behavior/TranslateBehaviorTest.php new file mode 100644 index 0000000..2593d44 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Behavior/TranslateBehaviorTest.php @@ -0,0 +1,1061 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Model.Behavior + * @since CakePHP(tm) v 1.2.0.5669 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ + +App::uses('Model', 'Model'); +App::uses('AppModel', 'Model'); +require_once dirname(dirname(__FILE__)) . DS . 'models.php'; + +/** + * TranslateBehaviorTest class + * + * @package Cake.Test.Case.Model.Behavior + */ +class TranslateBehaviorTest extends CakeTestCase { + +/** + * autoFixtures property + * + * @var bool false + */ + public $autoFixtures = false; + +/** + * fixtures property + * + * @var array + */ + public $fixtures = array( + 'core.translated_item', 'core.translate', 'core.translate_table', + 'core.translated_article', 'core.translate_article', 'core.user', 'core.comment', 'core.tag', 'core.articles_tag', + 'core.translate_with_prefix' + ); + +/** + * Test that count queries with conditions get the correct joins + * + * @return void + */ + public function testCountWithConditions() { + $this->loadFixtures('Translate', 'TranslatedItem'); + + $Model = new TranslatedItem(); + $Model->locale = 'eng'; + $result = $Model->find('count', array( + 'conditions' => array( + 'I18n__content.locale' => 'eng' + ) + )); + $this->assertEquals(3, $result); + } + +/** + * testTranslateModel method + * + * @return void + */ + public function testTranslateModel() { + $this->loadFixtures('TranslateTable', 'Tag', 'TranslatedItem', 'Translate', 'User', 'TranslatedArticle', 'TranslateArticle'); + $TestModel = new Tag(); + $TestModel->translateTable = 'another_i18n'; + $TestModel->Behaviors->attach('Translate', array('title')); + $translateModel = $TestModel->Behaviors->Translate->translateModel($TestModel); + $this->assertEquals('I18nModel', $translateModel->name); + $this->assertEquals('another_i18n', $translateModel->useTable); + + $TestModel = new User(); + $TestModel->Behaviors->attach('Translate', array('title')); + $translateModel = $TestModel->Behaviors->Translate->translateModel($TestModel); + $this->assertEquals('I18nModel', $translateModel->name); + $this->assertEquals('i18n', $translateModel->useTable); + + $TestModel = new TranslatedArticle(); + $translateModel = $TestModel->Behaviors->Translate->translateModel($TestModel); + $this->assertEquals('TranslateArticleModel', $translateModel->name); + $this->assertEquals('article_i18n', $translateModel->useTable); + + $TestModel = new TranslatedItem(); + $translateModel = $TestModel->Behaviors->Translate->translateModel($TestModel); + $this->assertEquals('TranslateTestModel', $translateModel->name); + $this->assertEquals('i18n', $translateModel->useTable); + } + +/** + * testLocaleFalsePlain method + * + * @return void + */ + public function testLocaleFalsePlain() { + $this->loadFixtures('Translate', 'TranslatedItem', 'User'); + + $TestModel = new TranslatedItem(); + $TestModel->locale = false; + + $result = $TestModel->read(null, 1); + $expected = array('TranslatedItem' => array( + 'id' => 1, + 'slug' => 'first_translated', + 'translated_article_id' => 1, + )); + $this->assertEquals($expected, $result); + + $result = $TestModel->find('all', array('fields' => array('slug'))); + $expected = array( + array('TranslatedItem' => array('slug' => 'first_translated')), + array('TranslatedItem' => array('slug' => 'second_translated')), + array('TranslatedItem' => array('slug' => 'third_translated')) + ); + $this->assertEquals($expected, $result); + } + +/** + * testLocaleFalseAssociations method + * + * @return void + */ + public function testLocaleFalseAssociations() { + $this->loadFixtures('Translate', 'TranslatedItem'); + + $TestModel = new TranslatedItem(); + $TestModel->locale = false; + $TestModel->unbindTranslation(); + $translations = array('title' => 'Title', 'content' => 'Content'); + $TestModel->bindTranslation($translations, false); + + $result = $TestModel->read(null, 1); + $expected = array( + 'TranslatedItem' => array('id' => 1, 'slug' => 'first_translated', 'translated_article_id' => 1), + 'Title' => array( + array('id' => 1, 'locale' => 'eng', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'title', 'content' => 'Title #1'), + array('id' => 3, 'locale' => 'deu', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'title', 'content' => 'Titel #1'), + array('id' => 5, 'locale' => 'cze', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'title', 'content' => 'Titulek #1') + ), + 'Content' => array( + array('id' => 2, 'locale' => 'eng', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'content', 'content' => 'Content #1'), + array('id' => 4, 'locale' => 'deu', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'content', 'content' => 'Inhalt #1'), + array('id' => 6, 'locale' => 'cze', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'content', 'content' => 'Obsah #1') + ) + ); + $this->assertEquals($expected, $result); + + $TestModel->hasMany['Title']['fields'] = $TestModel->hasMany['Content']['fields'] = array('content'); + $TestModel->hasMany['Title']['conditions']['locale'] = $TestModel->hasMany['Content']['conditions']['locale'] = 'eng'; + + $result = $TestModel->find('all', array('fields' => array('TranslatedItem.slug'))); + $expected = array( + array( + 'TranslatedItem' => array('id' => 1, 'slug' => 'first_translated'), + 'Title' => array(array('foreign_key' => 1, 'content' => 'Title #1')), + 'Content' => array(array('foreign_key' => 1, 'content' => 'Content #1')) + ), + array( + 'TranslatedItem' => array('id' => 2, 'slug' => 'second_translated'), + 'Title' => array(array('foreign_key' => 2, 'content' => 'Title #2')), + 'Content' => array(array('foreign_key' => 2, 'content' => 'Content #2')) + ), + array( + 'TranslatedItem' => array('id' => 3, 'slug' => 'third_translated'), + 'Title' => array(array('foreign_key' => 3, 'content' => 'Title #3')), + 'Content' => array(array('foreign_key' => 3, 'content' => 'Content #3')) + ) + ); + $this->assertEquals($expected, $result); + } + +/** + * testLocaleSingle method + * + * @return void + */ + public function testLocaleSingle() { + $this->loadFixtures('Translate', 'TranslatedItem'); + + $TestModel = new TranslatedItem(); + $TestModel->locale = 'eng'; + + $result = $TestModel->read(null, 1); + $expected = array( + 'TranslatedItem' => array( + 'id' => 1, + 'slug' => 'first_translated', + 'locale' => 'eng', + 'title' => 'Title #1', + 'content' => 'Content #1', + 'translated_article_id' => 1, + ) + ); + $this->assertEquals($expected, $result); + + $result = $TestModel->find('all'); + $expected = array( + array( + 'TranslatedItem' => array( + 'id' => 1, + 'slug' => 'first_translated', + 'locale' => 'eng', + 'title' => 'Title #1', + 'content' => 'Content #1', + 'translated_article_id' => 1, + ) + ), + array( + 'TranslatedItem' => array( + 'id' => 2, + 'slug' => 'second_translated', + 'locale' => 'eng', + 'title' => 'Title #2', + 'content' => 'Content #2', + 'translated_article_id' => 1, + ) + ), + array( + 'TranslatedItem' => array( + 'id' => 3, + 'slug' => 'third_translated', + 'locale' => 'eng', + 'title' => 'Title #3', + 'content' => 'Content #3', + 'translated_article_id' => 1, + ) + ) + ); + $this->assertEquals($expected, $result); + } + +/** + * testLocaleSingleWithConditions method + * + * @return void + */ + public function testLocaleSingleWithConditions() { + $this->loadFixtures('Translate', 'TranslatedItem'); + + $TestModel = new TranslatedItem(); + $TestModel->locale = 'eng'; + $result = $TestModel->find('all', array('conditions' => array('slug' => 'first_translated'))); + $expected = array( + array( + 'TranslatedItem' => array( + 'id' => 1, + 'slug' => 'first_translated', + 'locale' => 'eng', + 'title' => 'Title #1', + 'content' => 'Content #1', + 'translated_article_id' => 1, + ) + ) + ); + $this->assertEquals($expected, $result); + + $result = $TestModel->find('all', array('conditions' => "TranslatedItem.slug = 'first_translated'")); + $expected = array( + array( + 'TranslatedItem' => array( + 'id' => 1, + 'slug' => 'first_translated', + 'locale' => 'eng', + 'title' => 'Title #1', + 'content' => 'Content #1', + 'translated_article_id' => 1, + ) + ) + ); + $this->assertEquals($expected, $result); + } + +/** + * testLocaleSingleAssociations method + * + * @return void + */ + public function testLocaleSingleAssociations() { + $this->loadFixtures('Translate', 'TranslatedItem'); + + $TestModel = new TranslatedItem(); + $TestModel->locale = 'eng'; + $TestModel->unbindTranslation(); + $translations = array('title' => 'Title', 'content' => 'Content'); + $TestModel->bindTranslation($translations, false); + + $result = $TestModel->read(null, 1); + $expected = array( + 'TranslatedItem' => array( + 'id' => 1, + 'slug' => 'first_translated', + 'locale' => 'eng', + 'title' => 'Title #1', + 'content' => 'Content #1', + 'translated_article_id' => 1, + ), + 'Title' => array( + array('id' => 1, 'locale' => 'eng', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'title', 'content' => 'Title #1'), + array('id' => 3, 'locale' => 'deu', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'title', 'content' => 'Titel #1'), + array('id' => 5, 'locale' => 'cze', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'title', 'content' => 'Titulek #1') + ), + 'Content' => array( + array('id' => 2, 'locale' => 'eng', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'content', 'content' => 'Content #1'), + array('id' => 4, 'locale' => 'deu', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'content', 'content' => 'Inhalt #1'), + array('id' => 6, 'locale' => 'cze', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'content', 'content' => 'Obsah #1') + ) + ); + $this->assertEquals($expected, $result); + + $TestModel->hasMany['Title']['fields'] = $TestModel->hasMany['Content']['fields'] = array('content'); + $TestModel->hasMany['Title']['conditions']['locale'] = $TestModel->hasMany['Content']['conditions']['locale'] = 'eng'; + + $result = $TestModel->find('all', array('fields' => array('TranslatedItem.title'))); + $expected = array( + array( + 'TranslatedItem' => array( + 'id' => 1, + 'locale' => 'eng', + 'title' => 'Title #1', + 'slug' => 'first_translated', + 'translated_article_id' => 1, + ), + 'Title' => array(array('foreign_key' => 1, 'content' => 'Title #1')), + 'Content' => array(array('foreign_key' => 1, 'content' => 'Content #1')) + ), + array( + 'TranslatedItem' => array( + 'id' => 2, + 'locale' => 'eng', + 'title' => 'Title #2', + 'slug' => 'second_translated', + 'translated_article_id' => 1, + ), + 'Title' => array(array('foreign_key' => 2, 'content' => 'Title #2')), + 'Content' => array(array('foreign_key' => 2, 'content' => 'Content #2')) + ), + array( + 'TranslatedItem' => array( + 'id' => 3, + 'locale' => 'eng', + 'title' => 'Title #3', + 'slug' => 'third_translated', + 'translated_article_id' => 1, + ), + 'Title' => array(array('foreign_key' => 3, 'content' => 'Title #3')), + 'Content' => array(array('foreign_key' => 3, 'content' => 'Content #3')) + ) + ); + $this->assertEquals($expected, $result); + } + +/** + * testLocaleMultiple method + * + * @return void + */ + public function testLocaleMultiple() { + $this->loadFixtures('Translate', 'TranslatedItem'); + + $TestModel = new TranslatedItem(); + $TestModel->locale = array('deu', 'eng', 'cze'); + + $result = $TestModel->read(null, 1); + $expected = array( + 'TranslatedItem' => array( + 'id' => 1, + 'slug' => 'first_translated', + 'locale' => 'deu', + 'title' => 'Titel #1', + 'content' => 'Inhalt #1', + 'translated_article_id' => 1, + ) + ); + $this->assertEquals($expected, $result); + + $result = $TestModel->find('all', array('fields' => array('slug', 'title', 'content'))); + $expected = array( + array( + 'TranslatedItem' => array( + 'slug' => 'first_translated', + 'locale' => 'deu', + 'content' => 'Inhalt #1', + 'title' => 'Titel #1', + ) + ), + array( + 'TranslatedItem' => array( + 'slug' => 'second_translated', + 'locale' => 'deu', + 'title' => 'Titel #2', + 'content' => 'Inhalt #2', + ) + ), + array( + 'TranslatedItem' => array( + 'slug' => 'third_translated', + 'locale' => 'deu', + 'title' => 'Titel #3', + 'content' => 'Inhalt #3', + ) + ) + ); + + $this->assertEquals($expected, $result); + } + +/** + * testMissingTranslation method + * + * @return void + */ + public function testMissingTranslation() { + $this->loadFixtures('Translate', 'TranslatedItem'); + + $TestModel = new TranslatedItem(); + $TestModel->locale = 'rus'; + $result = $TestModel->read(null, 1); + $this->assertFalse($result); + + $TestModel->locale = array('rus'); + $result = $TestModel->read(null, 1); + $expected = array( + 'TranslatedItem' => array( + 'id' => 1, + 'slug' => 'first_translated', + 'locale' => 'rus', + 'title' => '', + 'content' => '', + 'translated_article_id' => 1, + ) + ); + $this->assertEquals($expected, $result); + } + +/** + * testTranslatedFindList method + * + * @return void + */ + public function testTranslatedFindList() { + $this->loadFixtures('Translate', 'TranslatedItem'); + + $TestModel = new TranslatedItem(); + $TestModel->locale = 'deu'; + $TestModel->displayField = 'title'; + $result = $TestModel->find('list', array('recursive' => 1)); + $expected = array(1 => 'Titel #1', 2 => 'Titel #2', 3 => 'Titel #3'); + $this->assertEquals($expected, $result); + + // SQL Server trigger an error and stops the page even if the debug = 0 + if ($this->db instanceof Sqlserver) { + $debug = Configure::read('debug'); + Configure::write('debug', 0); + + $result = $TestModel->find('list', array('recursive' => 1, 'callbacks' => false)); + $this->assertEquals(array(), $result); + + $result = $TestModel->find('list', array('recursive' => 1, 'callbacks' => 'after')); + $this->assertEquals(array(), $result); + Configure::write('debug', $debug); + } + + $result = $TestModel->find('list', array('recursive' => 1, 'callbacks' => 'before')); + $expected = array(1 => null, 2 => null, 3 => null); + $this->assertEquals($expected, $result); + } + +/** + * testReadSelectedFields method + * + * @return void + */ + public function testReadSelectedFields() { + $this->loadFixtures('Translate', 'TranslatedItem'); + + $TestModel = new TranslatedItem(); + $TestModel->locale = 'eng'; + $result = $TestModel->find('all', array('fields' => array('slug', 'TranslatedItem.content'))); + $expected = array( + array('TranslatedItem' => array('slug' => 'first_translated', 'locale' => 'eng', 'content' => 'Content #1')), + array('TranslatedItem' => array('slug' => 'second_translated', 'locale' => 'eng', 'content' => 'Content #2')), + array('TranslatedItem' => array('slug' => 'third_translated', 'locale' => 'eng', 'content' => 'Content #3')) + ); + $this->assertEquals($expected, $result); + + $result = $TestModel->find('all', array('fields' => array('TranslatedItem.slug', 'content'))); + $this->assertEquals($expected, $result); + + $TestModel->locale = array('eng', 'deu', 'cze'); + $delete = array(array('locale' => 'deu'), array('field' => 'content', 'locale' => 'eng')); + $I18nModel = ClassRegistry::getObject('TranslateTestModel'); + $I18nModel->deleteAll(array('or' => $delete)); + + $result = $TestModel->find('all', array('fields' => array('title', 'content'))); + $expected = array( + array('TranslatedItem' => array('locale' => 'eng', 'title' => 'Title #1', 'content' => 'Obsah #1')), + array('TranslatedItem' => array('locale' => 'eng', 'title' => 'Title #2', 'content' => 'Obsah #2')), + array('TranslatedItem' => array('locale' => 'eng', 'title' => 'Title #3', 'content' => 'Obsah #3')) + ); + $this->assertEquals($expected, $result); + } + +/** + * testSaveCreate method + * + * @return void + */ + public function testSaveCreate() { + $this->loadFixtures('Translate', 'TranslatedItem'); + + $TestModel = new TranslatedItem(); + $TestModel->locale = 'spa'; + $data = array( + 'slug' => 'fourth_translated', + 'title' => 'Leyenda #4', + 'content' => 'Contenido #4', + 'translated_article_id' => 1, + ); + $TestModel->create($data); + $TestModel->save(); + $result = $TestModel->read(); + $expected = array('TranslatedItem' => array_merge($data, array('id' => $TestModel->id, 'locale' => 'spa'))); + $this->assertEquals($expected, $result); + } + +/** + * Test that saving only some of the translated fields allows the record to be found again. + * + * @return void + */ + public function testSavePartialFields() { + $this->loadFixtures('Translate', 'TranslatedItem'); + + $TestModel = new TranslatedItem(); + $TestModel->locale = 'spa'; + $data = array( + 'slug' => 'fourth_translated', + 'title' => 'Leyenda #4', + ); + $TestModel->create($data); + $TestModel->save(); + $result = $TestModel->read(); + $expected = array( + 'TranslatedItem' => array( + 'id' => $TestModel->id, + 'translated_article_id' => null, + 'locale' => 'spa', + 'content' => '', + ) + $data + ); + $this->assertEquals($expected, $result); + } + +/** + * testSaveUpdate method + * + * @return void + */ + public function testSaveUpdate() { + $this->loadFixtures('Translate', 'TranslatedItem'); + + $TestModel = new TranslatedItem(); + $TestModel->locale = 'spa'; + $oldData = array('slug' => 'fourth_translated', 'title' => 'Leyenda #4', 'translated_article_id' => 1); + $TestModel->create($oldData); + $TestModel->save(); + $id = $TestModel->id; + $newData = array('id' => $id, 'content' => 'Contenido #4'); + $TestModel->create($newData); + $TestModel->save(); + $result = $TestModel->read(null, $id); + $expected = array('TranslatedItem' => array_merge($oldData, $newData, array('locale' => 'spa'))); + $this->assertEquals($expected, $result); + } + +/** + * testMultipleCreate method + * + * @return void + */ + public function testMultipleCreate() { + $this->loadFixtures('Translate', 'TranslatedItem'); + + $TestModel = new TranslatedItem(); + $TestModel->locale = 'deu'; + $data = array( + 'slug' => 'new_translated', + 'title' => array('eng' => 'New title', 'spa' => 'Nuevo leyenda'), + 'content' => array('eng' => 'New content', 'spa' => 'Nuevo contenido') + ); + $TestModel->create($data); + $TestModel->save(); + + $TestModel->unbindTranslation(); + $translations = array('title' => 'Title', 'content' => 'Content'); + $TestModel->bindTranslation($translations, false); + $TestModel->locale = array('eng', 'spa'); + + $result = $TestModel->read(); + $expected = array( + 'TranslatedItem' => array( + 'id' => 4, + 'slug' => 'new_translated', + 'locale' => 'eng', + 'title' => 'New title', + 'content' => 'New content', + 'translated_article_id' => null, + ), + 'Title' => array( + array('id' => 21, 'locale' => 'eng', 'model' => 'TranslatedItem', 'foreign_key' => 4, 'field' => 'title', 'content' => 'New title'), + array('id' => 22, 'locale' => 'spa', 'model' => 'TranslatedItem', 'foreign_key' => 4, 'field' => 'title', 'content' => 'Nuevo leyenda') + ), + 'Content' => array( + array('id' => 19, 'locale' => 'eng', 'model' => 'TranslatedItem', 'foreign_key' => 4, 'field' => 'content', 'content' => 'New content'), + array('id' => 20, 'locale' => 'spa', 'model' => 'TranslatedItem', 'foreign_key' => 4, 'field' => 'content', 'content' => 'Nuevo contenido') + ) + ); + $this->assertEquals($expected, $result); + } + +/** + * testMultipleUpdate method + * + * @return void + */ + public function testMultipleUpdate() { + $this->loadFixtures('Translate', 'TranslatedItem'); + + $TestModel = new TranslatedItem(); + $TestModel->locale = 'eng'; + $TestModel->validate['title'] = 'notEmpty'; + $data = array('TranslatedItem' => array( + 'id' => 1, + 'title' => array('eng' => 'New Title #1', 'deu' => 'Neue Titel #1', 'cze' => 'Novy Titulek #1'), + 'content' => array('eng' => 'New Content #1', 'deu' => 'Neue Inhalt #1', 'cze' => 'Novy Obsah #1') + )); + $TestModel->create(); + $TestModel->save($data); + + $TestModel->unbindTranslation(); + $translations = array('title' => 'Title', 'content' => 'Content'); + $TestModel->bindTranslation($translations, false); + $result = $TestModel->read(null, 1); + $expected = array( + 'TranslatedItem' => array( + 'id' => '1', + 'slug' => 'first_translated', + 'locale' => 'eng', + 'title' => 'New Title #1', + 'content' => 'New Content #1', + 'translated_article_id' => 1, + ), + 'Title' => array( + array('id' => 1, 'locale' => 'eng', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'title', 'content' => 'New Title #1'), + array('id' => 3, 'locale' => 'deu', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'title', 'content' => 'Neue Titel #1'), + array('id' => 5, 'locale' => 'cze', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'title', 'content' => 'Novy Titulek #1') + ), + 'Content' => array( + array('id' => 2, 'locale' => 'eng', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'content', 'content' => 'New Content #1'), + array('id' => 4, 'locale' => 'deu', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'content', 'content' => 'Neue Inhalt #1'), + array('id' => 6, 'locale' => 'cze', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'content', 'content' => 'Novy Obsah #1') + ) + ); + $this->assertEquals($expected, $result); + + $TestModel->unbindTranslation($translations); + $TestModel->bindTranslation(array('title', 'content'), false); + } + +/** + * testMixedCreateUpdateWithArrayLocale method + * + * @return void + */ + public function testMixedCreateUpdateWithArrayLocale() { + $this->loadFixtures('Translate', 'TranslatedItem'); + + $TestModel = new TranslatedItem(); + $TestModel->locale = array('cze', 'deu'); + $data = array('TranslatedItem' => array( + 'id' => 1, + 'title' => array('eng' => 'Updated Title #1', 'spa' => 'Nuevo leyenda #1'), + 'content' => 'Upraveny obsah #1' + )); + $TestModel->create(); + $TestModel->save($data); + + $TestModel->unbindTranslation(); + $translations = array('title' => 'Title', 'content' => 'Content'); + $TestModel->bindTranslation($translations, false); + $result = $TestModel->read(null, 1); + $result['Title'] = Hash::sort($result['Title'], '{n}.id', 'asc'); + $result['Content'] = Hash::sort($result['Content'], '{n}.id', 'asc'); + $expected = array( + 'TranslatedItem' => array( + 'id' => 1, + 'slug' => 'first_translated', + 'locale' => 'cze', + 'title' => 'Titulek #1', + 'content' => 'Upraveny obsah #1', + 'translated_article_id' => 1, + ), + 'Title' => array( + array('id' => 1, 'locale' => 'eng', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'title', 'content' => 'Updated Title #1'), + array('id' => 3, 'locale' => 'deu', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'title', 'content' => 'Titel #1'), + array('id' => 5, 'locale' => 'cze', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'title', 'content' => 'Titulek #1'), + array('id' => 19, 'locale' => 'spa', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'title', 'content' => 'Nuevo leyenda #1') + ), + 'Content' => array( + array('id' => 2, 'locale' => 'eng', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'content', 'content' => 'Content #1'), + array('id' => 4, 'locale' => 'deu', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'content', 'content' => 'Inhalt #1'), + array('id' => 6, 'locale' => 'cze', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'content', 'content' => 'Upraveny obsah #1') + ) + ); + $this->assertEquals($expected, $result); + } + +/** + * Test that saveAll() works with hasMany associations that contain + * translations. + * + * @return void + */ + public function testSaveAllTranslatedAssociations() { + $this->loadFixtures('Translate', 'TranslateArticle', 'TranslatedItem', 'TranslatedArticle', 'User'); + $Model = new TranslatedArticle(); + $Model->locale = 'eng'; + + $data = array( + 'TranslatedArticle' => array( + 'id' => 4, + 'user_id' => 1, + 'published' => 'Y', + 'title' => 'Title (eng) #1', + 'body' => 'Body (eng) #1' + ), + 'TranslatedItem' => array( + array( + 'slug' => '', + 'title' => 'Nuevo leyenda #1', + 'content' => 'Upraveny obsah #1' + ), + array( + 'slug' => '', + 'title' => 'New Title #2', + 'content' => 'New Content #2' + ), + ) + ); + $result = $Model->saveAll($data); + $this->assertTrue($result); + + $result = $Model->TranslatedItem->find('all', array( + 'conditions' => array('translated_article_id' => $Model->id) + )); + $this->assertCount(2, $result); + $this->assertEquals($data['TranslatedItem'][0]['title'], $result[0]['TranslatedItem']['title']); + $this->assertEquals($data['TranslatedItem'][1]['title'], $result[1]['TranslatedItem']['title']); + } + +/** + * testValidation method + * + * @return void + */ + public function testValidation() { + $this->loadFixtures('Translate', 'TranslatedItem'); + + $TestModel = new TranslatedItem(); + $TestModel->locale = 'eng'; + $TestModel->validate['title'] = '/Only this title/'; + $data = array( + 'TranslatedItem' => array( + 'id' => 1, + 'title' => array('eng' => 'New Title #1', 'deu' => 'Neue Titel #1', 'cze' => 'Novy Titulek #1'), + 'content' => array('eng' => 'New Content #1', 'deu' => 'Neue Inhalt #1', 'cze' => 'Novy Obsah #1') + ) + ); + $TestModel->create(); + $this->assertFalse($TestModel->save($data)); + $this->assertEquals(array('This field cannot be left blank'), $TestModel->validationErrors['title']); + + $TestModel->locale = 'eng'; + $TestModel->validate['title'] = '/Only this title/'; + $data = array('TranslatedItem' => array( + 'id' => 1, + 'title' => array('eng' => 'Only this title', 'deu' => 'Neue Titel #1', 'cze' => 'Novy Titulek #1'), + 'content' => array('eng' => 'New Content #1', 'deu' => 'Neue Inhalt #1', 'cze' => 'Novy Obsah #1') + )); + $TestModel->create(); + $result = $TestModel->save($data); + $this->assertFalse(empty($result)); + } + +/** + * testAttachDetach method + * + * @return void + */ + public function testAttachDetach() { + $this->loadFixtures('Translate', 'TranslatedItem'); + + $TestModel = new TranslatedItem(); + + $TestModel->unbindTranslation(); + $translations = array('title' => 'Title', 'content' => 'Content'); + $TestModel->bindTranslation($translations, false); + + $result = array_keys($TestModel->hasMany); + $expected = array('Title', 'Content'); + $this->assertEquals($expected, $result); + + $TestModel->Behaviors->detach('Translate'); + $result = array_keys($TestModel->hasMany); + $expected = array(); + $this->assertEquals($expected, $result); + + $result = isset($TestModel->Behaviors->Translate); + $this->assertFalse($result); + + $result = isset($Behavior->settings[$TestModel->alias]); + $this->assertFalse($result); + + $result = isset($Behavior->runtime[$TestModel->alias]); + $this->assertFalse($result); + + $TestModel->Behaviors->attach('Translate', array('title' => 'Title', 'content' => 'Content')); + $result = array_keys($TestModel->hasMany); + $expected = array('Title', 'Content'); + $this->assertEquals($expected, $result); + + $result = isset($TestModel->Behaviors->Translate); + $this->assertTrue($result); + + $Behavior = $TestModel->Behaviors->Translate; + + $result = isset($Behavior->settings[$TestModel->alias]); + $this->assertTrue($result); + + $result = isset($Behavior->runtime[$TestModel->alias]); + $this->assertTrue($result); + } + +/** + * testAnotherTranslateTable method + * + * @return void + */ + public function testAnotherTranslateTable() { + $this->loadFixtures('Translate', 'TranslatedItem', 'TranslateTable'); + + $TestModel = new TranslatedItemWithTable(); + $TestModel->locale = 'eng'; + $result = $TestModel->read(null, 1); + $expected = array( + 'TranslatedItemWithTable' => array( + 'id' => 1, + 'slug' => 'first_translated', + 'locale' => 'eng', + 'title' => 'Another Title #1', + 'content' => 'Another Content #1', + 'translated_article_id' => 1, + ) + ); + $this->assertEquals($expected, $result); + } + +/** + * testTranslateWithAssociations method + * + * @return void + */ + public function testTranslateWithAssociations() { + $this->loadFixtures('TranslateArticle', 'TranslatedArticle', 'TranslatedItem', 'User', 'Comment', 'ArticlesTag', 'Tag'); + + $TestModel = new TranslatedArticle(); + $TestModel->locale = 'eng'; + $recursive = $TestModel->recursive; + + $result = $TestModel->read(null, 1); + $expected = array( + 'TranslatedArticle' => array( + 'id' => 1, + 'user_id' => 1, + 'published' => 'Y', + 'created' => '2007-03-18 10:39:23', + 'updated' => '2007-03-18 10:41:31', + 'locale' => 'eng', + 'title' => 'Title (eng) #1', + 'body' => 'Body (eng) #1' + ), + 'User' => array( + 'id' => 1, + 'user' => 'mariano', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', + 'updated' => '2007-03-17 01:18:31' + ), + 'TranslatedItem' => array( + array( + 'id' => 1, + 'translated_article_id' => 1, + 'slug' => 'first_translated' + ), + array( + 'id' => 2, + 'translated_article_id' => 1, + 'slug' => 'second_translated' + ), + array( + 'id' => 3, + 'translated_article_id' => 1, + 'slug' => 'third_translated' + ), + ) + ); + $this->assertEquals($expected, $result); + + $result = $TestModel->find('all', array('recursive' => -1)); + $expected = array( + array( + 'TranslatedArticle' => array( + 'id' => 1, + 'user_id' => 1, + 'published' => 'Y', + 'created' => '2007-03-18 10:39:23', + 'updated' => '2007-03-18 10:41:31', + 'locale' => 'eng', + 'title' => 'Title (eng) #1', + 'body' => 'Body (eng) #1' + ) + ), + array( + 'TranslatedArticle' => array( + 'id' => 2, + 'user_id' => 3, + 'published' => 'Y', + 'created' => '2007-03-18 10:41:23', + 'updated' => '2007-03-18 10:43:31', + 'locale' => 'eng', + 'title' => 'Title (eng) #2', + 'body' => 'Body (eng) #2' + ) + ), + array( + 'TranslatedArticle' => array( + 'id' => 3, + 'user_id' => 1, + 'published' => 'Y', + 'created' => '2007-03-18 10:43:23', + 'updated' => '2007-03-18 10:45:31', + 'locale' => 'eng', + 'title' => 'Title (eng) #3', + 'body' => 'Body (eng) #3' + ) + ) + ); + $this->assertEquals($expected, $result); + $this->assertEquals($TestModel->recursive, $recursive); + + $TestModel->recursive = -1; + $result = $TestModel->read(null, 1); + $expected = array( + 'TranslatedArticle' => array( + 'id' => 1, + 'user_id' => 1, + 'published' => 'Y', + 'created' => '2007-03-18 10:39:23', + 'updated' => '2007-03-18 10:41:31', + 'locale' => 'eng', + 'title' => 'Title (eng) #1', + 'body' => 'Body (eng) #1' + ) + ); + $this->assertEquals($expected, $result); + } + +/** + * testTranslateTableWithPrefix method + * Tests that is possible to have a translation model with a custom tablePrefix + * + * @return void + */ + public function testTranslateTableWithPrefix() { + $this->loadFixtures('TranslateWithPrefix', 'TranslatedItem'); + $TestModel = new TranslatedItem2; + $TestModel->locale = 'eng'; + $result = $TestModel->read(null, 1); + $expected = array('TranslatedItem' => array( + 'id' => 1, + 'slug' => 'first_translated', + 'locale' => 'eng', + 'content' => 'Content #1', + 'title' => 'Title #1', + 'translated_article_id' => 1, + )); + $this->assertEquals($expected, $result); + } + +/** + * Test infinite loops not occurring with unbindTranslation() + * + * @return void + */ + public function testUnbindTranslationInfinteLoop() { + $this->loadFixtures('Translate', 'TranslatedItem'); + + $TestModel = new TranslatedItem(); + $TestModel->Behaviors->detach('Translate'); + $TestModel->actsAs = array(); + $TestModel->Behaviors->attach('Translate'); + $TestModel->bindTranslation(array('title', 'content'), true); + $result = $TestModel->unbindTranslation(); + + $this->assertFalse($result); + } + +/** + * Test that an exception is raised when you try to over-write the name attribute. + * + * @expectedException CakeException + * @return void + */ + public function testExceptionOnNameTranslation() { + $this->loadFixtures('Translate', 'TranslatedItem'); + $TestModel = new TranslatedItem(); + $TestModel->bindTranslation(array('name' => 'name')); + } + +/** + * Test that translations can be bound and unbound dynamically. + * + * @return void + */ + public function testUnbindTranslation() { + $this->loadFixtures('Translate', 'TranslatedItem'); + $Model = new TranslatedItem(); + $Model->unbindTranslation(); + $Model->bindTranslation(array('body', 'slug'), false); + + $result = $Model->Behaviors->Translate->settings['TranslatedItem']; + $this->assertEquals(array('body', 'slug'), $result); + + $Model->unbindTranslation(array('body')); + $result = $Model->Behaviors->Translate->settings['TranslatedItem']; + $this->assertNotContains('body', $result); + + $Model->unbindTranslation('slug'); + $result = $Model->Behaviors->Translate->settings['TranslatedItem']; + $this->assertNotContains('slug', $result); + } + +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Behavior/TreeBehaviorAfterTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Behavior/TreeBehaviorAfterTest.php new file mode 100644 index 0000000..4e8ae4c --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Behavior/TreeBehaviorAfterTest.php @@ -0,0 +1,77 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Model.Behavior + * @since CakePHP(tm) v 1.2.0.5330 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ + +App::uses('Model', 'Model'); +App::uses('AppModel', 'Model'); +require_once dirname(dirname(__FILE__)) . DS . 'models.php'; + + +/** + * TreeBehaviorAfterTest class + * + * @package Cake.Test.Case.Model.Behavior + */ +class TreeBehaviorAfterTest extends CakeTestCase { + +/** + * Whether backup global state for each test method or not + * + * @var bool false + */ + public $backupGlobals = false; + +/** + * settings property + * + * @var array + */ + public $settings = array( + 'modelClass' => 'AfterTree', + 'leftField' => 'lft', + 'rightField' => 'rght', + 'parentField' => 'parent_id' + ); + +/** + * fixtures property + * + * @var array + */ + public $fixtures = array('core.after_tree'); + +/** + * Tests the afterSave callback in the model + * + * @return void + */ + public function testAftersaveCallback() { + $this->Tree = new AfterTree(); + + $expected = array('AfterTree' => array('name' => 'Six and One Half Changed in AfterTree::afterSave() but not in database', 'parent_id' => 6, 'lft' => 11, 'rght' => 12)); + $result = $this->Tree->save(array('AfterTree' => array('name' => 'Six and One Half', 'parent_id' => 6))); + $expected['AfterTree']['id'] = $this->Tree->id; + $this->assertEquals($expected, $result); + + $expected = array('AfterTree' => array('name' => 'Six and One Half', 'parent_id' => 6, 'lft' => 11, 'rght' => 12, 'id' => 8)); + $result = $this->Tree->find('all'); + $this->assertEquals($expected, $result[7]); + } +} + + diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Behavior/TreeBehaviorNumberTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Behavior/TreeBehaviorNumberTest.php new file mode 100644 index 0000000..1078286 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Behavior/TreeBehaviorNumberTest.php @@ -0,0 +1,1379 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Model.Behavior + * @since CakePHP(tm) v 1.2.0.5330 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ + +App::uses('Model', 'Model'); +App::uses('AppModel', 'Model'); +require_once dirname(dirname(__FILE__)) . DS . 'models.php'; + +/** + * TreeBehaviorNumberTest class + * + * @package Cake.Test.Case.Model.Behavior + */ +class TreeBehaviorNumberTest extends CakeTestCase { + +/** + * Whether backup global state for each test method or not + * + * @var bool false + */ + public $backupGlobals = false; + +/** + * settings property + * + * @var array + */ + public $settings = array( + 'modelClass' => 'NumberTree', + 'leftField' => 'lft', + 'rightField' => 'rght', + 'parentField' => 'parent_id' + ); + +/** + * fixtures property + * + * @var array + */ + public $fixtures = array('core.number_tree', 'core.person'); + +/** + * testInitialize method + * + * @return void + */ + public function testInitialize() { + extract($this->settings); + $this->Tree = new $modelClass(); + $this->Tree->initialize(2, 2); + + $result = $this->Tree->find('count'); + $this->assertEquals(7, $result); + + $validTree = $this->Tree->verify(); + $this->assertSame($validTree, true); + } + +/** + * testDetectInvalidLeft method + * + * @return void + */ + public function testDetectInvalidLeft() { + extract($this->settings); + $this->Tree = new $modelClass(); + $this->Tree->initialize(2, 2); + + $result = $this->Tree->findByName('1.1'); + + $save[$modelClass]['id'] = $result[$modelClass]['id']; + $save[$modelClass][$leftField] = 0; + + $this->Tree->save($save); + $result = $this->Tree->verify(); + $this->assertNotSame($result, true); + + $result = $this->Tree->recover(); + $this->assertSame($result, true); + + $result = $this->Tree->verify(); + $this->assertSame($result, true); + } + +/** + * testDetectInvalidRight method + * + * @return void + */ + public function testDetectInvalidRight() { + extract($this->settings); + $this->Tree = new $modelClass(); + $this->Tree->initialize(2, 2); + + $result = $this->Tree->findByName('1.1'); + + $save[$modelClass]['id'] = $result[$modelClass]['id']; + $save[$modelClass][$rightField] = 0; + + $this->Tree->save($save); + $result = $this->Tree->verify(); + $this->assertNotSame($result, true); + + $result = $this->Tree->recover(); + $this->assertSame($result, true); + + $result = $this->Tree->verify(); + $this->assertSame($result, true); + } + +/** + * testDetectInvalidParent method + * + * @return void + */ + public function testDetectInvalidParent() { + extract($this->settings); + $this->Tree = new $modelClass(); + $this->Tree->initialize(2, 2); + + $result = $this->Tree->findByName('1.1'); + + // Bypass behavior and any other logic + $this->Tree->updateAll(array($parentField => null), array('id' => $result[$modelClass]['id'])); + + $result = $this->Tree->verify(); + $this->assertNotSame($result, true); + + $result = $this->Tree->recover(); + $this->assertSame($result, true); + + $result = $this->Tree->verify(); + $this->assertSame($result, true); + } + +/** + * testDetectNoneExistentParent method + * + * @return void + */ + public function testDetectNoneExistentParent() { + extract($this->settings); + $this->Tree = new $modelClass(); + $this->Tree->initialize(2, 2); + + $result = $this->Tree->findByName('1.1'); + $this->Tree->updateAll(array($parentField => 999999), array('id' => $result[$modelClass]['id'])); + + $result = $this->Tree->verify(); + $this->assertNotSame($result, true); + + $result = $this->Tree->recover('MPTT'); + $this->assertSame($result, true); + + $result = $this->Tree->verify(); + $this->assertSame($result, true); + } + +/** + * testRecoverUsingParentMode method + * + * @return void + */ + public function testRecoverUsingParentMode() { + extract($this->settings); + $this->Tree = new $modelClass(); + $this->Tree->Behaviors->disable('Tree'); + + $this->Tree->save(array('parent_id' => null, 'name' => 'Main', $parentField => null, $leftField => 0, $rightField => 0)); + $node1 = $this->Tree->id; + + $this->Tree->create(); + $this->Tree->save(array('parent_id' => null, 'name' => 'About Us', $parentField => $node1, $leftField => 0, $rightField => 0)); + $node11 = $this->Tree->id; + $this->Tree->create(); + $this->Tree->save(array('parent_id' => null, 'name' => 'Programs', $parentField => $node1, $leftField => 0, $rightField => 0)); + $node12 = $this->Tree->id; + $this->Tree->create(); + $this->Tree->save(array('parent_id' => null, 'name' => 'Mission and History', $parentField => $node11, $leftField => 0, $rightField => 0)); + $this->Tree->create(); + $this->Tree->save(array('parent_id' => null, 'name' => 'Overview', $parentField => $node12, $leftField => 0, $rightField => 0)); + + $this->Tree->Behaviors->enable('Tree'); + + $result = $this->Tree->verify(); + $this->assertNotSame($result, true); + + $result = $this->Tree->recover(); + $this->assertTrue($result); + + $result = $this->Tree->verify(); + $this->assertTrue($result); + + $result = $this->Tree->find('first', array( + 'fields' => array('name', $parentField, $leftField, $rightField), + 'conditions' => array('name' => 'Main'), + 'recursive' => -1 + )); + $expected = array( + $modelClass => array( + 'name' => 'Main', + $parentField => null, + $leftField => 1, + $rightField => 10 + ) + ); + $this->assertEquals($expected, $result); + } + +/** + * testRecoverFromMissingParent method + * + * @return void + */ + public function testRecoverFromMissingParent() { + extract($this->settings); + $this->Tree = new $modelClass(); + $this->Tree->initialize(2, 2); + + $result = $this->Tree->findByName('1.1'); + $this->Tree->updateAll(array($parentField => 999999), array('id' => $result[$modelClass]['id'])); + + $result = $this->Tree->verify(); + $this->assertNotSame($result, true); + + $result = $this->Tree->recover(); + $this->assertSame($result, true); + + $result = $this->Tree->verify(); + $this->assertSame($result, true); + } + +/** + * testDetectInvalidParents method + * + * @return void + */ + public function testDetectInvalidParents() { + extract($this->settings); + $this->Tree = new $modelClass(); + $this->Tree->initialize(2, 2); + + $this->Tree->updateAll(array($parentField => null)); + + $result = $this->Tree->verify(); + $this->assertNotSame($result, true); + + $result = $this->Tree->recover(); + $this->assertSame($result, true); + + $result = $this->Tree->verify(); + $this->assertSame($result, true); + } + +/** + * testDetectInvalidLftsRghts method + * + * @return void + */ + public function testDetectInvalidLftsRghts() { + extract($this->settings); + $this->Tree = new $modelClass(); + $this->Tree->initialize(2, 2); + + $this->Tree->updateAll(array($leftField => 0, $rightField => 0)); + + $result = $this->Tree->verify(); + $this->assertNotSame($result, true); + + $this->Tree->recover(); + + $result = $this->Tree->verify(); + $this->assertSame($result, true); + } + +/** + * Reproduces a situation where a single node has lft= rght, and all other lft and rght fields follow sequentially + * + * @return void + */ + public function testDetectEqualLftsRghts() { + extract($this->settings); + $this->Tree = new $modelClass(); + $this->Tree->initialize(1, 3); + + $result = $this->Tree->findByName('1.1'); + $this->Tree->updateAll(array($rightField => $result[$modelClass][$leftField]), array('id' => $result[$modelClass]['id'])); + $this->Tree->updateAll(array($leftField => $this->Tree->escapeField($leftField) . ' -1'), + array($leftField . ' >' => $result[$modelClass][$leftField])); + $this->Tree->updateAll(array($rightField => $this->Tree->escapeField($rightField) . ' -1'), + array($rightField . ' >' => $result[$modelClass][$leftField])); + + $result = $this->Tree->verify(); + $this->assertNotSame($result, true); + + $result = $this->Tree->recover(); + $this->assertTrue($result); + + $result = $this->Tree->verify(); + $this->assertTrue($result); + } + +/** + * testAddOrphan method + * + * @return void + */ + public function testAddOrphan() { + extract($this->settings); + $this->Tree = new $modelClass(); + $this->Tree->initialize(2, 2); + + $this->Tree->save(array($modelClass => array('name' => 'testAddOrphan', $parentField => null))); + $result = $this->Tree->find('first', array('fields' => array('name', $parentField), 'order' => $modelClass . '.' . $leftField . ' desc')); + $expected = array($modelClass => array('name' => 'testAddOrphan', $parentField => null)); + $this->assertEquals($expected, $result); + + $validTree = $this->Tree->verify(); + $this->assertSame($validTree, true); + } + +/** + * testAddMiddle method + * + * @return void + */ + public function testAddMiddle() { + extract($this->settings); + $this->Tree = new $modelClass(); + $this->Tree->initialize(2, 2); + + $data = $this->Tree->find('first', array('fields' => array('id'), 'conditions' => array($modelClass . '.name' => '1.1'))); + $initialCount = $this->Tree->find('count'); + + $this->Tree->create(); + $result = $this->Tree->save(array($modelClass => array('name' => 'testAddMiddle', $parentField => $data[$modelClass]['id']))); + $expected = array_merge(array($modelClass => array('name' => 'testAddMiddle', $parentField => '2')), $result); + $this->assertSame($expected, $result); + + $laterCount = $this->Tree->find('count'); + + $laterCount = $this->Tree->find('count'); + $this->assertEquals($initialCount + 1, $laterCount); + + $children = $this->Tree->children($data[$modelClass]['id'], true, array('name')); + $expects = array(array($modelClass => array('name' => '1.1.1')), + array($modelClass => array('name' => '1.1.2')), + array($modelClass => array('name' => 'testAddMiddle'))); + $this->assertSame($children, $expects); + + $validTree = $this->Tree->verify(); + $this->assertSame($validTree, true); + } + +/** + * testAddInvalid method + * + * @return void + */ + public function testAddInvalid() { + extract($this->settings); + $this->Tree = new $modelClass(); + $this->Tree->initialize(2, 2); + $this->Tree->id = null; + + $initialCount = $this->Tree->find('count'); + //$this->expectError('Trying to save a node under a none-existant node in TreeBehavior::beforeSave'); + + $saveSuccess = $this->Tree->save(array($modelClass => array('name' => 'testAddInvalid', $parentField => 99999))); + $this->assertSame($saveSuccess, false); + + $laterCount = $this->Tree->find('count'); + $this->assertSame($initialCount, $laterCount); + + $validTree = $this->Tree->verify(); + $this->assertSame($validTree, true); + } + +/** + * testAddNotIndexedByModel method + * + * @return void + */ + public function testAddNotIndexedByModel() { + extract($this->settings); + $this->Tree = new $modelClass(); + $this->Tree->initialize(2, 2); + + $this->Tree->save(array('name' => 'testAddNotIndexed', $parentField => null)); + $result = $this->Tree->find('first', array('fields' => array('name', $parentField), 'order' => $modelClass . '.' . $leftField . ' desc')); + $expected = array($modelClass => array('name' => 'testAddNotIndexed', $parentField => null)); + $this->assertEquals($expected, $result); + + $validTree = $this->Tree->verify(); + $this->assertSame($validTree, true); + } + +/** + * testMovePromote method + * + * @return void + */ + public function testMovePromote() { + extract($this->settings); + $this->Tree = new $modelClass(); + $this->Tree->initialize(2, 2); + $this->Tree->id = null; + + $parent = $this->Tree->find('first', array('conditions' => array($modelClass . '.name' => '1. Root'))); + $parentId = $parent[$modelClass]['id']; + + $data = $this->Tree->find('first', array('fields' => array('id'), 'conditions' => array($modelClass . '.name' => '1.1.1'))); + $this->Tree->id = $data[$modelClass]['id']; + $this->Tree->saveField($parentField, $parentId); + $direct = $this->Tree->children($parentId, true, array('id', 'name', $parentField, $leftField, $rightField)); + $expects = array(array($modelClass => array('id' => 2, 'name' => '1.1', $parentField => 1, $leftField => 2, $rightField => 5)), + array($modelClass => array('id' => 5, 'name' => '1.2', $parentField => 1, $leftField => 6, $rightField => 11)), + array($modelClass => array('id' => 3, 'name' => '1.1.1', $parentField => 1, $leftField => 12, $rightField => 13))); + $this->assertEquals($direct, $expects); + $validTree = $this->Tree->verify(); + $this->assertSame($validTree, true); + } + +/** + * testMoveWithWhitelist method + * + * @return void + */ + public function testMoveWithWhitelist() { + extract($this->settings); + $this->Tree = new $modelClass(); + $this->Tree->initialize(2, 2); + $this->Tree->id = null; + + $parent = $this->Tree->find('first', array('conditions' => array($modelClass . '.name' => '1. Root'))); + $parentId = $parent[$modelClass]['id']; + + $data = $this->Tree->find('first', array('fields' => array('id'), 'conditions' => array($modelClass . '.name' => '1.1.1'))); + $this->Tree->id = $data[$modelClass]['id']; + $this->Tree->whitelist = array($parentField, 'name', 'description'); + $this->Tree->saveField($parentField, $parentId); + + $result = $this->Tree->children($parentId, true, array('id', 'name', $parentField, $leftField, $rightField)); + $expected = array(array($modelClass => array('id' => 2, 'name' => '1.1', $parentField => 1, $leftField => 2, $rightField => 5)), + array($modelClass => array('id' => 5, 'name' => '1.2', $parentField => 1, $leftField => 6, $rightField => 11)), + array($modelClass => array('id' => 3, 'name' => '1.1.1', $parentField => 1, $leftField => 12, $rightField => 13))); + $this->assertEquals($expected, $result); + $this->assertTrue($this->Tree->verify()); + } + +/** + * testInsertWithWhitelist method + * + * @return void + */ + public function testInsertWithWhitelist() { + extract($this->settings); + $this->Tree = new $modelClass(); + $this->Tree->initialize(2, 2); + + $this->Tree->whitelist = array('name', $parentField); + $this->Tree->save(array($modelClass => array('name' => 'testAddOrphan', $parentField => null))); + $result = $this->Tree->findByName('testAddOrphan', array('name', $parentField, $leftField, $rightField)); + $expected = array('name' => 'testAddOrphan', $parentField => null, $leftField => '15', $rightField => 16); + $this->assertEquals($expected, $result[$modelClass]); + $this->assertSame($this->Tree->verify(), true); + } + +/** + * testMoveBefore method + * + * @return void + */ + public function testMoveBefore() { + extract($this->settings); + $this->Tree = new $modelClass(); + $this->Tree->initialize(2, 2); + $this->Tree->id = null; + + $parent = $this->Tree->find('first', array('conditions' => array($modelClass . '.name' => '1.1'))); + $parentId = $parent[$modelClass]['id']; + + $data = $this->Tree->find('first', array('fields' => array('id'), 'conditions' => array($modelClass . '.name' => '1.2'))); + $this->Tree->id = $data[$modelClass]['id']; + $this->Tree->saveField($parentField, $parentId); + + $result = $this->Tree->children($parentId, true, array('name')); + $expects = array(array($modelClass => array('name' => '1.1.1')), + array($modelClass => array('name' => '1.1.2')), + array($modelClass => array('name' => '1.2'))); + $this->assertEquals($expects, $result); + + $validTree = $this->Tree->verify(); + $this->assertSame($validTree, true); + } + +/** + * testMoveAfter method + * + * @return void + */ + public function testMoveAfter() { + extract($this->settings); + $this->Tree = new $modelClass(); + $this->Tree->initialize(2, 2); + $this->Tree->id = null; + + $parent = $this->Tree->find('first', array('conditions' => array($modelClass . '.name' => '1.2'))); + $parentId = $parent[$modelClass]['id']; + + $data = $this->Tree->find('first', array('fields' => array('id'), 'conditions' => array($modelClass . '.name' => '1.1'))); + $this->Tree->id = $data[$modelClass]['id']; + $this->Tree->saveField($parentField, $parentId); + + $result = $this->Tree->children($parentId, true, array('name')); + $expects = array(array($modelClass => array('name' => '1.2.1')), + array($modelClass => array('name' => '1.2.2')), + array($modelClass => array('name' => '1.1'))); + $this->assertEquals($expects, $result); + + $validTree = $this->Tree->verify(); + $this->assertSame($validTree, true); + } + +/** + * testMoveDemoteInvalid method + * + * @return void + */ + public function testMoveDemoteInvalid() { + extract($this->settings); + $this->Tree = new $modelClass(); + $this->Tree->initialize(2, 2); + $this->Tree->id = null; + + $parent = $this->Tree->find('first', array('conditions' => array($modelClass . '.name' => '1. Root'))); + $parentId = $parent[$modelClass]['id']; + + $data = $this->Tree->find('first', array('fields' => array('id'), 'conditions' => array($modelClass . '.name' => '1.1.1'))); + + $expects = $this->Tree->find('all'); + $before = $this->Tree->read(null, $data[$modelClass]['id']); + + $this->Tree->id = $parentId; + $this->Tree->saveField($parentField, $data[$modelClass]['id']); + + $results = $this->Tree->find('all'); + $after = $this->Tree->read(null, $data[$modelClass]['id']); + + $this->assertEquals($expects, $results); + $this->assertEquals($before, $after); + + $validTree = $this->Tree->verify(); + $this->assertSame($validTree, true); + } + +/** + * testMoveInvalid method + * + * @return void + */ + public function testMoveInvalid() { + extract($this->settings); + $this->Tree = new $modelClass(); + $this->Tree->initialize(2, 2); + $this->Tree->id = null; + + $initialCount = $this->Tree->find('count'); + $data = $this->Tree->findByName('1.1'); + + $this->Tree->id = $data[$modelClass]['id']; + $this->Tree->saveField($parentField, 999999); + + $laterCount = $this->Tree->find('count'); + $this->assertSame($initialCount, $laterCount); + + $validTree = $this->Tree->verify(); + $this->assertSame($validTree, true); + } + +/** + * testMoveSelfInvalid method + * + * @return void + */ + public function testMoveSelfInvalid() { + extract($this->settings); + $this->Tree = new $modelClass(); + $this->Tree->initialize(2, 2); + $this->Tree->id = null; + + $initialCount = $this->Tree->find('count'); + $data = $this->Tree->findByName('1.1'); + + $this->Tree->id = $data[$modelClass]['id']; + $saveSuccess = $this->Tree->saveField($parentField, $this->Tree->id); + + $this->assertSame($saveSuccess, false); + $laterCount = $this->Tree->find('count'); + $this->assertSame($initialCount, $laterCount); + + $validTree = $this->Tree->verify(); + $this->assertSame($validTree, true); + } + +/** + * testMoveUpSuccess method + * + * @return void + */ + public function testMoveUpSuccess() { + extract($this->settings); + $this->Tree = new $modelClass(); + $this->Tree->initialize(2, 2); + + $data = $this->Tree->find('first', array('fields' => array('id'), 'conditions' => array($modelClass . '.name' => '1.2'))); + $this->Tree->moveUp($data[$modelClass]['id']); + + $parent = $this->Tree->findByName('1. Root', array('id')); + $this->Tree->id = $parent[$modelClass]['id']; + $result = $this->Tree->children(null, true, array('name')); + $expected = array(array($modelClass => array('name' => '1.2', )), + array($modelClass => array('name' => '1.1', ))); + $this->assertSame($expected, $result); + } + +/** + * testMoveUpFail method + * + * @return void + */ + public function testMoveUpFail() { + extract($this->settings); + $this->Tree = new $modelClass(); + $this->Tree->initialize(2, 2); + + $data = $this->Tree->find('first', array('conditions' => array($modelClass . '.name' => '1.1'))); + + $this->Tree->moveUp($data[$modelClass]['id']); + + $parent = $this->Tree->findByName('1. Root', array('id')); + $this->Tree->id = $parent[$modelClass]['id']; + $result = $this->Tree->children(null, true, array('name')); + $expected = array(array($modelClass => array('name' => '1.1', )), + array($modelClass => array('name' => '1.2', ))); + $this->assertSame($expected, $result); + } + +/** + * testMoveUp2 method + * + * @return void + */ + public function testMoveUp2() { + extract($this->settings); + $this->Tree = new $modelClass(); + $this->Tree->initialize(1, 10); + + $data = $this->Tree->find('first', array('fields' => array('id'), 'conditions' => array($modelClass . '.name' => '1.5'))); + $this->Tree->moveUp($data[$modelClass]['id'], 2); + + $parent = $this->Tree->findByName('1. Root', array('id')); + $this->Tree->id = $parent[$modelClass]['id']; + $result = $this->Tree->children(null, true, array('name')); + $expected = array( + array($modelClass => array('name' => '1.1', )), + array($modelClass => array('name' => '1.2', )), + array($modelClass => array('name' => '1.5', )), + array($modelClass => array('name' => '1.3', )), + array($modelClass => array('name' => '1.4', )), + array($modelClass => array('name' => '1.6', )), + array($modelClass => array('name' => '1.7', )), + array($modelClass => array('name' => '1.8', )), + array($modelClass => array('name' => '1.9', )), + array($modelClass => array('name' => '1.10', ))); + $this->assertSame($expected, $result); + } + +/** + * testMoveUpFirst method + * + * @return void + */ + public function testMoveUpFirst() { + extract($this->settings); + $this->Tree = new $modelClass(); + $this->Tree->initialize(1, 10); + + $data = $this->Tree->find('first', array('fields' => array('id'), 'conditions' => array($modelClass . '.name' => '1.5'))); + $this->Tree->moveUp($data[$modelClass]['id'], true); + + $parent = $this->Tree->findByName('1. Root', array('id')); + $this->Tree->id = $parent[$modelClass]['id']; + $result = $this->Tree->children(null, true, array('name')); + $expected = array( + array($modelClass => array('name' => '1.5', )), + array($modelClass => array('name' => '1.1', )), + array($modelClass => array('name' => '1.2', )), + array($modelClass => array('name' => '1.3', )), + array($modelClass => array('name' => '1.4', )), + array($modelClass => array('name' => '1.6', )), + array($modelClass => array('name' => '1.7', )), + array($modelClass => array('name' => '1.8', )), + array($modelClass => array('name' => '1.9', )), + array($modelClass => array('name' => '1.10', ))); + $this->assertSame($expected, $result); + } + +/** + * testMoveDownSuccess method + * + * @return void + */ + public function testMoveDownSuccess() { + extract($this->settings); + $this->Tree = new $modelClass(); + $this->Tree->initialize(2, 2); + + $data = $this->Tree->find('first', array('fields' => array('id'), 'conditions' => array($modelClass . '.name' => '1.1'))); + $this->Tree->moveDown($data[$modelClass]['id']); + + $parent = $this->Tree->findByName('1. Root', array('id')); + $this->Tree->id = $parent[$modelClass]['id']; + $result = $this->Tree->children(null, true, array('name')); + $expected = array(array($modelClass => array('name' => '1.2', )), + array($modelClass => array('name' => '1.1', ))); + $this->assertSame($expected, $result); + } + +/** + * testMoveDownFail method + * + * @return void + */ + public function testMoveDownFail() { + extract($this->settings); + $this->Tree = new $modelClass(); + $this->Tree->initialize(2, 2); + + $data = $this->Tree->find('first', array('conditions' => array($modelClass . '.name' => '1.2'))); + $this->Tree->moveDown($data[$modelClass]['id']); + + $parent = $this->Tree->findByName('1. Root', array('id')); + $this->Tree->id = $parent[$modelClass]['id']; + $result = $this->Tree->children(null, true, array('name')); + $expected = array(array($modelClass => array('name' => '1.1', )), + array($modelClass => array('name' => '1.2', ))); + $this->assertSame($expected, $result); + } + +/** + * testMoveDownLast method + * + * @return void + */ + public function testMoveDownLast() { + extract($this->settings); + $this->Tree = new $modelClass(); + $this->Tree->initialize(1, 10); + + $data = $this->Tree->find('first', array('fields' => array('id'), 'conditions' => array($modelClass . '.name' => '1.5'))); + $this->Tree->moveDown($data[$modelClass]['id'], true); + + $parent = $this->Tree->findByName('1. Root', array('id')); + $this->Tree->id = $parent[$modelClass]['id']; + $result = $this->Tree->children(null, true, array('name')); + $expected = array( + array($modelClass => array('name' => '1.1', )), + array($modelClass => array('name' => '1.2', )), + array($modelClass => array('name' => '1.3', )), + array($modelClass => array('name' => '1.4', )), + array($modelClass => array('name' => '1.6', )), + array($modelClass => array('name' => '1.7', )), + array($modelClass => array('name' => '1.8', )), + array($modelClass => array('name' => '1.9', )), + array($modelClass => array('name' => '1.10', )), + array($modelClass => array('name' => '1.5', ))); + $this->assertSame($expected, $result); + } + +/** + * testMoveDown2 method + * + * @return void + */ + public function testMoveDown2() { + extract($this->settings); + $this->Tree = new $modelClass(); + $this->Tree->initialize(1, 10); + + $data = $this->Tree->find('first', array('fields' => array('id'), 'conditions' => array($modelClass . '.name' => '1.5'))); + $this->Tree->moveDown($data[$modelClass]['id'], 2); + + $parent = $this->Tree->findByName('1. Root', array('id')); + $this->Tree->id = $parent[$modelClass]['id']; + $result = $this->Tree->children(null, true, array('name')); + $expected = array( + array($modelClass => array('name' => '1.1', )), + array($modelClass => array('name' => '1.2', )), + array($modelClass => array('name' => '1.3', )), + array($modelClass => array('name' => '1.4', )), + array($modelClass => array('name' => '1.6', )), + array($modelClass => array('name' => '1.7', )), + array($modelClass => array('name' => '1.5', )), + array($modelClass => array('name' => '1.8', )), + array($modelClass => array('name' => '1.9', )), + array($modelClass => array('name' => '1.10', ))); + $this->assertSame($expected, $result); + } + +/** + * testSaveNoMove method + * + * @return void + */ + public function testSaveNoMove() { + extract($this->settings); + $this->Tree = new $modelClass(); + $this->Tree->initialize(1, 10); + + $data = $this->Tree->find('first', array('fields' => array('id'), 'conditions' => array($modelClass . '.name' => '1.5'))); + $this->Tree->id = $data[$modelClass]['id']; + $this->Tree->saveField('name', 'renamed'); + $parent = $this->Tree->findByName('1. Root', array('id')); + $this->Tree->id = $parent[$modelClass]['id']; + $result = $this->Tree->children(null, true, array('name')); + $expected = array( + array($modelClass => array('name' => '1.1', )), + array($modelClass => array('name' => '1.2', )), + array($modelClass => array('name' => '1.3', )), + array($modelClass => array('name' => '1.4', )), + array($modelClass => array('name' => 'renamed', )), + array($modelClass => array('name' => '1.6', )), + array($modelClass => array('name' => '1.7', )), + array($modelClass => array('name' => '1.8', )), + array($modelClass => array('name' => '1.9', )), + array($modelClass => array('name' => '1.10', ))); + $this->assertSame($expected, $result); + } + +/** + * testMoveToRootAndMoveUp method + * + * @return void + */ + public function testMoveToRootAndMoveUp() { + extract($this->settings); + $this->Tree = new $modelClass(); + $this->Tree->initialize(1, 1); + $data = $this->Tree->find('first', array('fields' => array('id'), 'conditions' => array($modelClass . '.name' => '1.1'))); + $this->Tree->id = $data[$modelClass]['id']; + $this->Tree->save(array($parentField => null)); + + $result = $this->Tree->verify(); + $this->assertSame($result, true); + + $this->Tree->moveUp(); + + $result = $this->Tree->find('all', array('fields' => 'name', 'order' => $modelClass . '.' . $leftField . ' ASC')); + $expected = array(array($modelClass => array('name' => '1.1')), + array($modelClass => array('name' => '1. Root'))); + $this->assertSame($expected, $result); + } + +/** + * testDelete method + * + * @return void + */ + public function testDelete() { + extract($this->settings); + $this->Tree = new $modelClass(); + $this->Tree->initialize(2, 2); + + $initialCount = $this->Tree->find('count'); + $result = $this->Tree->findByName('1.1.1'); + + $return = $this->Tree->delete($result[$modelClass]['id']); + $this->assertEquals(true, $return); + + $laterCount = $this->Tree->find('count'); + $this->assertEquals($initialCount - 1, $laterCount); + + $validTree = $this->Tree->verify(); + $this->assertSame($validTree, true); + + $initialCount = $this->Tree->find('count'); + $result = $this->Tree->findByName('1.1'); + + $return = $this->Tree->delete($result[$modelClass]['id']); + $this->assertEquals(true, $return); + + $laterCount = $this->Tree->find('count'); + $this->assertEquals($initialCount - 2, $laterCount); + + $validTree = $this->Tree->verify(); + $this->assertSame($validTree, true); + } + +/** + * Test deleting a record that doesn't exist. + * + * @return void + */ + public function testDeleteDoesNotExist() { + extract($this->settings); + $this->Tree = new $modelClass(); + $this->Tree->initialize(2, 2); + $this->Tree->delete(99999); + } + +/** + * testRemove method + * + * @return void + */ + public function testRemove() { + extract($this->settings); + $this->Tree = new $modelClass(); + $this->Tree->initialize(2, 2); + $initialCount = $this->Tree->find('count'); + $result = $this->Tree->findByName('1.1'); + + $this->Tree->removeFromTree($result[$modelClass]['id']); + + $laterCount = $this->Tree->find('count'); + $this->assertEquals($initialCount, $laterCount); + + $children = $this->Tree->children($result[$modelClass][$parentField], true, array('name')); + $expects = array(array($modelClass => array('name' => '1.1.1')), + array($modelClass => array('name' => '1.1.2')), + array($modelClass => array('name' => '1.2'))); + $this->assertEquals($children, $expects); + + $topNodes = $this->Tree->children(false, true,array('name')); + $expects = array(array($modelClass => array('name' => '1. Root')), + array($modelClass => array('name' => '1.1'))); + $this->assertEquals($topNodes, $expects); + + $validTree = $this->Tree->verify(); + $this->assertSame($validTree, true); + } + +/** + * testRemoveLastTopParent method + * + * @return void + */ + public function testRemoveLastTopParent() { + extract($this->settings); + $this->Tree = new $modelClass(); + $this->Tree->initialize(2, 2); + + $initialCount = $this->Tree->find('count'); + $initialTopNodes = $this->Tree->childCount(false); + + $result = $this->Tree->findByName('1. Root'); + $this->Tree->removeFromTree($result[$modelClass]['id']); + + $laterCount = $this->Tree->find('count'); + $laterTopNodes = $this->Tree->childCount(false); + + $this->assertEquals($initialCount, $laterCount); + $this->assertEquals($initialTopNodes, $laterTopNodes); + + $topNodes = $this->Tree->children(false, true,array('name')); + $expects = array(array($modelClass => array('name' => '1.1')), + array($modelClass => array('name' => '1.2')), + array($modelClass => array('name' => '1. Root'))); + + $this->assertEquals($topNodes, $expects); + + $validTree = $this->Tree->verify(); + $this->assertSame($validTree, true); + } + +/** + * testRemoveNoChildren method + * + * @return void + */ + public function testRemoveNoChildren() { + extract($this->settings); + $this->Tree = new $modelClass(); + $this->Tree->initialize(2, 2); + $initialCount = $this->Tree->find('count'); + + $result = $this->Tree->findByName('1.1.1'); + $this->Tree->removeFromTree($result[$modelClass]['id']); + + $laterCount = $this->Tree->find('count'); + $this->assertEquals($initialCount, $laterCount); + + $nodes = $this->Tree->find('list', array('order' => $leftField)); + $expects = array( + 1 => '1. Root', + 2 => '1.1', + 4 => '1.1.2', + 5 => '1.2', + 6 => '1.2.1', + 7 => '1.2.2', + 3 => '1.1.1', + ); + + $this->assertEquals($nodes, $expects); + + $validTree = $this->Tree->verify(); + $this->assertSame($validTree, true); + } + +/** + * testRemoveAndDelete method + * + * @return void + */ + public function testRemoveAndDelete() { + extract($this->settings); + $this->Tree = new $modelClass(); + $this->Tree->initialize(2, 2); + + $initialCount = $this->Tree->find('count'); + $result = $this->Tree->findByName('1.1'); + + $this->Tree->removeFromTree($result[$modelClass]['id'], true); + + $laterCount = $this->Tree->find('count'); + $this->assertEquals($initialCount - 1, $laterCount); + + $children = $this->Tree->children($result[$modelClass][$parentField], true, array('name'), $leftField . ' asc'); + $expects = array( + array($modelClass => array('name' => '1.1.1')), + array($modelClass => array('name' => '1.1.2')), + array($modelClass => array('name' => '1.2')) + ); + $this->assertEquals($children, $expects); + + $topNodes = $this->Tree->children(false, true,array('name')); + $expects = array(array($modelClass => array('name' => '1. Root'))); + $this->assertEquals($topNodes, $expects); + + $validTree = $this->Tree->verify(); + $this->assertSame($validTree, true); + } + +/** + * testRemoveAndDeleteNoChildren method + * + * @return void + */ + public function testRemoveAndDeleteNoChildren() { + extract($this->settings); + $this->Tree = new $modelClass(); + $this->Tree->initialize(2, 2); + $initialCount = $this->Tree->find('count'); + + $result = $this->Tree->findByName('1.1.1'); + $this->Tree->removeFromTree($result[$modelClass]['id'], true); + + $laterCount = $this->Tree->find('count'); + $this->assertEquals($initialCount - 1, $laterCount); + + $nodes = $this->Tree->find('list', array('order' => $leftField)); + $expects = array( + 1 => '1. Root', + 2 => '1.1', + 4 => '1.1.2', + 5 => '1.2', + 6 => '1.2.1', + 7 => '1.2.2', + ); + $this->assertEquals($nodes, $expects); + + $validTree = $this->Tree->verify(); + $this->assertSame($validTree, true); + } + +/** + * testChildren method + * + * @return void + */ + public function testChildren() { + extract($this->settings); + $this->Tree = new $modelClass(); + $this->Tree->initialize(2, 2); + + $data = $this->Tree->find('first', array('conditions' => array($modelClass . '.name' => '1. Root'))); + $this->Tree->id = $data[$modelClass]['id']; + + $direct = $this->Tree->children(null, true, array('id', 'name', $parentField, $leftField, $rightField)); + $expects = array(array($modelClass => array('id' => 2, 'name' => '1.1', $parentField => 1, $leftField => 2, $rightField => 7)), + array($modelClass => array('id' => 5, 'name' => '1.2', $parentField => 1, $leftField => 8, $rightField => 13))); + $this->assertEquals($direct, $expects); + + $total = $this->Tree->children(null, null, array('id', 'name', $parentField, $leftField, $rightField)); + $expects = array(array($modelClass => array('id' => 2, 'name' => '1.1', $parentField => 1, $leftField => 2, $rightField => 7)), + array($modelClass => array('id' => 3, 'name' => '1.1.1', $parentField => 2, $leftField => 3, $rightField => 4)), + array($modelClass => array('id' => 4, 'name' => '1.1.2', $parentField => 2, $leftField => 5, $rightField => 6)), + array($modelClass => array('id' => 5, 'name' => '1.2', $parentField => 1, $leftField => 8, $rightField => 13)), + array($modelClass => array('id' => 6, 'name' => '1.2.1', $parentField => 5, $leftField => 9, $rightField => 10)), + array($modelClass => array('id' => 7, 'name' => '1.2.2', $parentField => 5, $leftField => 11, $rightField => 12))); + $this->assertEquals($total, $expects); + + $this->assertEquals(array(), $this->Tree->children(10000)); + } + +/** + * testCountChildren method + * + * @return void + */ + public function testCountChildren() { + extract($this->settings); + $this->Tree = new $modelClass(); + $this->Tree->initialize(2, 2); + + $data = $this->Tree->find('first', array('conditions' => array($modelClass . '.name' => '1. Root'))); + $this->Tree->id = $data[$modelClass]['id']; + + $direct = $this->Tree->childCount(null, true); + $this->assertEquals(2, $direct); + + $total = $this->Tree->childCount(); + $this->assertEquals(6, $total); + + $this->Tree->read(null, $data[$modelClass]['id']); + $id = $this->Tree->field('id', array($modelClass . '.name' => '1.2')); + $total = $this->Tree->childCount($id); + $this->assertEquals(2, $total); + } + +/** + * testGetParentNode method + * + * @return void + */ + public function testGetParentNode() { + extract($this->settings); + $this->Tree = new $modelClass(); + $this->Tree->initialize(2, 2); + + $data = $this->Tree->find('first', array('conditions' => array($modelClass . '.name' => '1.2.2'))); + $this->Tree->id = $data[$modelClass]['id']; + + $result = $this->Tree->getParentNode(null, array('name')); + $expects = array($modelClass => array('name' => '1.2')); + $this->assertSame($expects, $result); + } + +/** + * testGetPath method + * + * @return void + */ + public function testGetPath() { + extract($this->settings); + $this->Tree = new $modelClass(); + $this->Tree->initialize(2, 2); + + $data = $this->Tree->find('first', array('conditions' => array($modelClass . '.name' => '1.2.2'))); + $this->Tree->id = $data[$modelClass]['id']; + + $result = $this->Tree->getPath(null, array('name')); + $expects = array(array($modelClass => array('name' => '1. Root')), + array($modelClass => array('name' => '1.2')), + array($modelClass => array('name' => '1.2.2'))); + $this->assertSame($expects, $result); + } + +/** + * testNoAmbiguousColumn method + * + * @return void + */ + public function testNoAmbiguousColumn() { + extract($this->settings); + $this->Tree = new $modelClass(); + $this->Tree->bindModel(array('belongsTo' => array('Dummy' => + array('className' => $modelClass, 'foreignKey' => $parentField, 'conditions' => array('Dummy.id' => null)))), false); + $this->Tree->initialize(2, 2); + + $data = $this->Tree->find('first', array('conditions' => array($modelClass . '.name' => '1. Root'))); + $this->Tree->id = $data[$modelClass]['id']; + + $direct = $this->Tree->children(null, true, array('id', 'name', $parentField, $leftField, $rightField)); + $expects = array(array($modelClass => array('id' => 2, 'name' => '1.1', $parentField => 1, $leftField => 2, $rightField => 7)), + array($modelClass => array('id' => 5, 'name' => '1.2', $parentField => 1, $leftField => 8, $rightField => 13))); + $this->assertEquals($direct, $expects); + + $total = $this->Tree->children(null, null, array('id', 'name', $parentField, $leftField, $rightField)); + $expects = array( + array($modelClass => array('id' => 2, 'name' => '1.1', $parentField => 1, $leftField => 2, $rightField => 7)), + array($modelClass => array('id' => 3, 'name' => '1.1.1', $parentField => 2, $leftField => 3, $rightField => 4)), + array($modelClass => array('id' => 4, 'name' => '1.1.2', $parentField => 2, $leftField => 5, $rightField => 6)), + array($modelClass => array('id' => 5, 'name' => '1.2', $parentField => 1, $leftField => 8, $rightField => 13)), + array($modelClass => array('id' => 6, 'name' => '1.2.1', $parentField => 5, $leftField => 9, $rightField => 10)), + array($modelClass => array('id' => 7, 'name' => '1.2.2', $parentField => 5, $leftField => 11, $rightField => 12)) + ); + $this->assertEquals($total, $expects); + } + +/** + * testReorderTree method + * + * @return void + */ + public function testReorderTree() { + extract($this->settings); + $this->Tree = new $modelClass(); + $this->Tree->initialize(3, 3); + $nodes = $this->Tree->find('list', array('order' => $leftField)); + + $data = $this->Tree->find('first', array('fields' => array('id'), 'conditions' => array($modelClass . '.name' => '1.1'))); + $this->Tree->moveDown($data[$modelClass]['id']); + + $data = $this->Tree->find('first', array('fields' => array('id'), 'conditions' => array($modelClass . '.name' => '1.2.1'))); + $this->Tree->moveDown($data[$modelClass]['id']); + + $data = $this->Tree->find('first', array('fields' => array('id'), 'conditions' => array($modelClass . '.name' => '1.3.2.2'))); + $this->Tree->moveDown($data[$modelClass]['id']); + + $unsortedNodes = $this->Tree->find('list', array('order' => $leftField)); + $this->assertEquals($nodes, $unsortedNodes); + $this->assertNotEquals(array_keys($nodes), array_keys($unsortedNodes)); + + $this->Tree->reorder(); + $sortedNodes = $this->Tree->find('list', array('order' => $leftField)); + $this->assertSame($nodes, $sortedNodes); + } + +/** + * test reordering large-ish trees with cacheQueries = true. + * This caused infinite loops when moving down elements as stale data is returned + * from the memory cache + * + * @return void + */ + public function testReorderBigTreeWithQueryCaching() { + extract($this->settings); + $this->Tree = new $modelClass(); + $this->Tree->initialize(2, 10); + + $original = $this->Tree->cacheQueries; + $this->Tree->cacheQueries = true; + $this->Tree->reorder(array('field' => 'name', 'direction' => 'DESC')); + $this->assertTrue($this->Tree->cacheQueries, 'cacheQueries was not restored after reorder(). %s'); + $this->Tree->cacheQueries = $original; + } + +/** + * testGenerateTreeListWithSelfJoin method + * + * @return void + */ + public function testGenerateTreeListWithSelfJoin() { + extract($this->settings); + $this->Tree = new $modelClass(); + $this->Tree->bindModel(array('belongsTo' => array('Dummy' => + array('className' => $modelClass, 'foreignKey' => $parentField, 'conditions' => array('Dummy.id' => null)))), false); + $this->Tree->initialize(2, 2); + + $result = $this->Tree->generateTreeList(); + $expected = array(1 => '1. Root', 2 => '_1.1', 3 => '__1.1.1', 4 => '__1.1.2', 5 => '_1.2', 6 => '__1.2.1', 7 => '__1.2.2'); + $this->assertSame($expected, $result); + } + +/** + * testArraySyntax method + * + * @return void + */ + public function testArraySyntax() { + extract($this->settings); + $this->Tree = new $modelClass(); + $this->Tree->initialize(3, 3); + $this->assertSame($this->Tree->childCount(2), $this->Tree->childCount(array('id' => 2))); + $this->assertSame($this->Tree->getParentNode(2), $this->Tree->getParentNode(array('id' => 2))); + $this->assertSame($this->Tree->getPath(4), $this->Tree->getPath(array('id' => 4))); + } + +/** + * testFindThreaded method + * + * @return void + */ + public function testFindThreaded() { + $Model = new Person(); + $Model->recursive = -1; + $Model->Behaviors->attach('Tree', array('parent' => 'mother_id')); + + $result = $Model->find('threaded'); + $expected = array( + array( + 'Person' => array( + 'id' => '4', + 'name' => 'mother - grand mother', + 'mother_id' => '0', + 'father_id' => '0' + ), + 'children' => array( + array( + 'Person' => array( + 'id' => '2', + 'name' => 'mother', + 'mother_id' => '4', + 'father_id' => '5' + ), + 'children' => array( + array( + 'Person' => array( + 'id' => '1', + 'name' => 'person', + 'mother_id' => '2', + 'father_id' => '3' + ), + 'children' => array() + ) + ) + ) + ) + ), + array( + 'Person' => array( + 'id' => '5', + 'name' => 'mother - grand father', + 'mother_id' => '0', + 'father_id' => '0' + ), + 'children' => array() + ), + array( + 'Person' => array( + 'id' => '6', + 'name' => 'father - grand mother', + 'mother_id' => '0', + 'father_id' => '0' + ), + 'children' => array( + array( + 'Person' => array( + 'id' => '3', + 'name' => 'father', + 'mother_id' => '6', + 'father_id' => '7' + ), + 'children' => array() + ) + ) + ), + array( + 'Person' => array( + 'id' => '7', + 'name' => 'father - grand father', + 'mother_id' => '0', + 'father_id' => '0' + ), + 'children' => array() + ) + ); + $this->assertEquals($expected, $result); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Behavior/TreeBehaviorScopedTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Behavior/TreeBehaviorScopedTest.php new file mode 100644 index 0000000..b9e8297 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Behavior/TreeBehaviorScopedTest.php @@ -0,0 +1,316 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Model.Behavior + * @since CakePHP(tm) v 1.2.0.5330 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ + +App::uses('Model', 'Model'); +App::uses('AppModel', 'Model'); +require_once dirname(dirname(__FILE__)) . DS . 'models.php'; + +/** + * TreeBehaviorScopedTest class + * + * @package Cake.Test.Case.Model.Behavior + */ +class TreeBehaviorScopedTest extends CakeTestCase { + +/** + * Whether backup global state for each test method or not + * + * @var bool false + */ + public $backupGlobals = false; + +/** + * settings property + * + * @var array + */ + public $settings = array( + 'modelClass' => 'FlagTree', + 'leftField' => 'lft', + 'rightField' => 'rght', + 'parentField' => 'parent_id' + ); + +/** + * fixtures property + * + * @var array + */ + public $fixtures = array('core.flag_tree', 'core.ad', 'core.campaign', 'core.translate', 'core.number_tree_two'); + +/** + * testStringScope method + * + * @return void + */ + public function testStringScope() { + $this->Tree = new FlagTree(); + $this->Tree->initialize(2, 3); + + $this->Tree->id = 1; + $this->Tree->saveField('flag', 1); + $this->Tree->id = 2; + $this->Tree->saveField('flag', 1); + + $result = $this->Tree->children(); + $expected = array( + array('FlagTree' => array('id' => '3', 'name' => '1.1.1', 'parent_id' => '2', 'lft' => '3', 'rght' => '4', 'flag' => '0')), + array('FlagTree' => array('id' => '4', 'name' => '1.1.2', 'parent_id' => '2', 'lft' => '5', 'rght' => '6', 'flag' => '0')), + array('FlagTree' => array('id' => '5', 'name' => '1.1.3', 'parent_id' => '2', 'lft' => '7', 'rght' => '8', 'flag' => '0')) + ); + $this->assertEquals($expected, $result); + + $this->Tree->Behaviors->attach('Tree', array('scope' => 'FlagTree.flag = 1')); + $this->assertEquals(array(), $this->Tree->children()); + + $this->Tree->id = 1; + $this->Tree->Behaviors->attach('Tree', array('scope' => 'FlagTree.flag = 1')); + + $result = $this->Tree->children(); + $expected = array(array('FlagTree' => array('id' => '2', 'name' => '1.1', 'parent_id' => '1', 'lft' => '2', 'rght' => '9', 'flag' => '1'))); + $this->assertEquals($expected, $result); + + $this->assertTrue($this->Tree->delete()); + $this->assertEquals(11, $this->Tree->find('count')); + } + +/** + * testArrayScope method + * + * @return void + */ + public function testArrayScope() { + $this->Tree = new FlagTree(); + $this->Tree->initialize(2, 3); + + $this->Tree->id = 1; + $this->Tree->saveField('flag', 1); + $this->Tree->id = 2; + $this->Tree->saveField('flag', 1); + + $result = $this->Tree->children(); + $expected = array( + array('FlagTree' => array('id' => '3', 'name' => '1.1.1', 'parent_id' => '2', 'lft' => '3', 'rght' => '4', 'flag' => '0')), + array('FlagTree' => array('id' => '4', 'name' => '1.1.2', 'parent_id' => '2', 'lft' => '5', 'rght' => '6', 'flag' => '0')), + array('FlagTree' => array('id' => '5', 'name' => '1.1.3', 'parent_id' => '2', 'lft' => '7', 'rght' => '8', 'flag' => '0')) + ); + $this->assertEquals($expected, $result); + + $this->Tree->Behaviors->attach('Tree', array('scope' => array('FlagTree.flag' => 1))); + $this->assertEquals(array(), $this->Tree->children()); + + $this->Tree->id = 1; + $this->Tree->Behaviors->attach('Tree', array('scope' => array('FlagTree.flag' => 1))); + + $result = $this->Tree->children(); + $expected = array(array('FlagTree' => array('id' => '2', 'name' => '1.1', 'parent_id' => '1', 'lft' => '2', 'rght' => '9', 'flag' => '1'))); + $this->assertEquals($expected, $result); + + $this->assertTrue($this->Tree->delete()); + $this->assertEquals(11, $this->Tree->find('count')); + } + +/** + * testMoveUpWithScope method + * + * @return void + */ + public function testMoveUpWithScope() { + $this->Ad = new Ad(); + $this->Ad->Behaviors->attach('Tree', array('scope' => 'Campaign')); + $this->Ad->moveUp(6); + + $this->Ad->id = 4; + $result = $this->Ad->children(); + $this->assertEquals(array(6, 5), Hash::extract($result, '{n}.Ad.id')); + $this->assertEquals(array(2, 2), Hash::extract($result, '{n}.Campaign.id')); + } + +/** + * testMoveDownWithScope method + * + * @return void + */ + public function testMoveDownWithScope() { + $this->Ad = new Ad(); + $this->Ad->Behaviors->attach('Tree', array('scope' => 'Campaign')); + $this->Ad->moveDown(6); + + $this->Ad->id = 4; + $result = $this->Ad->children(); + $this->assertEquals(array(5, 6), Hash::extract($result, '{n}.Ad.id')); + $this->assertEquals(array(2, 2), Hash::extract($result, '{n}.Campaign.id')); + } + +/** + * Tests the interaction (non-interference) between TreeBehavior and other behaviors with respect + * to callback hooks + * + * @return void + */ + public function testTranslatingTree() { + $this->Tree = new FlagTree(); + $this->Tree->cacheQueries = false; + $this->Tree->Behaviors->attach('Translate', array('name')); + + //Save + $this->Tree->locale = 'eng'; + $data = array('FlagTree' => array( + 'name' => 'name #1', + 'locale' => 'eng', + 'parent_id' => null, + )); + $this->Tree->save($data); + $result = $this->Tree->find('all'); + $expected = array(array('FlagTree' => array( + 'id' => 1, + 'name' => 'name #1', + 'parent_id' => null, + 'lft' => 1, + 'rght' => 2, + 'flag' => 0, + 'locale' => 'eng', + ))); + $this->assertEquals($expected, $result); + + //update existing record, same locale + $this->Tree->create(); + $data['FlagTree']['name'] = 'Named 2'; + $this->Tree->id = 1; + $this->Tree->save($data); + $result = $this->Tree->find('all'); + $expected = array(array('FlagTree' => array( + 'id' => 1, + 'name' => 'Named 2', + 'parent_id' => null, + 'lft' => 1, + 'rght' => 2, + 'flag' => 0, + 'locale' => 'eng', + ))); + $this->assertEquals($expected, $result); + + //update different locale, same record + $this->Tree->create(); + $this->Tree->locale = 'deu'; + $this->Tree->id = 1; + $data = array('FlagTree' => array( + 'id' => 1, + 'parent_id' => null, + 'name' => 'namen #1', + 'locale' => 'deu', + )); + $this->Tree->save($data); + + $this->Tree->locale = 'deu'; + $result = $this->Tree->find('all'); + $expected = array(array('FlagTree' => array( + 'id' => 1, + 'name' => 'namen #1', + 'parent_id' => null, + 'lft' => 1, + 'rght' => 2, + 'flag' => 0, + 'locale' => 'deu', + ))); + $this->assertEquals($expected, $result); + + //Save with bindTranslation + $this->Tree->locale = 'eng'; + $data = array( + 'name' => array('eng' => 'New title', 'spa' => 'Nuevo leyenda'), + 'parent_id' => null + ); + $this->Tree->create($data); + $this->Tree->save(); + + $this->Tree->unbindTranslation(); + $translations = array('name' => 'Name'); + $this->Tree->bindTranslation($translations, false); + $this->Tree->locale = array('eng', 'spa'); + + $result = $this->Tree->read(); + $expected = array( + 'FlagTree' => array('id' => 2, 'parent_id' => null, 'locale' => 'eng', 'name' => 'New title', 'flag' => 0, 'lft' => 3, 'rght' => 4), + 'Name' => array( + array('id' => 21, 'locale' => 'eng', 'model' => 'FlagTree', 'foreign_key' => 2, 'field' => 'name', 'content' => 'New title'), + array('id' => 22, 'locale' => 'spa', 'model' => 'FlagTree', 'foreign_key' => 2, 'field' => 'name', 'content' => 'Nuevo leyenda') + ), + ); + $this->assertEquals($expected, $result); + } + +/** + * testGenerateTreeListWithSelfJoin method + * + * @return void + */ + public function testAliasesWithScopeInTwoTreeAssociations() { + extract($this->settings); + $this->Tree = new $modelClass(); + $this->Tree->initialize(2, 2); + + $this->TreeTwo = new NumberTreeTwo(); + + $record = $this->Tree->find('first'); + + $this->Tree->bindModel(array( + 'hasMany' => array( + 'SecondTree' => array( + 'className' => 'NumberTreeTwo', + 'foreignKey' => 'number_tree_id' + ) + ) + )); + $this->TreeTwo->bindModel(array( + 'belongsTo' => array( + 'FirstTree' => array( + 'className' => $modelClass, + 'foreignKey' => 'number_tree_id' + ) + ) + )); + $this->TreeTwo->Behaviors->attach('Tree', array( + 'scope' => 'FirstTree' + )); + + $data = array( + 'NumberTreeTwo' => array( + 'name' => 'First', + 'number_tree_id' => $record['FlagTree']['id'] + ) + ); + $this->TreeTwo->create(); + $result = $this->TreeTwo->save($data); + $this->assertFalse(empty($result)); + + $result = $this->TreeTwo->find('first'); + $expected = array('NumberTreeTwo' => array( + 'id' => 1, + 'name' => 'First', + 'number_tree_id' => $record['FlagTree']['id'], + 'parent_id' => null, + 'lft' => 1, + 'rght' => 2 + )); + $this->assertEquals($expected, $result); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Behavior/TreeBehaviorTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Behavior/TreeBehaviorTest.php new file mode 100644 index 0000000..4b55e7e --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Behavior/TreeBehaviorTest.php @@ -0,0 +1,43 @@ +addTestFile(CORE_TEST_CASES . DS . 'Model' . DS . 'Behavior' . DS . 'TreeBehaviorNumberTest.php'); + $suite->addTestFile(CORE_TEST_CASES . DS . 'Model' . DS . 'Behavior' . DS . 'TreeBehaviorScopedTest.php'); + $suite->addTestFile(CORE_TEST_CASES . DS . 'Model' . DS . 'Behavior' . DS . 'TreeBehaviorAfterTest.php'); + $suite->addTestFile(CORE_TEST_CASES . DS . 'Model' . DS . 'Behavior' . DS . 'TreeBehaviorUuidTest.php'); + return $suite; + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Behavior/TreeBehaviorUuidTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Behavior/TreeBehaviorUuidTest.php new file mode 100644 index 0000000..a69445e --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Behavior/TreeBehaviorUuidTest.php @@ -0,0 +1,255 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Model.Behavior + * @since CakePHP(tm) v 1.2.0.5330 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ + +App::uses('Model', 'Model'); +App::uses('AppModel', 'Model'); +require_once dirname(dirname(__FILE__)) . DS . 'models.php'; + +/** + * TreeBehaviorUuidTest class + * + * @package Cake.Test.Case.Model.Behavior + */ +class TreeBehaviorUuidTest extends CakeTestCase { + +/** + * Whether backup global state for each test method or not + * + * @var bool false + */ + public $backupGlobals = false; + +/** + * settings property + * + * @var array + */ + public $settings = array( + 'modelClass' => 'UuidTree', + 'leftField' => 'lft', + 'rightField' => 'rght', + 'parentField' => 'parent_id' + ); + +/** + * fixtures property + * + * @var array + */ + public $fixtures = array('core.uuid_tree'); + +/** + * testMovePromote method + * + * @return void + */ + public function testMovePromote() { + extract($this->settings); + $this->Tree = new $modelClass(); + $this->Tree->initialize(2, 2); + $this->Tree->id = null; + + $parent = $this->Tree->find('first', array('conditions' => array($modelClass . '.name' => '1. Root'))); + $parentId = $parent[$modelClass]['id']; + + $data = $this->Tree->find('first', array('fields' => array('id'), 'conditions' => array($modelClass . '.name' => '1.1.1'))); + $this->Tree->id = $data[$modelClass]['id']; + $this->Tree->saveField($parentField, $parentId); + $direct = $this->Tree->children($parentId, true, array('name', $leftField, $rightField)); + $expects = array(array($modelClass => array('name' => '1.1', $leftField => 2, $rightField => 5)), + array($modelClass => array('name' => '1.2', $leftField => 6, $rightField => 11)), + array($modelClass => array('name' => '1.1.1', $leftField => 12, $rightField => 13))); + $this->assertEquals($direct, $expects); + $validTree = $this->Tree->verify(); + $this->assertSame($validTree, true); + } + +/** + * testMoveWithWhitelist method + * + * @return void + */ + public function testMoveWithWhitelist() { + extract($this->settings); + $this->Tree = new $modelClass(); + $this->Tree->initialize(2, 2); + $this->Tree->id = null; + + $parent = $this->Tree->find('first', array('conditions' => array($modelClass . '.name' => '1. Root'))); + $parentId = $parent[$modelClass]['id']; + + $data = $this->Tree->find('first', array('fields' => array('id'), 'conditions' => array($modelClass . '.name' => '1.1.1'))); + $this->Tree->id = $data[$modelClass]['id']; + $this->Tree->whitelist = array($parentField, 'name', 'description'); + $this->Tree->saveField($parentField, $parentId); + + $result = $this->Tree->children($parentId, true, array('name', $leftField, $rightField)); + $expected = array(array($modelClass => array('name' => '1.1', $leftField => 2, $rightField => 5)), + array($modelClass => array('name' => '1.2', $leftField => 6, $rightField => 11)), + array($modelClass => array('name' => '1.1.1', $leftField => 12, $rightField => 13))); + $this->assertEquals($expected, $result); + $this->assertTrue($this->Tree->verify()); + } + +/** + * testRemoveNoChildren method + * + * @return void + */ + public function testRemoveNoChildren() { + extract($this->settings); + $this->Tree = new $modelClass(); + $this->Tree->initialize(2, 2); + $initialCount = $this->Tree->find('count'); + + $result = $this->Tree->findByName('1.1.1'); + $this->Tree->removeFromTree($result[$modelClass]['id']); + + $laterCount = $this->Tree->find('count'); + $this->assertEquals($initialCount, $laterCount); + + $nodes = $this->Tree->find('list', array('order' => $leftField)); + $expects = array( + '1. Root', + '1.1', + '1.1.2', + '1.2', + '1.2.1', + '1.2.2', + '1.1.1', + ); + + $this->assertEquals(array_values($nodes), $expects); + + $validTree = $this->Tree->verify(); + $this->assertSame($validTree, true); + } + +/** + * testRemoveAndDeleteNoChildren method + * + * @return void + */ + public function testRemoveAndDeleteNoChildren() { + extract($this->settings); + $this->Tree = new $modelClass(); + $this->Tree->initialize(2, 2); + $initialCount = $this->Tree->find('count'); + + $result = $this->Tree->findByName('1.1.1'); + $this->Tree->removeFromTree($result[$modelClass]['id'], true); + + $laterCount = $this->Tree->find('count'); + $this->assertEquals($initialCount - 1, $laterCount); + + $nodes = $this->Tree->find('list', array('order' => $leftField)); + $expects = array( + '1. Root', + '1.1', + '1.1.2', + '1.2', + '1.2.1', + '1.2.2', + ); + $this->assertEquals(array_values($nodes), $expects); + + $validTree = $this->Tree->verify(); + $this->assertSame($validTree, true); + } + +/** + * testChildren method + * + * @return void + */ + public function testChildren() { + extract($this->settings); + $this->Tree = new $modelClass(); + $this->Tree->initialize(2, 2); + + $data = $this->Tree->find('first', array('conditions' => array($modelClass . '.name' => '1. Root'))); + $this->Tree->id = $data[$modelClass]['id']; + + $direct = $this->Tree->children(null, true, array('name', $leftField, $rightField)); + $expects = array(array($modelClass => array('name' => '1.1', $leftField => 2, $rightField => 7)), + array($modelClass => array('name' => '1.2', $leftField => 8, $rightField => 13))); + $this->assertEquals($direct, $expects); + + $total = $this->Tree->children(null, null, array('name', $leftField, $rightField)); + $expects = array(array($modelClass => array('name' => '1.1', $leftField => 2, $rightField => 7)), + array($modelClass => array('name' => '1.1.1', $leftField => 3, $rightField => 4)), + array($modelClass => array('name' => '1.1.2', $leftField => 5, $rightField => 6)), + array($modelClass => array('name' => '1.2', $leftField => 8, $rightField => 13)), + array($modelClass => array('name' => '1.2.1', $leftField => 9, $rightField => 10)), + array($modelClass => array('name' => '1.2.2', $leftField => 11, $rightField => 12))); + $this->assertEquals($total, $expects); + } + +/** + * testNoAmbiguousColumn method + * + * @return void + */ + public function testNoAmbiguousColumn() { + extract($this->settings); + $this->Tree = new $modelClass(); + $this->Tree->initialize(2, 2); + + $this->Tree->bindModel(array('belongsTo' => array('Dummy' => + array('className' => $modelClass, 'foreignKey' => $parentField, 'conditions' => array('Dummy.id' => null)))), false); + + $data = $this->Tree->find('first', array('conditions' => array($modelClass . '.name' => '1. Root'))); + $this->Tree->id = $data[$modelClass]['id']; + + $direct = $this->Tree->children(null, true, array('name', $leftField, $rightField)); + $expects = array(array($modelClass => array('name' => '1.1', $leftField => 2, $rightField => 7)), + array($modelClass => array('name' => '1.2', $leftField => 8, $rightField => 13))); + $this->assertEquals($direct, $expects); + + $total = $this->Tree->children(null, null, array('name', $leftField, $rightField)); + $expects = array( + array($modelClass => array('name' => '1.1', $leftField => 2, $rightField => 7)), + array($modelClass => array('name' => '1.1.1', $leftField => 3, $rightField => 4)), + array($modelClass => array('name' => '1.1.2', $leftField => 5, $rightField => 6)), + array($modelClass => array('name' => '1.2', $leftField => 8, $rightField => 13)), + array($modelClass => array('name' => '1.2.1', $leftField => 9, $rightField => 10)), + array($modelClass => array('name' => '1.2.2', $leftField => 11, $rightField => 12)) + ); + $this->assertEquals($total, $expects); + } + +/** + * testGenerateTreeListWithSelfJoin method + * + * @return void + */ + public function testGenerateTreeListWithSelfJoin() { + extract($this->settings); + $this->Tree = new $modelClass(); + $this->Tree->bindModel(array('belongsTo' => array('Dummy' => + array('className' => $modelClass, 'foreignKey' => $parentField, 'conditions' => array('Dummy.id' => null)))), false); + $this->Tree->initialize(2, 2); + + $result = $this->Tree->generateTreeList(); + $expected = array('1. Root', '_1.1', '__1.1.1', '__1.1.2', '_1.2', '__1.2.1', '__1.2.2'); + $this->assertSame(array_values($result), $expected); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/BehaviorCollectionTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/BehaviorCollectionTest.php new file mode 100644 index 0000000..b2b26b7 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/BehaviorCollectionTest.php @@ -0,0 +1,1185 @@ + 'testMethod', '/look for\s+(.+)/' => 'speakEnglish'); + +/** + * setup method + * + * @param Model $model + * @param array $config + * @return void + */ + public function setup(Model $model, $config = array()) { + parent::setup($model, $config); + if (isset($config['mangle'])) { + $config['mangle'] .= ' mangled'; + } + $this->settings[$model->alias] = array_merge(array('beforeFind' => 'on', 'afterFind' => 'off'), $config); + } + +/** + * beforeFind method + * + * @param Model $model + * @param array $query + * @return void + */ + public function beforeFind(Model $model, $query) { + $settings = $this->settings[$model->alias]; + if (!isset($settings['beforeFind']) || $settings['beforeFind'] == 'off') { + return parent::beforeFind($model, $query); + } + switch ($settings['beforeFind']) { + case 'on': + return false; + break; + case 'test': + return null; + break; + case 'modify': + $query['fields'] = array($model->alias . '.id', $model->alias . '.name', $model->alias . '.mytime'); + $query['recursive'] = -1; + return $query; + break; + } + } + +/** + * afterFind method + * + * @param Model $model + * @param array $results + * @param boolean $primary + * @return void + */ + public function afterFind(Model $model, $results, $primary) { + $settings = $this->settings[$model->alias]; + if (!isset($settings['afterFind']) || $settings['afterFind'] == 'off') { + return parent::afterFind($model, $results, $primary); + } + switch ($settings['afterFind']) { + case 'on': + return array(); + break; + case 'test': + return true; + break; + case 'test2': + return null; + break; + case 'modify': + return Hash::extract($results, "{n}.{$model->alias}"); + break; + } + } + +/** + * beforeSave method + * + * @param Model $model + * @return void + */ + public function beforeSave(Model $model) { + $settings = $this->settings[$model->alias]; + if (!isset($settings['beforeSave']) || $settings['beforeSave'] == 'off') { + return parent::beforeSave($model); + } + switch ($settings['beforeSave']) { + case 'on': + return false; + break; + case 'test': + return true; + break; + case 'modify': + $model->data[$model->alias]['name'] .= ' modified before'; + return true; + break; + } + } + +/** + * afterSave method + * + * @param Model $model + * @param boolean $created + * @return void + */ + public function afterSave(Model $model, $created) { + $settings = $this->settings[$model->alias]; + if (!isset($settings['afterSave']) || $settings['afterSave'] == 'off') { + return parent::afterSave($model, $created); + } + $string = 'modified after'; + if ($created) { + $string .= ' on create'; + } + switch ($settings['afterSave']) { + case 'on': + $model->data[$model->alias]['aftersave'] = $string; + break; + case 'test': + unset($model->data[$model->alias]['name']); + break; + case 'test2': + return false; + break; + case 'modify': + $model->data[$model->alias]['name'] .= ' ' . $string; + break; + } + } + +/** + * beforeValidate method + * + * @param Model $model + * @return void + */ + public function beforeValidate(Model $model) { + $settings = $this->settings[$model->alias]; + if (!isset($settings['validate']) || $settings['validate'] == 'off') { + return parent::beforeValidate($model); + } + switch ($settings['validate']) { + case 'on': + $model->invalidate('name'); + return true; + break; + case 'test': + return null; + break; + case 'whitelist': + $this->_addToWhitelist($model, array('name')); + return true; + break; + case 'stop': + $model->invalidate('name'); + return false; + break; + } + } + +/** + * afterValidate method + * + * @param Model $model + * @param bool $cascade + * @return void + */ + public function afterValidate(Model $model) { + $settings = $this->settings[$model->alias]; + if (!isset($settings['afterValidate']) || $settings['afterValidate'] == 'off') { + return parent::afterValidate($model); + } + switch ($settings['afterValidate']) { + case 'on': + return false; + break; + case 'test': + $model->data = array('foo'); + return true; + break; + } + } + +/** + * beforeDelete method + * + * @param Model $model + * @param bool $cascade + * @return void + */ + public function beforeDelete(Model $model, $cascade = true) { + $settings = $this->settings[$model->alias]; + if (!isset($settings['beforeDelete']) || $settings['beforeDelete'] == 'off') { + return parent::beforeDelete($model, $cascade); + } + switch ($settings['beforeDelete']) { + case 'on': + return false; + break; + case 'test': + return null; + break; + case 'test2': + echo 'beforeDelete success'; + if ($cascade) { + echo ' (cascading) '; + } + return true; + break; + } + } + +/** + * afterDelete method + * + * @param Model $model + * @return void + */ + public function afterDelete(Model $model) { + $settings = $this->settings[$model->alias]; + if (!isset($settings['afterDelete']) || $settings['afterDelete'] == 'off') { + return parent::afterDelete($model); + } + switch ($settings['afterDelete']) { + case 'on': + echo 'afterDelete success'; + break; + } + } + +/** + * onError method + * + * @param Model $model + * @return void + */ + public function onError(Model $model, $error) { + $settings = $this->settings[$model->alias]; + if (!isset($settings['onError']) || $settings['onError'] == 'off') { + return parent::onError($model, $error); + } + echo "onError trigger success"; + } + +/** + * beforeTest method + * + * @param Model $model + * @return void + */ + public function beforeTest(Model $model) { + if (!isset($model->beforeTestResult)) { + $model->beforeTestResult = array(); + } + $model->beforeTestResult[] = strtolower(get_class($this)); + return strtolower(get_class($this)); + } + +/** + * testMethod method + * + * @param Model $model + * @param bool $param + * @return void + */ + public function testMethod(Model $model, $param = true) { + if ($param === true) { + return 'working'; + } + } + +/** + * testData method + * + * @param Model $model + * @return void + */ + public function testData(Model $model) { + if (!isset($model->data['Apple']['field'])) { + return false; + } + $model->data['Apple']['field_2'] = true; + return true; + } + +/** + * validateField method + * + * @param Model $model + * @param string|array $field + * @return void + */ + public function validateField(Model $model, $field) { + return current($field) === 'Orange'; + } + +/** + * speakEnglish method + * + * @param Model $model + * @param string $method + * @param string $query + * @return void + */ + public function speakEnglish(Model $model, $method, $query) { + $method = preg_replace('/look for\s+/', 'Item.name = \'', $method); + $query = preg_replace('/^in\s+/', 'Location.name = \'', $query); + return $method . '\' AND ' . $query . '\''; + } + +} + +/** + * Test2Behavior class + * + * @package Cake.Test.Case.Model + */ +class Test2Behavior extends TestBehavior { + + public $mapMethods = array('/mappingRobot(\w+)/' => 'mapped'); + + public function resolveMethod(Model $model, $stuff) { + } + + public function mapped(Model $model, $method, $query) { + } + +} + +/** + * Test3Behavior class + * + * @package Cake.Test.Case.Model + */ +class Test3Behavior extends TestBehavior{ +} + +/** + * Test4Behavior class + * + * @package Cake.Test.Case.Model + */ +class Test4Behavior extends ModelBehavior{ + + public function setup(Model $model, $config = null) { + $model->bindModel( + array('hasMany' => array('Comment')) + ); + } + +} + +/** + * Test5Behavior class + * + * @package Cake.Test.Case.Model + */ +class Test5Behavior extends ModelBehavior{ + + public function setup(Model $model, $config = null) { + $model->bindModel( + array('belongsTo' => array('User')) + ); + } + +} + +/** + * Test6Behavior class + * + * @package Cake.Test.Case.Model + */ +class Test6Behavior extends ModelBehavior{ + + public function setup(Model $model, $config = null) { + $model->bindModel( + array('hasAndBelongsToMany' => array('Tag')) + ); + } + +} + +/** + * Test7Behavior class + * + * @package Cake.Test.Case.Model + */ +class Test7Behavior extends ModelBehavior{ + + public function setup(Model $model, $config = null) { + $model->bindModel( + array('hasOne' => array('Attachment')) + ); + } + +} + +/** + * Extended TestBehavior + */ +class TestAliasBehavior extends TestBehavior { +} + +/** + * BehaviorCollection class + * + * @package Cake.Test.Case.Model + */ +class BehaviorCollectionTest extends CakeTestCase { + +/** + * fixtures property + * + * @var array + */ + public $fixtures = array( + 'core.apple', 'core.sample', 'core.article', 'core.user', 'core.comment', + 'core.attachment', 'core.tag', 'core.articles_tag', 'core.translate' + ); + +/** + * Test load() with enabled => false + * + */ + public function testLoadDisabled() { + $Apple = new Apple(); + $this->assertSame(array(), $Apple->Behaviors->attached()); + + $Apple->Behaviors->load('Translate', array('enabled' => false)); + $this->assertTrue($Apple->Behaviors->attached('Translate')); + $this->assertFalse($Apple->Behaviors->enabled('Translate')); + } + +/** + * Tests loading aliased behaviors + */ + public function testLoadAlias() { + $Apple = new Apple(); + $this->assertSame(array(), $Apple->Behaviors->attached()); + + $Apple->Behaviors->load('Test', array('className' => 'TestAlias', 'somesetting' => true)); + $this->assertSame(array('Test'), $Apple->Behaviors->attached()); + $this->assertInstanceOf('TestAliasBehavior', $Apple->Behaviors->Test); + $this->assertTrue($Apple->Behaviors->Test->settings['Apple']['somesetting']); + + $this->assertEquals('working', $Apple->Behaviors->Test->testMethod($Apple, true)); + $this->assertEquals('working', $Apple->testMethod(true)); + $this->assertEquals('working', $Apple->Behaviors->dispatchMethod($Apple, 'testMethod')); + + App::build(array('Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS))); + CakePlugin::load('TestPlugin'); + $this->assertTrue($Apple->Behaviors->load('SomeOther', array('className' => 'TestPlugin.TestPluginPersisterOne'))); + $this->assertInstanceOf('TestPluginPersisterOneBehavior', $Apple->Behaviors->SomeOther); + + $result = $Apple->Behaviors->attached(); + $this->assertEquals(array('Test', 'SomeOther'), $result, 'attached() results are wrong.'); + App::build(); + CakePlugin::unload(); + } + +/** + * testBehaviorBinding method + * + * @return void + */ + public function testBehaviorBinding() { + $Apple = new Apple(); + $this->assertSame(array(), $Apple->Behaviors->attached()); + + $Apple->Behaviors->attach('Test', array('key' => 'value')); + $this->assertSame(array('Test'), $Apple->Behaviors->attached()); + $this->assertEquals('testbehavior', strtolower(get_class($Apple->Behaviors->Test))); + $expected = array('beforeFind' => 'on', 'afterFind' => 'off', 'key' => 'value'); + $this->assertEquals($expected, $Apple->Behaviors->Test->settings['Apple']); + $this->assertEquals(array('Apple'), array_keys($Apple->Behaviors->Test->settings)); + + $this->assertSame($Apple->Sample->Behaviors->attached(), array()); + $Apple->Sample->Behaviors->attach('Test', array('key2' => 'value2')); + $this->assertSame($Apple->Sample->Behaviors->attached(), array('Test')); + $this->assertEquals(array('beforeFind' => 'on', 'afterFind' => 'off', 'key2' => 'value2'), $Apple->Sample->Behaviors->Test->settings['Sample']); + + $this->assertEquals(array('Apple', 'Sample'), array_keys($Apple->Behaviors->Test->settings)); + $this->assertSame( + $Apple->Sample->Behaviors->Test->settings, + $Apple->Behaviors->Test->settings + ); + $this->assertNotSame($Apple->Behaviors->Test->settings['Apple'], $Apple->Sample->Behaviors->Test->settings['Sample']); + + $Apple->Behaviors->attach('Test', array('key2' => 'value2', 'key3' => 'value3', 'beforeFind' => 'off')); + $Apple->Sample->Behaviors->attach('Test', array('key' => 'value', 'key3' => 'value3', 'beforeFind' => 'off')); + $this->assertEquals(array('beforeFind' => 'off', 'afterFind' => 'off', 'key' => 'value', 'key2' => 'value2', 'key3' => 'value3'), $Apple->Behaviors->Test->settings['Apple']); + $this->assertEquals($Apple->Behaviors->Test->settings['Apple'], $Apple->Sample->Behaviors->Test->settings['Sample']); + + $this->assertFalse(isset($Apple->Child->Behaviors->Test)); + $Apple->Child->Behaviors->attach('Test', array('key' => 'value', 'key2' => 'value2', 'key3' => 'value3', 'beforeFind' => 'off')); + $this->assertEquals($Apple->Child->Behaviors->Test->settings['Child'], $Apple->Sample->Behaviors->Test->settings['Sample']); + + $this->assertFalse(isset($Apple->Parent->Behaviors->Test)); + $Apple->Parent->Behaviors->attach('Test', array('key' => 'value', 'key2' => 'value2', 'key3' => 'value3', 'beforeFind' => 'off')); + $this->assertEquals($Apple->Parent->Behaviors->Test->settings['Parent'], $Apple->Sample->Behaviors->Test->settings['Sample']); + + $Apple->Parent->Behaviors->attach('Test', array('key' => 'value', 'key2' => 'value', 'key3' => 'value', 'beforeFind' => 'off')); + $this->assertNotEquals($Apple->Parent->Behaviors->Test->settings['Parent'], $Apple->Sample->Behaviors->Test->settings['Sample']); + + $Apple->Behaviors->attach('Plugin.Test', array('key' => 'new value')); + $expected = array( + 'beforeFind' => 'off', 'afterFind' => 'off', 'key' => 'new value', + 'key2' => 'value2', 'key3' => 'value3' + ); + $this->assertEquals($expected, $Apple->Behaviors->Test->settings['Apple']); + + $current = $Apple->Behaviors->Test->settings['Apple']; + $expected = array_merge($current, array('mangle' => 'trigger mangled')); + $Apple->Behaviors->attach('Test', array('mangle' => 'trigger')); + $this->assertEquals($expected, $Apple->Behaviors->Test->settings['Apple']); + + $Apple->Behaviors->attach('Test'); + $expected = array_merge($current, array('mangle' => 'trigger mangled mangled')); + + $this->assertEquals($expected, $Apple->Behaviors->Test->settings['Apple']); + $Apple->Behaviors->attach('Test', array('mangle' => 'trigger')); + $expected = array_merge($current, array('mangle' => 'trigger mangled')); + $this->assertEquals($expected, $Apple->Behaviors->Test->settings['Apple']); + } + +/** + * test that attach()/detach() works with plugin.banana + * + * @return void + */ + public function testDetachWithPluginNames() { + $Apple = new Apple(); + $Apple->Behaviors->attach('Plugin.Test'); + $this->assertTrue(isset($Apple->Behaviors->Test), 'Missing behavior'); + $this->assertEquals(array('Test'), $Apple->Behaviors->attached()); + + $Apple->Behaviors->detach('Plugin.Test'); + $this->assertEquals(array(), $Apple->Behaviors->attached()); + + $Apple->Behaviors->attach('Plugin.Test'); + $this->assertTrue(isset($Apple->Behaviors->Test), 'Missing behavior'); + $this->assertEquals(array('Test'), $Apple->Behaviors->attached()); + + $Apple->Behaviors->detach('Test'); + $this->assertEquals(array(), $Apple->Behaviors->attached()); + } + +/** + * test that attaching a non existent Behavior triggers a cake error. + * + * @expectedException MissingBehaviorException + * @return void + */ + public function testInvalidBehaviorCausingCakeError() { + $Apple = new Apple(); + $Apple->Behaviors->attach('NoSuchBehavior'); + } + +/** + * testBehaviorToggling method + * + * @return void + */ + public function testBehaviorToggling() { + $Apple = new Apple(); + $expected = $Apple->find('all'); + $this->assertSame($Apple->Behaviors->enabled(), array()); + + $Apple->Behaviors->init('Apple', array('Test' => array('key' => 'value'))); + $this->assertSame($Apple->Behaviors->enabled(), array('Test')); + + $Apple->Behaviors->disable('Test'); + $this->assertSame(array('Test'), $Apple->Behaviors->attached()); + $this->assertSame($Apple->Behaviors->enabled(), array()); + + $Apple->Sample->Behaviors->attach('Test'); + $this->assertSame($Apple->Sample->Behaviors->enabled('Test'), true); + $this->assertSame($Apple->Behaviors->enabled(), array()); + + $Apple->Behaviors->enable('Test'); + $this->assertSame($Apple->Behaviors->attached('Test'), true); + $this->assertSame($Apple->Behaviors->enabled(), array('Test')); + + $Apple->Behaviors->disable('Test'); + $this->assertSame($Apple->Behaviors->enabled(), array()); + $Apple->Behaviors->attach('Test', array('enabled' => true)); + $this->assertSame($Apple->Behaviors->enabled(), array('Test')); + $Apple->Behaviors->attach('Test', array('enabled' => false)); + $this->assertSame($Apple->Behaviors->enabled(), array()); + $Apple->Behaviors->detach('Test'); + $this->assertSame($Apple->Behaviors->enabled(), array()); + } + +/** + * testBehaviorFindCallbacks method + * + * @return void + */ + public function testBehaviorFindCallbacks() { + $this->skipIf($this->db instanceof Sqlserver, 'This test is not compatible with SQL Server.'); + + $Apple = new Apple(); + $expected = $Apple->find('all'); + + $Apple->Behaviors->attach('Test'); + $this->assertSame($Apple->find('all'), null); + + $Apple->Behaviors->attach('Test', array('beforeFind' => 'off')); + $this->assertSame($expected, $Apple->find('all')); + + $Apple->Behaviors->attach('Test', array('beforeFind' => 'test')); + $this->assertSame($expected, $Apple->find('all')); + + $Apple->Behaviors->attach('Test', array('beforeFind' => 'modify')); + $expected2 = array( + array('Apple' => array('id' => '1', 'name' => 'Red Apple 1', 'mytime' => '22:57:17')), + array('Apple' => array('id' => '2', 'name' => 'Bright Red Apple', 'mytime' => '22:57:17')), + array('Apple' => array('id' => '3', 'name' => 'green blue', 'mytime' => '22:57:17')) + ); + $result = $Apple->find('all', array('conditions' => array('Apple.id <' => '4'))); + $this->assertEquals($expected2, $result); + + $Apple->Behaviors->disable('Test'); + $result = $Apple->find('all'); + $this->assertEquals($expected, $result); + + $Apple->Behaviors->attach('Test', array('beforeFind' => 'off', 'afterFind' => 'on')); + $this->assertSame($Apple->find('all'), array()); + + $Apple->Behaviors->attach('Test', array('afterFind' => 'off')); + $this->assertEquals($expected, $Apple->find('all')); + + $Apple->Behaviors->attach('Test', array('afterFind' => 'test')); + $this->assertEquals($expected, $Apple->find('all')); + + $Apple->Behaviors->attach('Test', array('afterFind' => 'test2')); + $this->assertEquals($expected, $Apple->find('all')); + + $Apple->Behaviors->attach('Test', array('afterFind' => 'modify')); + $expected = array( + array('id' => '1', 'apple_id' => '2', 'color' => 'Red 1', 'name' => 'Red Apple 1', 'created' => '2006-11-22 10:38:58', 'date' => '1951-01-04', 'modified' => '2006-12-01 13:31:26', 'mytime' => '22:57:17'), + array('id' => '2', 'apple_id' => '1', 'color' => 'Bright Red 1', 'name' => 'Bright Red Apple', 'created' => '2006-11-22 10:43:13', 'date' => '2014-01-01', 'modified' => '2006-11-30 18:38:10', 'mytime' => '22:57:17'), + array('id' => '3', 'apple_id' => '2', 'color' => 'blue green', 'name' => 'green blue', 'created' => '2006-12-25 05:13:36', 'date' => '2006-12-25', 'modified' => '2006-12-25 05:23:24', 'mytime' => '22:57:17'), + array('id' => '4', 'apple_id' => '2', 'color' => 'Blue Green', 'name' => 'Test Name', 'created' => '2006-12-25 05:23:36', 'date' => '2006-12-25', 'modified' => '2006-12-25 05:23:36', 'mytime' => '22:57:17'), + array('id' => '5', 'apple_id' => '5', 'color' => 'Green', 'name' => 'Blue Green', 'created' => '2006-12-25 05:24:06', 'date' => '2006-12-25', 'modified' => '2006-12-25 05:29:16', 'mytime' => '22:57:17'), + array('id' => '6', 'apple_id' => '4', 'color' => 'My new appleOrange', 'name' => 'My new apple', 'created' => '2006-12-25 05:29:39', 'date' => '2006-12-25', 'modified' => '2006-12-25 05:29:39', 'mytime' => '22:57:17'), + array('id' => '7', 'apple_id' => '6', 'color' => 'Some wierd color', 'name' => 'Some odd color', 'created' => '2006-12-25 05:34:21', 'date' => '2006-12-25', 'modified' => '2006-12-25 05:34:21', 'mytime' => '22:57:17') + ); + $this->assertEquals($expected, $Apple->find('all')); + } + +/** + * testBehaviorHasManyFindCallbacks method + * + * @return void + */ + public function testBehaviorHasManyFindCallbacks() { + $Apple = new Apple(); + $Apple->unbindModel(array('hasOne' => array('Sample'), 'belongsTo' => array('Parent')), false); + $expected = $Apple->find('all'); + + $Apple->unbindModel(array('hasMany' => array('Child'))); + $wellBehaved = $Apple->find('all'); + $Apple->Child->Behaviors->attach('Test', array('afterFind' => 'modify')); + $Apple->unbindModel(array('hasMany' => array('Child'))); + $this->assertSame($Apple->find('all'), $wellBehaved); + + $Apple->Child->Behaviors->attach('Test', array('before' => 'off')); + $this->assertSame($expected, $Apple->find('all')); + + $Apple->Child->Behaviors->attach('Test', array('before' => 'test')); + $this->assertSame($expected, $Apple->find('all')); + + $expected2 = array( + array( + 'Apple' => array('id' => 1), + 'Child' => array( + array('id' => 2, 'name' => 'Bright Red Apple', 'mytime' => '22:57:17'))), + array( + 'Apple' => array('id' => 2), + 'Child' => array( + array('id' => 1, 'name' => 'Red Apple 1', 'mytime' => '22:57:17'), + array('id' => 3, 'name' => 'green blue', 'mytime' => '22:57:17'), + array('id' => 4, 'name' => 'Test Name', 'mytime' => '22:57:17'))), + array( + 'Apple' => array('id' => 3), + 'Child' => array()) + ); + + $Apple->Child->Behaviors->attach('Test', array('before' => 'modify')); + $result = $Apple->find('all', array('fields' => array('Apple.id'), 'conditions' => array('Apple.id <' => '4'))); + + $Apple->Child->Behaviors->disable('Test'); + $result = $Apple->find('all'); + $this->assertEquals($expected, $result); + + $Apple->Child->Behaviors->attach('Test', array('before' => 'off', 'after' => 'on')); + + $Apple->Child->Behaviors->attach('Test', array('after' => 'off')); + $this->assertEquals($expected, $Apple->find('all')); + + $Apple->Child->Behaviors->attach('Test', array('after' => 'test')); + $this->assertEquals($expected, $Apple->find('all')); + + $Apple->Child->Behaviors->attach('Test', array('after' => 'test2')); + $this->assertEquals($expected, $Apple->find('all')); + } + +/** + * testBehaviorHasOneFindCallbacks method + * + * @return void + */ + public function testBehaviorHasOneFindCallbacks() { + $Apple = new Apple(); + $Apple->unbindModel(array('hasMany' => array('Child'), 'belongsTo' => array('Parent')), false); + $expected = $Apple->find('all'); + + $Apple->unbindModel(array('hasOne' => array('Sample'))); + $wellBehaved = $Apple->find('all'); + $Apple->Sample->Behaviors->attach('Test'); + $Apple->unbindModel(array('hasOne' => array('Sample'))); + $this->assertSame($Apple->find('all'), $wellBehaved); + + $Apple->Sample->Behaviors->attach('Test', array('before' => 'off')); + $this->assertSame($expected, $Apple->find('all')); + + $Apple->Sample->Behaviors->attach('Test', array('before' => 'test')); + $this->assertSame($expected, $Apple->find('all')); + + $Apple->Sample->Behaviors->disable('Test'); + $result = $Apple->find('all'); + $this->assertEquals($expected, $result); + + $Apple->Sample->Behaviors->attach('Test', array('after' => 'off')); + $this->assertEquals($expected, $Apple->find('all')); + + $Apple->Sample->Behaviors->attach('Test', array('after' => 'test')); + $this->assertEquals($expected, $Apple->find('all')); + + $Apple->Sample->Behaviors->attach('Test', array('after' => 'test2')); + $this->assertEquals($expected, $Apple->find('all')); + } + +/** + * testBehaviorBelongsToFindCallbacks method + * + * @return void + */ + public function testBehaviorBelongsToFindCallbacks() { + $this->skipIf($this->db instanceof Sqlserver, 'This test is not compatible with SQL Server.'); + + $Apple = new Apple(); + $Apple->unbindModel(array('hasMany' => array('Child'), 'hasOne' => array('Sample')), false); + $expected = $Apple->find('all'); + + $Apple->unbindModel(array('belongsTo' => array('Parent'))); + $wellBehaved = $Apple->find('all'); + $Apple->Parent->Behaviors->attach('Test'); + $Apple->unbindModel(array('belongsTo' => array('Parent'))); + $this->assertSame($Apple->find('all'), $wellBehaved); + + $Apple->Parent->Behaviors->attach('Test', array('before' => 'off')); + $this->assertSame($expected, $Apple->find('all')); + + $Apple->Parent->Behaviors->attach('Test', array('before' => 'test')); + $this->assertSame($expected, $Apple->find('all')); + + $Apple->Parent->Behaviors->attach('Test', array('before' => 'modify')); + $expected2 = array( + array( + 'Apple' => array('id' => 1), + 'Parent' => array('id' => 2, 'name' => 'Bright Red Apple', 'mytime' => '22:57:17')), + array( + 'Apple' => array('id' => 2), + 'Parent' => array('id' => 1, 'name' => 'Red Apple 1', 'mytime' => '22:57:17')), + array( + 'Apple' => array('id' => 3), + 'Parent' => array('id' => 2, 'name' => 'Bright Red Apple', 'mytime' => '22:57:17')) + ); + $result2 = $Apple->find('all', array( + 'fields' => array('Apple.id', 'Parent.id', 'Parent.name', 'Parent.mytime'), + 'conditions' => array('Apple.id <' => '4') + )); + $this->assertEquals($expected2, $result2); + + $Apple->Parent->Behaviors->disable('Test'); + $result = $Apple->find('all'); + $this->assertEquals($expected, $result); + + $Apple->Parent->Behaviors->attach('Test', array('after' => 'off')); + $this->assertEquals($expected, $Apple->find('all')); + + $Apple->Parent->Behaviors->attach('Test', array('after' => 'test')); + $this->assertEquals($expected, $Apple->find('all')); + + $Apple->Parent->Behaviors->attach('Test', array('after' => 'test2')); + $this->assertEquals($expected, $Apple->find('all')); + } + +/** + * testBehaviorSaveCallbacks method + * + * @return void + */ + public function testBehaviorSaveCallbacks() { + $Sample = new Sample(); + $record = array('Sample' => array('apple_id' => 6, 'name' => 'sample99')); + + $Sample->Behaviors->attach('Test', array('beforeSave' => 'on')); + $Sample->create(); + $this->assertSame(false, $Sample->save($record)); + + $Sample->Behaviors->attach('Test', array('beforeSave' => 'off')); + $Sample->create(); + $result = $Sample->save($record); + $expected = $record; + $expected['Sample']['id'] = $Sample->id; + $this->assertSame($expected, $result); + + $Sample->Behaviors->attach('Test', array('beforeSave' => 'test')); + $Sample->create(); + $result = $Sample->save($record); + $expected = $record; + $expected['Sample']['id'] = $Sample->id; + $this->assertSame($expected, $result); + + $Sample->Behaviors->attach('Test', array('beforeSave' => 'modify')); + $expected = Hash::insert($record, 'Sample.name', 'sample99 modified before'); + $Sample->create(); + $result = $Sample->save($record); + $expected['Sample']['id'] = $Sample->id; + $this->assertSame($expected, $result); + + $Sample->Behaviors->disable('Test'); + $this->assertSame($record, $Sample->save($record)); + + $Sample->Behaviors->attach('Test', array('beforeSave' => 'off', 'afterSave' => 'on')); + $expected = Hash::merge($record, array('Sample' => array('aftersave' => 'modified after on create'))); + $Sample->create(); + $result = $Sample->save($record); + $expected['Sample']['id'] = $Sample->id; + $this->assertEquals($expected, $result); + + $Sample->Behaviors->attach('Test', array('beforeSave' => 'modify', 'afterSave' => 'modify')); + $expected = Hash::merge($record, array('Sample' => array('name' => 'sample99 modified before modified after on create'))); + $Sample->create(); + $result = $Sample->save($record); + $expected['Sample']['id'] = $Sample->id; + $this->assertSame($expected, $result); + + $Sample->Behaviors->attach('Test', array('beforeSave' => 'off', 'afterSave' => 'test')); + $Sample->create(); + $expected = $record; + $result = $Sample->save($record); + $expected['Sample']['id'] = $Sample->id; + $this->assertSame($expected, $result); + + $Sample->Behaviors->attach('Test', array('afterSave' => 'test2')); + $Sample->create(); + $expected = $record; + $result = $Sample->save($record); + $expected['Sample']['id'] = $Sample->id; + $this->assertSame($expected, $result); + + $Sample->Behaviors->attach('Test', array('beforeFind' => 'off', 'afterFind' => 'off')); + $Sample->recursive = -1; + $record2 = $Sample->read(null, 1); + + $Sample->Behaviors->attach('Test', array('afterSave' => 'on')); + $expected = Hash::merge($record2, array('Sample' => array('aftersave' => 'modified after'))); + $Sample->create(); + $this->assertSame($expected, $Sample->save($record2)); + + $Sample->Behaviors->attach('Test', array('afterSave' => 'modify')); + $expected = Hash::merge($record2, array('Sample' => array('name' => 'sample1 modified after'))); + $Sample->create(); + $this->assertSame($expected, $Sample->save($record2)); + } + +/** + * testBehaviorDeleteCallbacks method + * + * @return void + */ + public function testBehaviorDeleteCallbacks() { + $Apple = new Apple(); + + $Apple->Behaviors->attach('Test', array('beforeFind' => 'off', 'beforeDelete' => 'off')); + $this->assertSame($Apple->delete(6), true); + + $Apple->Behaviors->attach('Test', array('beforeDelete' => 'on')); + $this->assertSame($Apple->delete(4), false); + + $Apple->Behaviors->attach('Test', array('beforeDelete' => 'test2')); + + ob_start(); + $results = $Apple->delete(4); + $this->assertSame(trim(ob_get_clean()), 'beforeDelete success (cascading)'); + $this->assertSame($results, true); + + ob_start(); + $results = $Apple->delete(3, false); + $this->assertSame(trim(ob_get_clean()), 'beforeDelete success'); + $this->assertSame($results, true); + + $Apple->Behaviors->attach('Test', array('beforeDelete' => 'off', 'afterDelete' => 'on')); + ob_start(); + $results = $Apple->delete(2, false); + $this->assertSame(trim(ob_get_clean()), 'afterDelete success'); + $this->assertSame($results, true); + } + +/** + * testBehaviorOnErrorCallback method + * + * @return void + */ + public function testBehaviorOnErrorCallback() { + $Apple = new Apple(); + + $Apple->Behaviors->attach('Test', array('beforeFind' => 'off', 'onError' => 'on')); + ob_start(); + $Apple->Behaviors->Test->onError($Apple, ''); + $this->assertSame(trim(ob_get_clean()), 'onError trigger success'); + } + +/** + * testBehaviorValidateCallback method + * + * @return void + */ + public function testBehaviorValidateCallback() { + $Apple = new Apple(); + + $Apple->Behaviors->attach('Test'); + $this->assertSame($Apple->validates(), true); + + $Apple->Behaviors->attach('Test', array('validate' => 'on')); + $this->assertSame($Apple->validates(), false); + $this->assertSame($Apple->validationErrors, array('name' => array(true))); + + $Apple->Behaviors->attach('Test', array('validate' => 'stop')); + $this->assertSame($Apple->validates(), false); + $this->assertSame($Apple->validationErrors, array('name' => array(true, true))); + + $Apple->Behaviors->attach('Test', array('validate' => 'whitelist')); + $Apple->validates(); + $this->assertSame($Apple->whitelist, array()); + + $Apple->whitelist = array('unknown'); + $Apple->validates(); + $this->assertSame($Apple->whitelist, array('unknown', 'name')); + } + +/** + * testBehaviorValidateAfterCallback method + * + * @return void + */ + public function testBehaviorValidateAfterCallback() { + $Apple = new Apple(); + + $Apple->Behaviors->attach('Test'); + $this->assertSame($Apple->validates(), true); + + $Apple->Behaviors->attach('Test', array('afterValidate' => 'on')); + $this->assertSame($Apple->validates(), true); + $this->assertSame($Apple->validationErrors, array()); + + $Apple->Behaviors->attach('Test', array('afterValidate' => 'test')); + $Apple->data = array('bar'); + $Apple->validates(); + $this->assertEquals(array('foo'), $Apple->data); + } + +/** + * testBehaviorValidateMethods method + * + * @return void + */ + public function testBehaviorValidateMethods() { + $Apple = new Apple(); + $Apple->Behaviors->attach('Test'); + $Apple->validate['color'] = 'validateField'; + + $result = $Apple->save(array('name' => 'Genetically Modified Apple', 'color' => 'Orange')); + $this->assertEquals(array('name', 'color', 'modified', 'created', 'id'), array_keys($result['Apple'])); + + $Apple->create(); + $result = $Apple->save(array('name' => 'Regular Apple', 'color' => 'Red')); + $this->assertFalse($result); + } + +/** + * testBehaviorMethodDispatching method + * + * @return void + */ + public function testBehaviorMethodDispatching() { + $Apple = new Apple(); + $Apple->Behaviors->attach('Test'); + + $expected = 'working'; + $this->assertEquals($expected, $Apple->testMethod()); + $this->assertEquals($expected, $Apple->Behaviors->dispatchMethod($Apple, 'testMethod')); + + $result = $Apple->Behaviors->dispatchMethod($Apple, 'wtf'); + $this->assertEquals(array('unhandled'), $result); + + $result = $Apple->{'look for the remote'}('in the couch'); + $expected = "Item.name = 'the remote' AND Location.name = 'the couch'"; + $this->assertEquals($expected, $result); + + $result = $Apple->{'look for THE REMOTE'}('in the couch'); + $expected = "Item.name = 'THE REMOTE' AND Location.name = 'the couch'"; + $this->assertEquals($expected, $result, 'Mapped method was lowercased.'); + } + +/** + * testBehaviorMethodDispatchingWithData method + * + * @return void + */ + public function testBehaviorMethodDispatchingWithData() { + $Apple = new Apple(); + $Apple->Behaviors->attach('Test'); + + $Apple->set('field', 'value'); + $this->assertTrue($Apple->testData()); + $this->assertTrue($Apple->data['Apple']['field_2']); + + $this->assertTrue($Apple->testData('one', 'two', 'three', 'four', 'five', 'six')); + } + +/** + * undocumented function + * + * @return void + */ + public function testBindModelCallsInBehaviors() { + // hasMany + $Article = new Article(); + $Article->unbindModel(array('hasMany' => array('Comment'))); + $result = $Article->find('first'); + $this->assertFalse(array_key_exists('Comment', $result)); + + $Article->Behaviors->attach('Test4'); + $result = $Article->find('first'); + $this->assertTrue(array_key_exists('Comment', $result)); + + // belongsTo + $Article->unbindModel(array('belongsTo' => array('User'))); + $result = $Article->find('first'); + $this->assertFalse(array_key_exists('User', $result)); + + $Article->Behaviors->attach('Test5'); + $result = $Article->find('first'); + $this->assertTrue(array_key_exists('User', $result)); + + // hasAndBelongsToMany + $Article->unbindModel(array('hasAndBelongsToMany' => array('Tag'))); + $result = $Article->find('first'); + $this->assertFalse(array_key_exists('Tag', $result)); + + $Article->Behaviors->attach('Test6'); + $result = $Article->find('first'); + $this->assertTrue(array_key_exists('Comment', $result)); + + // hasOne + $Comment = new Comment(); + $Comment->unbindModel(array('hasOne' => array('Attachment'))); + $result = $Comment->find('first'); + $this->assertFalse(array_key_exists('Attachment', $result)); + + $Comment->Behaviors->attach('Test7'); + $result = $Comment->find('first'); + $this->assertTrue(array_key_exists('Attachment', $result)); + } + +/** + * Test attach and detaching + * + * @return void + */ + public function testBehaviorAttachAndDetach() { + $Sample = new Sample(); + $Sample->actsAs = array('Test3' => array('bar'), 'Test2' => array('foo', 'bar')); + $Sample->Behaviors->init($Sample->alias, $Sample->actsAs); + $Sample->Behaviors->attach('Test2'); + $Sample->Behaviors->detach('Test3'); + + $Sample->Behaviors->trigger('beforeTest', array(&$Sample)); + } + +/** + * test that hasMethod works with basic functions. + * + * @return void + */ + public function testHasMethodBasic() { + $Sample = new Sample(); + $Collection = new BehaviorCollection(); + $Collection->init('Sample', array('Test', 'Test2')); + + $this->assertTrue($Collection->hasMethod('testMethod')); + $this->assertTrue($Collection->hasMethod('resolveMethod')); + + $this->assertFalse($Collection->hasMethod('No method')); + } + +/** + * test that hasMethod works with mapped methods. + * + * @return void + */ + public function testHasMethodMappedMethods() { + $Sample = new Sample(); + $Collection = new BehaviorCollection(); + $Collection->init('Sample', array('Test', 'Test2')); + + $this->assertTrue($Collection->hasMethod('look for the remote in the couch')); + $this->assertTrue($Collection->hasMethod('mappingRobotOnTheRoof')); + } + +/** + * test hasMethod returning a 'callback' + * + * @return void + */ + public function testHasMethodAsCallback() { + $Sample = new Sample(); + $Collection = new BehaviorCollection(); + $Collection->init('Sample', array('Test', 'Test2')); + + $result = $Collection->hasMethod('testMethod', true); + $expected = array('Test', 'testMethod'); + $this->assertEquals($expected, $result); + + $result = $Collection->hasMethod('resolveMethod', true); + $expected = array('Test2', 'resolveMethod'); + $this->assertEquals($expected, $result); + + $result = $Collection->hasMethod('mappingRobotOnTheRoof', true); + $expected = array('Test2', 'mapped', 'mappingRobotOnTheRoof'); + $this->assertEquals($expected, $result); + } + +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/CakeSchemaTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/CakeSchemaTest.php new file mode 100644 index 0000000..47effcc --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/CakeSchemaTest.php @@ -0,0 +1,1091 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Model + * @since CakePHP(tm) v 1.2.0.5550 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ + +App::uses('CakeSchema', 'Model'); +App::uses('CakeTestFixture', 'TestSuite/Fixture'); + +/** + * Test for Schema database management + * + * @package Cake.Test.Case.Model + */ +class MyAppSchema extends CakeSchema { + +/** + * name property + * + * @var string 'MyApp' + */ + public $name = 'MyApp'; + +/** + * connection property + * + * @var string 'test' + */ + public $connection = 'test'; + +/** + * comments property + * + * @var array + */ + public $comments = array( + 'id' => array('type' => 'integer', 'null' => false, 'default' => 0, 'key' => 'primary'), + 'post_id' => array('type' => 'integer', 'null' => false, 'default' => 0), + 'user_id' => array('type' => 'integer', 'null' => false), + 'title' => array('type' => 'string', 'null' => false, 'length' => 100), + 'comment' => array('type' => 'text', 'null' => false, 'default' => null), + 'published' => array('type' => 'string', 'null' => true, 'default' => 'N', 'length' => 1), + 'created' => array('type' => 'datetime', 'null' => true, 'default' => null), + 'updated' => array('type' => 'datetime', 'null' => true, 'default' => null), + 'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => true)), + ); + +/** + * posts property + * + * @var array + */ + public $posts = array( + 'id' => array('type' => 'integer', 'null' => false, 'default' => 0, 'key' => 'primary'), + 'author_id' => array('type' => 'integer', 'null' => true, 'default' => ''), + 'title' => array('type' => 'string', 'null' => false, 'default' => 'Title'), + 'body' => array('type' => 'text', 'null' => true, 'default' => null), + 'summary' => array('type' => 'text', 'null' => true), + 'published' => array('type' => 'string', 'null' => true, 'default' => 'Y', 'length' => 1), + 'created' => array('type' => 'datetime', 'null' => true, 'default' => null), + 'updated' => array('type' => 'datetime', 'null' => true, 'default' => null), + 'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => true)), + ); + +/** + * _foo property + * + * @var array + */ + protected $_foo = array('bar'); + +/** + * setup method + * + * @param mixed $version + * @return void + */ + public function setup($version) { + } + +/** + * teardown method + * + * @param mixed $version + * @return void + */ + public function teardown($version) { + } + +/** + * getVar method + * + * @param string $var Name of var + * @return mixed + */ + public function getVar($var) { + if (!isset($this->$var)) { + return null; + } + return $this->$var; + } + +} + +/** + * TestAppSchema class + * + * @package Cake.Test.Case.Model + */ +class TestAppSchema extends CakeSchema { + +/** + * name property + * + * @var string 'MyApp' + */ + public $name = 'MyApp'; + +/** + * comments property + * + * @var array + */ + public $comments = array( + 'id' => array('type' => 'integer', 'null' => false, 'default' => 0,'key' => 'primary'), + 'article_id' => array('type' => 'integer', 'null' => false), + 'user_id' => array('type' => 'integer', 'null' => false), + 'comment' => array('type' => 'text', 'null' => true, 'default' => null), + 'published' => array('type' => 'string', 'null' => true, 'default' => 'N', 'length' => 1), + 'created' => array('type' => 'datetime', 'null' => true, 'default' => null), + 'updated' => array('type' => 'datetime', 'null' => true, 'default' => null), + 'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => true)), + 'tableParameters' => array(), + ); + +/** + * posts property + * + * @var array + */ + public $posts = array( + 'id' => array('type' => 'integer', 'null' => false, 'default' => 0, 'key' => 'primary'), + 'author_id' => array('type' => 'integer', 'null' => false), + 'title' => array('type' => 'string', 'null' => false), + 'body' => array('type' => 'text', 'null' => true, 'default' => null), + 'published' => array('type' => 'string', 'null' => true, 'default' => 'N', 'length' => 1), + 'created' => array('type' => 'datetime', 'null' => true, 'default' => null), + 'updated' => array('type' => 'datetime', 'null' => true, 'default' => null), + 'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => true)), + 'tableParameters' => array(), + ); + +/** + * posts_tags property + * + * @var array + */ + public $posts_tags = array( + 'post_id' => array('type' => 'integer', 'null' => false, 'key' => 'primary'), + 'tag_id' => array('type' => 'string', 'null' => false, 'key' => 'primary'), + 'indexes' => array('posts_tag' => array('column' => array('tag_id', 'post_id'), 'unique' => 1)), + 'tableParameters' => array() + ); + +/** + * tags property + * + * @var array + */ + public $tags = array( + 'id' => array('type' => 'integer', 'null' => false, 'default' => 0, 'key' => 'primary'), + 'tag' => array('type' => 'string', 'null' => false), + 'created' => array('type' => 'datetime', 'null' => true, 'default' => null), + 'updated' => array('type' => 'datetime', 'null' => true, 'default' => null), + 'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => true)), + 'tableParameters' => array() + ); + +/** + * datatypes property + * + * @var array + */ + public $datatypes = array( + 'id' => array('type' => 'integer', 'null' => false, 'default' => 0, 'key' => 'primary'), + 'float_field' => array('type' => 'float', 'null' => false, 'length' => '5,2', 'default' => ''), + 'bool' => array('type' => 'boolean', 'null' => false, 'default' => false), + 'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => true)), + 'tableParameters' => array() + ); + +/** + * setup method + * + * @param mixed $version + * @return void + */ + public function setup($version) { + } + +/** + * teardown method + * + * @param mixed $version + * @return void + */ + public function teardown($version) { + } + +} + +/** + * SchemaPost class + * + * @package Cake.Test.Case.Model + */ +class SchemaPost extends CakeTestModel { + +/** + * name property + * + * @var string 'SchemaPost' + */ + public $name = 'SchemaPost'; + +/** + * useTable property + * + * @var string 'posts' + */ + public $useTable = 'posts'; + +/** + * hasMany property + * + * @var array + */ + public $hasMany = array('SchemaComment'); + +/** + * hasAndBelongsToMany property + * + * @var array + */ + public $hasAndBelongsToMany = array('SchemaTag'); +} + +/** + * SchemaComment class + * + * @package Cake.Test.Case.Model + */ +class SchemaComment extends CakeTestModel { + +/** + * name property + * + * @var string 'SchemaComment' + */ + public $name = 'SchemaComment'; + +/** + * useTable property + * + * @var string 'comments' + */ + public $useTable = 'comments'; + +/** + * belongsTo property + * + * @var array + */ + public $belongsTo = array('SchemaPost'); +} + +/** + * SchemaTag class + * + * @package Cake.Test.Case.Model + */ +class SchemaTag extends CakeTestModel { + +/** + * name property + * + * @var string 'SchemaTag' + */ + public $name = 'SchemaTag'; + +/** + * useTable property + * + * @var string 'tags' + */ + public $useTable = 'tags'; + +/** + * hasAndBelongsToMany property + * + * @var array + */ + public $hasAndBelongsToMany = array('SchemaPost'); +} + +/** + * SchemaDatatype class + * + * @package Cake.Test.Case.Model + */ +class SchemaDatatype extends CakeTestModel { + +/** + * name property + * + * @var string 'SchemaDatatype' + */ + public $name = 'SchemaDatatype'; + +/** + * useTable property + * + * @var string 'datatypes' + */ + public $useTable = 'datatypes'; +} + +/** + * Testdescribe class + * + * This class is defined purely to inherit the cacheSources variable otherwise + * testSchemaCreateTable will fail if listSources has already been called and + * its source cache populated - I.e. if the test is run within a group + * + * @uses CakeTestModel + * @package + * @package Cake.Test.Case.Model + */ +class Testdescribe extends CakeTestModel { + +/** + * name property + * + * @var string 'Testdescribe' + */ + public $name = 'Testdescribe'; +} + +/** + * SchemaCrossDatabase class + * + * @package Cake.Test.Case.Model + */ +class SchemaCrossDatabase extends CakeTestModel { + +/** + * name property + * + * @var string 'SchemaCrossDatabase' + */ + public $name = 'SchemaCrossDatabase'; + +/** + * useTable property + * + * @var string 'posts' + */ + public $useTable = 'cross_database'; + +/** + * useDbConfig property + * + * @var string 'test2' + */ + public $useDbConfig = 'test2'; +} + +/** + * SchemaCrossDatabaseFixture class + * + * @package Cake.Test.Case.Model + */ +class SchemaCrossDatabaseFixture extends CakeTestFixture { + +/** + * name property + * + * @var string 'CrossDatabase' + */ + public $name = 'CrossDatabase'; + +/** + * table property + * + */ + public $table = 'cross_database'; + +/** + * fields property + * + * @var array + */ + public $fields = array( + 'id' => array('type' => 'integer', 'key' => 'primary'), + 'name' => 'string' + ); + +/** + * records property + * + * @var array + */ + public $records = array( + array('id' => 1, 'name' => 'First'), + array('id' => 2, 'name' => 'Second'), + ); +} + +/** + * SchemaPrefixAuthUser class + * + * @package Cake.Test.Case.Model + */ +class SchemaPrefixAuthUser extends CakeTestModel { + +/** + * name property + * + * @var string + */ + public $name = 'SchemaPrefixAuthUser'; + +/** + * table prefix + * + * @var string + */ + public $tablePrefix = 'auth_'; + +/** + * useTable + * + * @var string + */ + public $useTable = 'users'; +} + +/** + * CakeSchemaTest + * + * @package Cake.Test.Case.Model + */ +class CakeSchemaTest extends CakeTestCase { + +/** + * fixtures property + * + * @var array + */ + public $fixtures = array( + 'core.post', 'core.tag', 'core.posts_tag', 'core.test_plugin_comment', + 'core.datatype', 'core.auth_user', 'core.author', + 'core.test_plugin_article', 'core.user', 'core.comment', + 'core.prefix_test' + ); + +/** + * setUp method + * + * @return void + */ + public function setUp() { + parent::setUp(); + ConnectionManager::getDataSource('test')->cacheSources = false; + $this->Schema = new TestAppSchema(); + } + +/** + * tearDown method + * + * @return void + */ + public function tearDown() { + parent::tearDown(); + if (file_exists(TMP . 'tests' . DS . 'schema.php')) { + unlink(TMP . 'tests' . DS . 'schema.php'); + } + unset($this->Schema); + CakePlugin::unload(); + } + +/** + * testSchemaName method + * + * @return void + */ + public function testSchemaName() { + $Schema = new CakeSchema(); + $this->assertEquals(Inflector::camelize(Inflector::slug(APP_DIR)), $Schema->name); + + Configure::write('App.dir', 'Some.name.with.dots'); + $Schema = new CakeSchema(); + $this->assertEquals('SomeNameWithDots', $Schema->name); + + Configure::write('App.dir', 'Some-name-with-dashes'); + $Schema = new CakeSchema(); + $this->assertEquals('SomeNameWithDashes', $Schema->name); + + Configure::write('App.dir', 'Some name with spaces'); + $Schema = new CakeSchema(); + $this->assertEquals('SomeNameWithSpaces', $Schema->name); + + Configure::write('App.dir', 'Some,name;with&weird=characters'); + $Schema = new CakeSchema(); + $this->assertEquals('SomeNameWithWeirdCharacters', $Schema->name); + + Configure::write('App.dir', 'app'); + } + +/** + * testSchemaRead method + * + * @return void + */ + public function testSchemaRead() { + $read = $this->Schema->read(array( + 'connection' => 'test', + 'name' => 'TestApp', + 'models' => array('SchemaPost', 'SchemaComment', 'SchemaTag', 'SchemaDatatype') + )); + unset($read['tables']['missing']); + + $expected = array('comments', 'datatypes', 'posts', 'posts_tags', 'tags'); + foreach ($expected as $table) { + $this->assertTrue(isset($read['tables'][$table]), 'Missing table ' . $table); + } + foreach ($this->Schema->tables as $table => $fields) { + $this->assertEquals(array_keys($fields), array_keys($read['tables'][$table])); + } + + if (isset($read['tables']['datatypes']['float_field']['length'])) { + $this->assertEquals( + $read['tables']['datatypes']['float_field']['length'], + $this->Schema->tables['datatypes']['float_field']['length'] + ); + } + + $this->assertEquals( + $read['tables']['datatypes']['float_field']['type'], + $this->Schema->tables['datatypes']['float_field']['type'] + ); + + $this->assertEquals( + $read['tables']['datatypes']['float_field']['null'], + $this->Schema->tables['datatypes']['float_field']['null'] + ); + + $db = ConnectionManager::getDataSource('test'); + $config = $db->config; + $config['prefix'] = 'schema_test_prefix_'; + ConnectionManager::create('schema_prefix', $config); + $read = $this->Schema->read(array('connection' => 'schema_prefix', 'models' => false)); + $this->assertTrue(empty($read['tables'])); + + $read = $this->Schema->read(array( + 'connection' => 'test', + 'name' => 'TestApp', + 'models' => array('SchemaComment', 'SchemaTag', 'SchemaPost') + )); + $this->assertFalse(isset($read['tables']['missing']['posts_tags']), 'Join table marked as missing'); + } + +/** + * testSchemaReadWithAppModel method + * + * @access public + * @return void + */ + public function testSchemaReadWithAppModel() { + $connections = ConnectionManager::enumConnectionObjects(); + ConnectionManager::drop('default'); + ConnectionManager::create('default', $connections['test']); + try { + $read = $this->Schema->read(array( + 'connection' => 'default', + 'name' => 'TestApp', + 'models' => array('AppModel') + )); + } catch(MissingTableException $mte) { + ConnectionManager::drop('default'); + $this->fail($mte->getMessage()); + } + ConnectionManager::drop('default'); + } + +/** + * testSchemaReadWithOddTablePrefix method + * + * @return void + */ + public function testSchemaReadWithOddTablePrefix() { + $config = ConnectionManager::getDataSource('test')->config; + $this->skipIf(!empty($config['prefix']), 'This test can not be executed with datasource prefix set.'); + + $SchemaPost = ClassRegistry::init('SchemaPost'); + $SchemaPost->tablePrefix = 'po'; + $SchemaPost->useTable = 'sts'; + $read = $this->Schema->read(array( + 'connection' => 'test', + 'name' => 'TestApp', + 'models' => array('SchemaPost') + )); + + $this->assertFalse(isset($read['tables']['missing']['posts']), 'Posts table was not read from tablePrefix'); + } + +/** + * test read() with tablePrefix properties. + * + * @return void + */ + public function testSchemaReadWithTablePrefix() { + $config = ConnectionManager::getDataSource('test')->config; + $this->skipIf(!empty($config['prefix']), 'This test can not be executed with datasource prefix set.'); + + $model = new SchemaPrefixAuthUser(); + + $Schema = new CakeSchema(); + $read = $Schema->read(array( + 'connection' => 'test', + 'name' => 'TestApp', + 'models' => array('SchemaPrefixAuthUser') + )); + unset($read['tables']['missing']); + $this->assertTrue(isset($read['tables']['auth_users']), 'auth_users key missing %s'); + } + +/** + * test reading schema with config prefix. + * + * @return void + */ + public function testSchemaReadWithConfigPrefix() { + $this->skipIf($this->db instanceof Sqlite, 'Cannot open 2 connections to Sqlite'); + + $db = ConnectionManager::getDataSource('test'); + $config = $db->config; + $this->skipIf(!empty($config['prefix']), 'This test can not be executed with datasource prefix set.'); + + $config['prefix'] = 'schema_test_prefix_'; + ConnectionManager::create('schema_prefix', $config); + $read = $this->Schema->read(array('connection' => 'schema_prefix', 'models' => false)); + $this->assertTrue(empty($read['tables'])); + + $config['prefix'] = 'prefix_'; + ConnectionManager::create('schema_prefix2', $config); + $read = $this->Schema->read(array( + 'connection' => 'schema_prefix2', + 'name' => 'TestApp', + 'models' => false)); + $this->assertTrue(isset($read['tables']['prefix_tests'])); + } + +/** + * test reading schema from plugins. + * + * @return void + */ + public function testSchemaReadWithPlugins() { + App::objects('model', null, false); + App::build(array( + 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS) + )); + CakePlugin::load('TestPlugin'); + + $Schema = new CakeSchema(); + $Schema->plugin = 'TestPlugin'; + $read = $Schema->read(array( + 'connection' => 'test', + 'name' => 'TestApp', + 'models' => true + )); + unset($read['tables']['missing']); + $this->assertTrue(isset($read['tables']['auth_users'])); + $this->assertTrue(isset($read['tables']['authors'])); + $this->assertTrue(isset($read['tables']['test_plugin_comments'])); + $this->assertTrue(isset($read['tables']['posts'])); + $this->assertTrue(count($read['tables']) >= 4); + + App::build(); + } + +/** + * test reading schema with tables from another database. + * + * @return void + */ + public function testSchemaReadWithCrossDatabase() { + $config = ConnectionManager::enumConnectionObjects(); + $this->skipIf( + !isset($config['test']) || !isset($config['test2']), + 'Primary and secondary test databases not configured, ' . + 'skipping cross-database join tests. ' . + 'To run these tests, you must define $test and $test2 in your database configuration.' + ); + + $db = ConnectionManager::getDataSource('test2'); + $fixture = new SchemaCrossDatabaseFixture(); + $fixture->create($db); + $fixture->insert($db); + + $read = $this->Schema->read(array( + 'connection' => 'test', + 'name' => 'TestApp', + 'models' => array('SchemaCrossDatabase', 'SchemaPost') + )); + $this->assertTrue(isset($read['tables']['posts'])); + $this->assertFalse(isset($read['tables']['cross_database']), 'Cross database should not appear'); + $this->assertFalse(isset($read['tables']['missing']['cross_database']), 'Cross database should not appear'); + + $read = $this->Schema->read(array( + 'connection' => 'test2', + 'name' => 'TestApp', + 'models' => array('SchemaCrossDatabase', 'SchemaPost') + )); + $this->assertFalse(isset($read['tables']['posts']), 'Posts should not appear'); + $this->assertFalse(isset($read['tables']['posts']), 'Posts should not appear'); + $this->assertTrue(isset($read['tables']['cross_database'])); + + $fixture->drop($db); + } + +/** + * test that tables are generated correctly + * + * @return void + */ + public function testGenerateTable() { + $posts = array( + 'id' => array('type' => 'integer', 'null' => false, 'default' => 0, 'key' => 'primary'), + 'author_id' => array('type' => 'integer', 'null' => false), + 'title' => array('type' => 'string', 'null' => false), + 'body' => array('type' => 'text', 'null' => true, 'default' => null), + 'published' => array('type' => 'string', 'null' => true, 'default' => 'N', 'length' => 1), + 'created' => array('type' => 'datetime', 'null' => true, 'default' => null), + 'updated' => array('type' => 'datetime', 'null' => true, 'default' => null), + 'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => true)), + ); + $result = $this->Schema->generateTable('posts', $posts); + $this->assertRegExp('/public \$posts/', $result); + } + +/** + * testSchemaWrite method + * + * @return void + */ + public function testSchemaWrite() { + $write = $this->Schema->write(array( + 'name' => 'MyOtherApp', + 'tables' => $this->Schema->tables, + 'path' => TMP . 'tests' + )); + $file = file_get_contents(TMP . 'tests' . DS . 'schema.php'); + $this->assertEquals($write, $file); + + require_once TMP . 'tests' . DS . 'schema.php'; + $OtherSchema = new MyOtherAppSchema(); + $this->assertEquals($this->Schema->tables, $OtherSchema->tables); + } + +/** + * testSchemaComparison method + * + * @return void + */ + public function testSchemaComparison() { + $New = new MyAppSchema(); + $compare = $New->compare($this->Schema); + $expected = array( + 'comments' => array( + 'add' => array( + 'post_id' => array('type' => 'integer', 'null' => false, 'default' => 0, 'after' => 'id'), + 'title' => array('type' => 'string', 'null' => false, 'length' => 100, 'after' => 'user_id'), + ), + 'drop' => array( + 'article_id' => array('type' => 'integer', 'null' => false), + 'tableParameters' => array(), + ), + 'change' => array( + 'comment' => array('type' => 'text', 'null' => false, 'default' => null), + ) + ), + 'posts' => array( + 'add' => array( + 'summary' => array('type' => 'text', 'null' => true, 'after' => 'body'), + ), + 'drop' => array( + 'tableParameters' => array(), + ), + 'change' => array( + 'author_id' => array('type' => 'integer', 'null' => true, 'default' => ''), + 'title' => array('type' => 'string', 'null' => false, 'default' => 'Title'), + 'published' => array('type' => 'string', 'null' => true, 'default' => 'Y', 'length' => 1) + ) + ), + ); + $this->assertEquals($expected, $compare); + $this->assertNull($New->getVar('comments')); + $this->assertEquals(array('bar'), $New->getVar('_foo')); + + $tables = array( + 'missing' => array( + 'categories' => array( + 'id' => array('type' => 'integer', 'null' => false, 'default' => null, 'key' => 'primary'), + 'created' => array('type' => 'datetime', 'null' => false, 'default' => null), + 'modified' => array('type' => 'datetime', 'null' => false, 'default' => null), + 'name' => array('type' => 'string', 'null' => false, 'default' => null, 'length' => 100), + 'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => 1)), + 'tableParameters' => array('charset' => 'latin1', 'collate' => 'latin1_swedish_ci', 'engine' => 'MyISAM') + ) + ), + 'ratings' => array( + 'id' => array('type' => 'integer', 'null' => false, 'default' => null, 'key' => 'primary'), + 'foreign_key' => array('type' => 'integer', 'null' => false, 'default' => null), + 'model' => array('type' => 'varchar', 'null' => false, 'default' => null), + 'value' => array('type' => 'float', 'null' => false, 'length' => '5,2', 'default' => null), + 'created' => array('type' => 'datetime', 'null' => false, 'default' => null), + 'modified' => array('type' => 'datetime', 'null' => false, 'default' => null), + 'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => 1)), + 'tableParameters' => array('charset' => 'latin1', 'collate' => 'latin1_swedish_ci', 'engine' => 'MyISAM') + ) + ); + $compare = $New->compare($this->Schema, $tables); + $expected = array( + 'ratings' => array( + 'add' => array( + 'id' => array('type' => 'integer', 'null' => false, 'default' => null, 'key' => 'primary'), + 'foreign_key' => array('type' => 'integer', 'null' => false, 'default' => null, 'after' => 'id'), + 'model' => array('type' => 'varchar', 'null' => false, 'default' => null, 'after' => 'foreign_key'), + 'value' => array('type' => 'float', 'null' => false, 'length' => '5,2', 'default' => null, 'after' => 'model'), + 'created' => array('type' => 'datetime', 'null' => false, 'default' => null, 'after' => 'value'), + 'modified' => array('type' => 'datetime', 'null' => false, 'default' => null, 'after' => 'created'), + 'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => 1)), + 'tableParameters' => array('charset' => 'latin1', 'collate' => 'latin1_swedish_ci', 'engine' => 'MyISAM') + ) + ) + ); + $this->assertEquals($expected, $compare); + } + +/** + * test comparing '' and null and making sure they are different. + * + * @return void + */ + public function testCompareEmptyStringAndNull() { + $One = new CakeSchema(array( + 'posts' => array( + 'id' => array('type' => 'integer', 'null' => false, 'default' => null, 'key' => 'primary'), + 'name' => array('type' => 'string', 'null' => false, 'default' => '') + ) + )); + $Two = new CakeSchema(array( + 'posts' => array( + 'id' => array('type' => 'integer', 'null' => false, 'default' => null, 'key' => 'primary'), + 'name' => array('type' => 'string', 'null' => false, 'default' => null) + ) + )); + $compare = $One->compare($Two); + $expected = array( + 'posts' => array( + 'change' => array( + 'name' => array('type' => 'string', 'null' => false, 'default' => null) + ) + ) + ); + $this->assertEquals($expected, $compare); + } + +/** + * Test comparing tableParameters and indexes. + * + * @return void + */ + public function testTableParametersAndIndexComparison() { + $old = array( + 'posts' => array( + 'id' => array('type' => 'integer', 'null' => false, 'default' => 0, 'key' => 'primary'), + 'author_id' => array('type' => 'integer', 'null' => false), + 'title' => array('type' => 'string', 'null' => false), + 'indexes' => array( + 'PRIMARY' => array('column' => 'id', 'unique' => true) + ), + 'tableParameters' => array( + 'charset' => 'latin1', + 'collate' => 'latin1_general_ci' + ) + ), + 'comments' => array( + 'id' => array('type' => 'integer', 'null' => false, 'default' => 0, 'key' => 'primary'), + 'post_id' => array('type' => 'integer', 'null' => false, 'default' => 0), + 'comment' => array('type' => 'text'), + 'indexes' => array( + 'PRIMARY' => array('column' => 'id', 'unique' => true), + 'post_id' => array('column' => 'post_id'), + ), + 'tableParameters' => array( + 'engine' => 'InnoDB', + 'charset' => 'latin1', + 'collate' => 'latin1_general_ci' + ) + ) + ); + $new = array( + 'posts' => array( + 'id' => array('type' => 'integer', 'null' => false, 'default' => 0, 'key' => 'primary'), + 'author_id' => array('type' => 'integer', 'null' => false), + 'title' => array('type' => 'string', 'null' => false), + 'indexes' => array( + 'PRIMARY' => array('column' => 'id', 'unique' => true), + 'author_id' => array('column' => 'author_id'), + ), + 'tableParameters' => array( + 'charset' => 'utf8', + 'collate' => 'utf8_general_ci', + 'engine' => 'MyISAM' + ) + ), + 'comments' => array( + 'id' => array('type' => 'integer', 'null' => false, 'default' => 0, 'key' => 'primary'), + 'post_id' => array('type' => 'integer', 'null' => false, 'default' => 0), + 'comment' => array('type' => 'text'), + 'indexes' => array( + 'PRIMARY' => array('column' => 'id', 'unique' => true), + ), + 'tableParameters' => array( + 'charset' => 'utf8', + 'collate' => 'utf8_general_ci' + ) + ) + ); + $compare = $this->Schema->compare($old, $new); + $expected = array( + 'posts' => array( + 'add' => array( + 'indexes' => array('author_id' => array('column' => 'author_id')), + ), + 'change' => array( + 'tableParameters' => array( + 'charset' => 'utf8', + 'collate' => 'utf8_general_ci', + 'engine' => 'MyISAM' + ) + ) + ), + 'comments' => array( + 'drop' => array( + 'indexes' => array('post_id' => array('column' => 'post_id')), + ), + 'change' => array( + 'tableParameters' => array( + 'charset' => 'utf8', + 'collate' => 'utf8_general_ci', + ) + ) + ) + ); + $this->assertEquals($expected, $compare); + } + +/** + * Test comparing with field changed from VARCHAR to DATETIME + * + * @return void + */ + public function testCompareVarcharToDatetime() { + $old = array( + 'posts' => array( + 'id' => array('type' => 'integer', 'null' => false, 'default' => 0, 'key' => 'primary'), + 'author_id' => array('type' => 'integer', 'null' => false), + 'title' => array('type' => 'string', 'null' => true, 'length' => 45), + 'indexes' => array( + 'PRIMARY' => array('column' => 'id', 'unique' => true) + ), + 'tableParameters' => array( + 'charset' => 'latin1', + 'collate' => 'latin1_general_ci' + ) + ), + ); + $new = array( + 'posts' => array( + 'id' => array('type' => 'integer', 'null' => false, 'default' => 0, 'key' => 'primary'), + 'author_id' => array('type' => 'integer', 'null' => false), + 'title' => array('type' => 'datetime', 'null' => false), + 'indexes' => array( + 'PRIMARY' => array('column' => 'id', 'unique' => true) + ), + 'tableParameters' => array( + 'charset' => 'latin1', + 'collate' => 'latin1_general_ci' + ) + ), + ); + $compare = $this->Schema->compare($old, $new); + $expected = array( + 'posts' => array( + 'change' => array( + 'title' => array( + 'type' => 'datetime', + 'null' => false, + ) + ) + ), + ); + $this->assertEquals($expected, $compare, 'Invalid SQL, datetime does not have length'); + } + +/** + * testSchemaLoading method + * + * @return void + */ + public function testSchemaLoading() { + $Other = $this->Schema->load(array('name' => 'MyOtherApp', 'path' => TMP . 'tests')); + $this->assertEquals('MyOtherApp', $Other->name); + $this->assertEquals($Other->tables, $this->Schema->tables); + } + +/** + * test loading schema files inside of plugins. + * + * @return void + */ + public function testSchemaLoadingFromPlugin() { + App::build(array( + 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS) + )); + CakePlugin::load('TestPlugin'); + $Other = $this->Schema->load(array('name' => 'TestPluginApp', 'plugin' => 'TestPlugin')); + $this->assertEquals('TestPluginApp', $Other->name); + $this->assertEquals(array('test_plugin_acos'), array_keys($Other->tables)); + + App::build(); + } + +/** + * testSchemaCreateTable method + * + * @return void + */ + public function testSchemaCreateTable() { + $db = ConnectionManager::getDataSource('test'); + $db->cacheSources = false; + + $Schema = new CakeSchema(array( + 'connection' => 'test', + 'testdescribes' => array( + 'id' => array('type' => 'integer', 'key' => 'primary'), + 'int_null' => array('type' => 'integer', 'null' => true), + 'int_not_null' => array('type' => 'integer', 'null' => false), + ), + )); + $sql = $db->createSchema($Schema); + + $col = $Schema->tables['testdescribes']['int_null']; + $col['name'] = 'int_null'; + $column = $this->db->buildColumn($col); + $this->assertRegExp('/' . preg_quote($column, '/') . '/', $sql); + + $col = $Schema->tables['testdescribes']['int_not_null']; + $col['name'] = 'int_not_null'; + $column = $this->db->buildColumn($col); + $this->assertRegExp('/' . preg_quote($column, '/') . '/', $sql); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/ConnectionManagerTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/ConnectionManagerTest.php new file mode 100644 index 0000000..a35d06b --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/ConnectionManagerTest.php @@ -0,0 +1,346 @@ +assertTrue(count($sources) >= 1); + + $connections = array('default', 'test', 'test'); + $this->assertTrue(count(array_intersect(array_keys($sources), $connections)) >= 1); + } + +/** + * testGetDataSource method + * + * @return void + */ + public function testGetDataSource() { + App::build(array( + 'Model/Datasource' => array( + CAKE . 'Test' . DS . 'test_app' . DS . 'Model' . DS . 'Datasource' . DS + ) + )); + + $name = 'test_get_datasource'; + $config = array('datasource' => 'Test2Source'); + + $connection = ConnectionManager::create($name, $config); + $connections = ConnectionManager::enumConnectionObjects(); + $this->assertTrue((bool)(count(array_keys($connections) >= 1))); + + $source = ConnectionManager::getDataSource('test_get_datasource'); + $this->assertTrue(is_object($source)); + ConnectionManager::drop('test_get_datasource'); + } + +/** + * testGetDataSourceException() method + * + * @return void + * @expectedException MissingDatasourceConfigException + */ + public function testGetDataSourceException() { + ConnectionManager::getDataSource('non_existent_source'); + } + +/** + * testGetPluginDataSource method + * + * @return void + */ + public function testGetPluginDataSource() { + App::build(array( + 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS) + ), App::RESET); + CakePlugin::load('TestPlugin'); + $name = 'test_source'; + $config = array('datasource' => 'TestPlugin.TestSource'); + $connection = ConnectionManager::create($name, $config); + + $this->assertTrue(class_exists('TestSource')); + $this->assertEquals($connection->configKeyName, $name); + $this->assertEquals($connection->config, $config); + + ConnectionManager::drop($name); + } + +/** + * testGetPluginDataSourceAndPluginDriver method + * + * @return void + */ + public function testGetPluginDataSourceAndPluginDriver() { + App::build(array( + 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS) + ), App::RESET); + CakePlugin::load('TestPlugin'); + $name = 'test_plugin_source_and_driver'; + $config = array('datasource' => 'TestPlugin.Database/TestDriver'); + + $connection = ConnectionManager::create($name, $config); + + $this->assertTrue(class_exists('TestSource')); + $this->assertTrue(class_exists('TestDriver')); + $this->assertEquals($connection->configKeyName, $name); + $this->assertEquals($connection->config, $config); + + ConnectionManager::drop($name); + } + +/** + * testGetLocalDataSourceAndPluginDriver method + * + * @return void + */ + public function testGetLocalDataSourceAndPluginDriver() { + App::build(array( + 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS) + )); + CakePlugin::load('TestPlugin'); + $name = 'test_local_source_and_plugin_driver'; + $config = array('datasource' => 'TestPlugin.Database/DboDummy'); + + $connection = ConnectionManager::create($name, $config); + + $this->assertTrue(class_exists('DboSource')); + $this->assertTrue(class_exists('DboDummy')); + $this->assertEquals($connection->configKeyName, $name); + + ConnectionManager::drop($name); + } + +/** + * testGetPluginDataSourceAndLocalDriver method + * + * @return void + */ + public function testGetPluginDataSourceAndLocalDriver() { + App::build(array( + 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS), + 'Model/Datasource/Database' => array( + CAKE . 'Test' . DS . 'test_app' . DS . 'Model' . DS . 'Datasource' . DS . 'Database' . DS + ) + )); + + $name = 'test_plugin_source_and_local_driver'; + $config = array('datasource' => 'Database/TestLocalDriver'); + + $connection = ConnectionManager::create($name, $config); + + $this->assertTrue(class_exists('TestSource')); + $this->assertTrue(class_exists('TestLocalDriver')); + $this->assertEquals($connection->configKeyName, $name); + $this->assertEquals($connection->config, $config); + ConnectionManager::drop($name); + } + +/** + * testSourceList method + * + * @return void + */ + public function testSourceList() { + ConnectionManager::getDataSource('test'); + $sources = ConnectionManager::sourceList(); + $this->assertTrue(count($sources) >= 1); + $this->assertTrue(in_array('test', array_keys($sources))); + } + +/** + * testGetSourceName method + * + * @return void + */ + public function testGetSourceName() { + $connections = ConnectionManager::enumConnectionObjects(); + $source = ConnectionManager::getDataSource('test'); + $result = ConnectionManager::getSourceName($source); + + $this->assertEquals('test', $result); + + $source = new StdClass(); + $result = ConnectionManager::getSourceName($source); + $this->assertNull($result); + } + +/** + * testLoadDataSource method + * + * @return void + */ + public function testLoadDataSource() { + $connections = array( + array('classname' => 'Mysql', 'filename' => 'Mysql', 'package' => 'Database'), + array('classname' => 'Postgres', 'filename' => 'Postgres', 'package' => 'Database'), + array('classname' => 'Sqlite', 'filename' => 'Sqlite', 'package' => 'Database'), + ); + + foreach ($connections as $connection) { + $exists = class_exists($connection['classname']); + $loaded = ConnectionManager::loadDataSource($connection); + $this->assertEquals($loaded, !$exists, "Failed loading the {$connection['classname']} datasource"); + } + } + +/** + * testLoadDataSourceException() method + * + * @return void + * @expectedException MissingDatasourceException + */ + public function testLoadDataSourceException() { + $connection = array('classname' => 'NonExistentDataSource', 'filename' => 'non_existent'); + $loaded = ConnectionManager::loadDataSource($connection); + } + +/** + * testCreateDataSource method + * + * @return void + */ + public function testCreateDataSourceWithIntegrationTests() { + $name = 'test_created_connection'; + + $connections = ConnectionManager::enumConnectionObjects(); + $this->assertTrue((bool)(count(array_keys($connections) >= 1))); + + $source = ConnectionManager::getDataSource('test'); + $this->assertTrue(is_object($source)); + + $config = $source->config; + $connection = ConnectionManager::create($name, $config); + + $this->assertTrue(is_object($connection)); + $this->assertEquals($name, $connection->configKeyName); + $this->assertEquals($name, ConnectionManager::getSourceName($connection)); + + $source = ConnectionManager::create(null, array()); + $this->assertEquals(null, $source); + + $source = ConnectionManager::create('another_test', array()); + $this->assertEquals(null, $source); + + $config = array('classname' => 'DboMysql', 'filename' => 'dbo' . DS . 'dbo_mysql'); + $source = ConnectionManager::create(null, $config); + $this->assertEquals(null, $source); + } + +/** + * testConnectionData method + * + * @return void + */ + public function testConnectionData() { + App::build(array( + 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS), + 'Model/Datasource' => array( + CAKE . 'Test' . DS . 'test_app' . DS . 'Model' . DS . 'Datasource' . DS + ) + ), App::RESET); + CakePlugin::load(array('TestPlugin', 'TestPluginTwo')); + $expected = array( + 'datasource' => 'Test2Source' + ); + + ConnectionManager::create('connection1', array('datasource' => 'Test2Source')); + $connections = ConnectionManager::enumConnectionObjects(); + $this->assertEquals($expected, $connections['connection1']); + ConnectionManager::drop('connection1'); + + ConnectionManager::create('connection2', array('datasource' => 'Test2Source')); + $connections = ConnectionManager::enumConnectionObjects(); + $this->assertEquals($expected, $connections['connection2']); + ConnectionManager::drop('connection2'); + + ConnectionManager::create('connection3', array('datasource' => 'TestPlugin.TestSource')); + $connections = ConnectionManager::enumConnectionObjects(); + $expected['datasource'] = 'TestPlugin.TestSource'; + $this->assertEquals($expected, $connections['connection3']); + ConnectionManager::drop('connection3'); + + ConnectionManager::create('connection4', array('datasource' => 'TestPlugin.TestSource')); + $connections = ConnectionManager::enumConnectionObjects(); + $this->assertEquals($expected, $connections['connection4']); + ConnectionManager::drop('connection4'); + + ConnectionManager::create('connection5', array('datasource' => 'Test2OtherSource')); + $connections = ConnectionManager::enumConnectionObjects(); + $expected['datasource'] = 'Test2OtherSource'; + $this->assertEquals($expected, $connections['connection5']); + ConnectionManager::drop('connection5'); + + ConnectionManager::create('connection6', array('datasource' => 'Test2OtherSource')); + $connections = ConnectionManager::enumConnectionObjects(); + $this->assertEquals($expected, $connections['connection6']); + ConnectionManager::drop('connection6'); + + ConnectionManager::create('connection7', array('datasource' => 'TestPlugin.TestOtherSource')); + $connections = ConnectionManager::enumConnectionObjects(); + $expected['datasource'] = 'TestPlugin.TestOtherSource'; + $this->assertEquals($expected, $connections['connection7']); + ConnectionManager::drop('connection7'); + + ConnectionManager::create('connection8', array('datasource' => 'TestPlugin.TestOtherSource')); + $connections = ConnectionManager::enumConnectionObjects(); + $this->assertEquals($expected, $connections['connection8']); + ConnectionManager::drop('connection8'); + } + +/** + * Tests that a connection configuration can be deleted in runtime + * + * @return void + */ + public function testDrop() { + App::build(array( + 'Model/Datasource' => array( + CAKE . 'Test' . DS . 'test_app' . DS . 'Model' . DS . 'Datasource' . DS + ) + )); + ConnectionManager::create('droppable', array('datasource' => 'Test2Source')); + $connections = ConnectionManager::enumConnectionObjects(); + $this->assertEquals(array('datasource' => 'Test2Source'), $connections['droppable']); + + $this->assertTrue(ConnectionManager::drop('droppable')); + $connections = ConnectionManager::enumConnectionObjects(); + $this->assertFalse(isset($connections['droppable'])); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Datasource/CakeSessionTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Datasource/CakeSessionTest.php new file mode 100644 index 0000000..a227697 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Datasource/CakeSessionTest.php @@ -0,0 +1,754 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Model.Datasource + * @since CakePHP(tm) v 1.2.0.4206 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ + +App::uses('CakeSession', 'Model/Datasource'); +App::uses('DatabaseSession', 'Model/Datasource/Session'); +App::uses('CacheSession', 'Model/Datasource/Session'); + +class TestCakeSession extends CakeSession { + + public static function setUserAgent($value) { + self::$_userAgent = $value; + } + + public static function setHost($host) { + self::_setHost($host); + } + +} + +class TestCacheSession extends CacheSession { + + protected function _writeSession() { + return true; + } + +} + +class TestDatabaseSession extends DatabaseSession { + + protected function _writeSession() { + return true; + } + +} + +/** + * CakeSessionTest class + * + * @package Cake.Test.Case.Model.Datasource + */ +class CakeSessionTest extends CakeTestCase { + + protected static $_gcDivisor; + +/** + * Fixtures used in the SessionTest + * + * @var array + */ + public $fixtures = array('core.session'); + +/** + * setup before class. + * + * @return void + */ + public static function setupBeforeClass() { + // Make sure garbage colector will be called + self::$_gcDivisor = ini_get('session.gc_divisor'); + ini_set('session.gc_divisor', '1'); + } + +/** + * teardown after class + * + * @return void + */ + public static function teardownAfterClass() { + // Revert to the default setting + ini_set('session.gc_divisor', self::$_gcDivisor); + } + +/** + * setUp method + * + * @return void + */ + public function setUp() { + parent::setUp(); + Configure::write('Session', array( + 'defaults' => 'php', + 'cookie' => 'cakephp', + 'timeout' => 120, + 'cookieTimeout' => 120, + 'ini' => array(), + )); + TestCakeSession::init(); + } + +/** + * tearDown method + * + * @return void + */ + public function teardown() { + if (TestCakeSession::started()) { + session_write_close(); + } + unset($_SESSION); + parent::teardown(); + } + +/** + * test setting ini properties with Session configuration. + * + * @return void + */ + public function testSessionConfigIniSetting() { + $_SESSION = null; + + Configure::write('Session', array( + 'cookie' => 'test', + 'checkAgent' => false, + 'timeout' => 86400, + 'ini' => array( + 'session.referer_check' => 'example.com', + 'session.use_trans_sid' => false + ) + )); + TestCakeSession::start(); + $this->assertEquals('', ini_get('session.use_trans_sid'), 'Ini value is incorrect'); + $this->assertEquals('example.com', ini_get('session.referer_check'), 'Ini value is incorrect'); + $this->assertEquals('test', ini_get('session.name'), 'Ini value is incorrect'); + } + +/** + * testSessionPath + * + * @return void + */ + public function testSessionPath() { + TestCakeSession::init('/index.php'); + $this->assertEquals('/', TestCakeSession::$path); + + TestCakeSession::init('/sub_dir/index.php'); + $this->assertEquals('/sub_dir/', TestCakeSession::$path); + } + +/** + * testCakeSessionPathEmpty + * + * @return void + */ + public function testCakeSessionPathEmpty() { + TestCakeSession::init(''); + $this->assertEquals('/', TestCakeSession::$path, 'Session path is empty, with "" as $base needs to be /'); + } + +/** + * testCakeSessionPathContainsParams + * + * @return void + */ + public function testCakeSessionPathContainsQuestion() { + TestCakeSession::init('/index.php?'); + $this->assertEquals('/', TestCakeSession::$path); + } + +/** + * testSetHost + * + * @return void + */ + public function testSetHost() { + TestCakeSession::init(); + TestCakeSession::setHost('cakephp.org'); + $this->assertEquals('cakephp.org', TestCakeSession::$host); + } + +/** + * testSetHostWithPort + * + * @return void + */ + public function testSetHostWithPort() { + TestCakeSession::init(); + TestCakeSession::setHost('cakephp.org:443'); + $this->assertEquals('cakephp.org', TestCakeSession::$host); + } + +/** + * test valid with bogus user agent. + * + * @return void + */ + public function testValidBogusUserAgent() { + Configure::write('Session.checkAgent', true); + TestCakeSession::start(); + $this->assertTrue(TestCakeSession::valid(), 'Newly started session should be valid'); + + TestCakeSession::userAgent('bogus!'); + $this->assertFalse(TestCakeSession::valid(), 'user agent mismatch should fail.'); + } + +/** + * test valid with bogus user agent. + * + * @return void + */ + public function testValidTimeExpiry() { + Configure::write('Session.checkAgent', true); + TestCakeSession::start(); + $this->assertTrue(TestCakeSession::valid(), 'Newly started session should be valid'); + + TestCakeSession::$time = strtotime('next year'); + $this->assertFalse(TestCakeSession::valid(), 'time should cause failure.'); + } + +/** + * testCheck method + * + * @return void + */ + public function testCheck() { + TestCakeSession::write('SessionTestCase', 'value'); + $this->assertTrue(TestCakeSession::check('SessionTestCase')); + + $this->assertFalse(TestCakeSession::check('NotExistingSessionTestCase'), false); + } + +/** + * testSimpleRead method + * + * @return void + */ + public function testSimpleRead() { + TestCakeSession::write('testing', '1,2,3'); + $result = TestCakeSession::read('testing'); + $this->assertEquals('1,2,3', $result); + + TestCakeSession::write('testing', array('1' => 'one', '2' => 'two','3' => 'three')); + $result = TestCakeSession::read('testing.1'); + $this->assertEquals('one', $result); + + $result = TestCakeSession::read('testing'); + $this->assertEquals(array('1' => 'one', '2' => 'two', '3' => 'three'), $result); + + $result = TestCakeSession::read(); + $this->assertTrue(isset($result['testing'])); + $this->assertTrue(isset($result['Config'])); + $this->assertTrue(isset($result['Config']['userAgent'])); + + TestCakeSession::write('This.is.a.deep.array.my.friend', 'value'); + $result = TestCakeSession::read('This.is.a.deep.array.my.friend'); + $this->assertEquals('value', $result); + } + +/** + * testReadyEmpty + * + * @return void + */ + public function testReadyEmpty() { + $this->assertFalse(TestCakeSession::read('')); + } + +/** + * test writing a hash of values/ + * + * @return void + */ + public function testWriteArray() { + $result = TestCakeSession::write(array( + 'one' => 1, + 'two' => 2, + 'three' => array('something'), + 'null' => null + )); + $this->assertTrue($result); + $this->assertEquals(1, TestCakeSession::read('one')); + $this->assertEquals(array('something'), TestCakeSession::read('three')); + $this->assertEquals(null, TestCakeSession::read('null')); + } + +/** + * testWriteEmptyKey + * + * @return void + */ + public function testWriteEmptyKey() { + $this->assertFalse(TestCakeSession::write('', 'graham')); + $this->assertFalse(TestCakeSession::write('', '')); + $this->assertFalse(TestCakeSession::write('')); + } + +/** + * Test overwriting a string value as if it were an array. + * + * @return void + */ + public function testWriteOverwriteStringValue() { + TestCakeSession::write('Some.string', 'value'); + $this->assertEquals('value', TestCakeSession::read('Some.string')); + + TestCakeSession::write('Some.string.array', array('values')); + $this->assertEquals( + array('values'), + TestCakeSession::read('Some.string.array') + ); + } + +/** + * testId method + * + * @return void + */ + public function testId() { + TestCakeSession::destroy(); + + $result = TestCakeSession::id(); + $expected = session_id(); + $this->assertEquals($expected, $result); + + TestCakeSession::id('MySessionId'); + $result = TestCakeSession::id(); + $this->assertEquals('MySessionId', $result); + } + +/** + * testStarted method + * + * @return void + */ + public function testStarted() { + unset($_SESSION); + $_SESSION = null; + + $this->assertFalse(TestCakeSession::started()); + $this->assertTrue(TestCakeSession::start()); + $this->assertTrue(TestCakeSession::started()); + } + +/** + * testError method + * + * @return void + */ + public function testError() { + TestCakeSession::read('Does.not.exist'); + $result = TestCakeSession::error(); + $this->assertEquals("Does.not.exist doesn't exist", $result); + + TestCakeSession::delete('Failing.delete'); + $result = TestCakeSession::error(); + $this->assertEquals("Failing.delete doesn't exist", $result); + } + +/** + * testDel method + * + * @return void + */ + public function testDelete() { + $this->assertTrue(TestCakeSession::write('Delete.me', 'Clearing out')); + $this->assertTrue(TestCakeSession::delete('Delete.me')); + $this->assertFalse(TestCakeSession::check('Delete.me')); + $this->assertTrue(TestCakeSession::check('Delete')); + + $this->assertTrue(TestCakeSession::write('Clearing.sale', 'everything must go')); + $this->assertTrue(TestCakeSession::delete('Clearing')); + $this->assertFalse(TestCakeSession::check('Clearing.sale')); + $this->assertFalse(TestCakeSession::check('Clearing')); + } + +/** + * testDestroy method + * + * @return void + */ + public function testDestroy() { + TestCakeSession::write('bulletProof', 'invincible'); + $id = TestCakeSession::id(); + TestCakeSession::destroy(); + + $this->assertFalse(TestCakeSession::check('bulletProof')); + $this->assertNotEquals(TestCakeSession::id(), $id); + } + +/** + * testCheckingSavedEmpty method + * + * @return void + */ + public function testCheckingSavedEmpty() { + $this->assertTrue(TestCakeSession::write('SessionTestCase', 0)); + $this->assertTrue(TestCakeSession::check('SessionTestCase')); + + $this->assertTrue(TestCakeSession::write('SessionTestCase', '0')); + $this->assertTrue(TestCakeSession::check('SessionTestCase')); + + $this->assertTrue(TestCakeSession::write('SessionTestCase', false)); + $this->assertTrue(TestCakeSession::check('SessionTestCase')); + + $this->assertTrue(TestCakeSession::write('SessionTestCase', null)); + $this->assertFalse(TestCakeSession::check('SessionTestCase')); + } + +/** + * testCheckKeyWithSpaces method + * + * @return void + */ + public function testCheckKeyWithSpaces() { + $this->assertTrue(TestCakeSession::write('Session Test', "test")); + $this->assertTrue(TestCakeSession::check('Session Test')); + TestCakeSession::delete('Session Test'); + + $this->assertTrue(TestCakeSession::write('Session Test.Test Case', "test")); + $this->assertTrue(TestCakeSession::check('Session Test.Test Case')); + } + +/** + * testCheckEmpty + * + * @return void + */ + public function testCheckEmpty() { + $this->assertFalse(TestCakeSession::check()); + } + +/** + * test key exploitation + * + * @return void + */ + public function testKeyExploit() { + $key = "a'] = 1; phpinfo(); \$_SESSION['a"; + $result = TestCakeSession::write($key, 'haxored'); + $this->assertTrue($result); + + $result = TestCakeSession::read($key); + $this->assertEquals('haxored', $result); + } + +/** + * testReadingSavedEmpty method + * + * @return void + */ + public function testReadingSavedEmpty() { + TestCakeSession::write('SessionTestCase', 0); + $this->assertEquals(0, TestCakeSession::read('SessionTestCase')); + + TestCakeSession::write('SessionTestCase', '0'); + $this->assertEquals('0', TestCakeSession::read('SessionTestCase')); + $this->assertFalse(TestCakeSession::read('SessionTestCase') === 0); + + TestCakeSession::write('SessionTestCase', false); + $this->assertFalse(TestCakeSession::read('SessionTestCase')); + + TestCakeSession::write('SessionTestCase', null); + $this->assertEquals(null, TestCakeSession::read('SessionTestCase')); + } + +/** + * testCheckUserAgentFalse method + * + * @return void + */ + public function testCheckUserAgentFalse() { + Configure::write('Session.checkAgent', false); + TestCakeSession::setUserAgent(md5('http://randomdomainname.com' . Configure::read('Security.salt'))); + $this->assertTrue(TestCakeSession::valid()); + } + +/** + * testCheckUserAgentTrue method + * + * @return void + */ + public function testCheckUserAgentTrue() { + Configure::write('Session.checkAgent', true); + TestCakeSession::$error = false; + $agent = md5('http://randomdomainname.com' . Configure::read('Security.salt')); + + TestCakeSession::write('Config.userAgent', md5('Hacking you!')); + TestCakeSession::setUserAgent($agent); + $this->assertFalse(TestCakeSession::valid()); + } + +/** + * testReadAndWriteWithCakeStorage method + * + * @return void + */ + public function testReadAndWriteWithCakeStorage() { + Configure::write('Session.defaults', 'cake'); + + TestCakeSession::init(); + TestCakeSession::start(); + + TestCakeSession::write('SessionTestCase', 0); + $this->assertEquals(0, TestCakeSession::read('SessionTestCase')); + + TestCakeSession::write('SessionTestCase', '0'); + $this->assertEquals('0', TestCakeSession::read('SessionTestCase')); + $this->assertFalse(TestCakeSession::read('SessionTestCase') === 0); + + TestCakeSession::write('SessionTestCase', false); + $this->assertFalse(TestCakeSession::read('SessionTestCase')); + + TestCakeSession::write('SessionTestCase', null); + $this->assertEquals(null, TestCakeSession::read('SessionTestCase')); + + TestCakeSession::write('SessionTestCase', 'This is a Test'); + $this->assertEquals('This is a Test', TestCakeSession::read('SessionTestCase')); + + TestCakeSession::write('SessionTestCase', 'This is a Test'); + TestCakeSession::write('SessionTestCase', 'This was updated'); + $this->assertEquals('This was updated', TestCakeSession::read('SessionTestCase')); + + TestCakeSession::destroy(); + $this->assertNull(TestCakeSession::read('SessionTestCase')); + } + +/** + * test using a handler from app/Model/Datasource/Session. + * + * @return void + */ + public function testUsingAppLibsHandler() { + App::build(array( + 'Model/Datasource/Session' => array( + CAKE . 'Test' . DS . 'test_app' . DS . 'Model' . DS . 'Datasource' . DS . 'Session' . DS + ), + 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS) + ), App::RESET); + Configure::write('Session', array( + 'defaults' => 'cake', + 'handler' => array( + 'engine' => 'TestAppLibSession' + ) + )); + TestCakeSession::destroy(); + $this->assertTrue(TestCakeSession::started()); + + App::build(); + } + +/** + * test using a handler from a plugin. + * + * @return void + */ + public function testUsingPluginHandler() { + App::build(array( + 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS) + ), App::RESET); + CakePlugin::load('TestPlugin'); + + Configure::write('Session', array( + 'defaults' => 'cake', + 'handler' => array( + 'engine' => 'TestPlugin.TestPluginSession' + ) + )); + + TestCakeSession::destroy(); + $this->assertTrue(TestCakeSession::started()); + + App::build(); + } + +/** + * testReadAndWriteWithCacheStorage method + * + * @return void + */ + public function testReadAndWriteWithCacheStorage() { + Configure::write('Session.defaults', 'cache'); + Configure::write('Session.handler.engine', 'TestCacheSession'); + + TestCakeSession::init(); + TestCakeSession::destroy(); + + TestCakeSession::write('SessionTestCase', 0); + $this->assertEquals(0, TestCakeSession::read('SessionTestCase')); + + TestCakeSession::write('SessionTestCase', '0'); + $this->assertEquals('0', TestCakeSession::read('SessionTestCase')); + $this->assertFalse(TestCakeSession::read('SessionTestCase') === 0); + + TestCakeSession::write('SessionTestCase', false); + $this->assertFalse(TestCakeSession::read('SessionTestCase')); + + TestCakeSession::write('SessionTestCase', null); + $this->assertEquals(null, TestCakeSession::read('SessionTestCase')); + + TestCakeSession::write('SessionTestCase', 'This is a Test'); + $this->assertEquals('This is a Test', TestCakeSession::read('SessionTestCase')); + + TestCakeSession::write('SessionTestCase', 'This is a Test'); + TestCakeSession::write('SessionTestCase', 'This was updated'); + $this->assertEquals('This was updated', TestCakeSession::read('SessionTestCase')); + + TestCakeSession::destroy(); + $this->assertNull(TestCakeSession::read('SessionTestCase')); + } + +/** + * test that changing the config name of the cache config works. + * + * @return void + */ + public function testReadAndWriteWithCustomCacheConfig() { + Configure::write('Session.defaults', 'cache'); + Configure::write('Session.handler.engine', 'TestCacheSession'); + Configure::write('Session.handler.config', 'session_test'); + + Cache::config('session_test', array( + 'engine' => 'File', + 'prefix' => 'session_test_', + )); + + TestCakeSession::init(); + TestCakeSession::start(); + + TestCakeSession::write('SessionTestCase', 'Some value'); + $this->assertEquals('Some value', TestCakeSession::read('SessionTestCase')); + $id = TestCakeSession::id(); + + Cache::delete($id, 'session_test'); + } + +/** + * testReadAndWriteWithDatabaseStorage method + * + * @return void + */ + public function testReadAndWriteWithDatabaseStorage() { + Configure::write('Session.defaults', 'database'); + Configure::write('Session.handler.engine', 'TestDatabaseSession'); + Configure::write('Session.handler.table', 'sessions'); + Configure::write('Session.handler.model', 'Session'); + Configure::write('Session.handler.database', 'test'); + + TestCakeSession::init(); + $this->assertNull(TestCakeSession::id()); + + TestCakeSession::start(); + $expected = session_id(); + $this->assertEquals($expected, TestCakeSession::id()); + + TestCakeSession::renew(); + $this->assertFalse($expected == TestCakeSession::id()); + + $expected = session_id(); + $this->assertEquals($expected, TestCakeSession::id()); + + TestCakeSession::write('SessionTestCase', 0); + $this->assertEquals(0, TestCakeSession::read('SessionTestCase')); + + TestCakeSession::write('SessionTestCase', '0'); + $this->assertEquals('0', TestCakeSession::read('SessionTestCase')); + $this->assertFalse(TestCakeSession::read('SessionTestCase') === 0); + + TestCakeSession::write('SessionTestCase', false); + $this->assertFalse(TestCakeSession::read('SessionTestCase')); + + TestCakeSession::write('SessionTestCase', null); + $this->assertEquals(null, TestCakeSession::read('SessionTestCase')); + + TestCakeSession::write('SessionTestCase', 'This is a Test'); + $this->assertEquals('This is a Test', TestCakeSession::read('SessionTestCase')); + + TestCakeSession::write('SessionTestCase', 'Some additional data'); + $this->assertEquals('Some additional data', TestCakeSession::read('SessionTestCase')); + + TestCakeSession::destroy(); + $this->assertNull(TestCakeSession::read('SessionTestCase')); + + Configure::write('Session', array( + 'defaults' => 'php' + )); + TestCakeSession::init(); + } + +/** + * testSessionTimeout method + * + * @return void + */ + public function testSessionTimeout() { + Configure::write('debug', 2); + Configure::write('Session.defaults', 'cake'); + Configure::write('Session.autoRegenerate', false); + + $timeoutSeconds = Configure::read('Session.timeout') * 60; + + TestCakeSession::destroy(); + TestCakeSession::write('Test', 'some value'); + + $this->assertWithinMargin(time() + $timeoutSeconds, CakeSession::$sessionTime, 1); + $this->assertEquals(10, $_SESSION['Config']['countdown']); + $this->assertWithinMargin(CakeSession::$sessionTime, $_SESSION['Config']['time'], 1); + $this->assertWithinMargin(time(), CakeSession::$time, 1); + $this->assertWithinMargin(time() + $timeoutSeconds, $_SESSION['Config']['time'], 1); + + Configure::write('Session.harden', true); + TestCakeSession::destroy(); + + TestCakeSession::write('Test', 'some value'); + $this->assertWithinMargin(time() + $timeoutSeconds, CakeSession::$sessionTime, 1); + $this->assertEquals(10, $_SESSION['Config']['countdown']); + $this->assertWithinMargin(CakeSession::$sessionTime, $_SESSION['Config']['time'], 1); + $this->assertWithinMargin(time(), CakeSession::$time, 1); + $this->assertWithinMargin(CakeSession::$time + $timeoutSeconds, $_SESSION['Config']['time'], 1); + } + +/** + * Test that cookieTimeout matches timeout when unspecified. + * + * @return void + */ + public function testCookieTimeoutFallback() { + $_SESSION = null; + Configure::write('Session', array( + 'defaults' => 'cake', + 'timeout' => 400, + )); + TestCakeSession::start(); + $this->assertEquals(400, Configure::read('Session.cookieTimeout')); + $this->assertEquals(400, Configure::read('Session.timeout')); + $this->assertEquals(400 * 60, ini_get('session.cookie_lifetime')); + $this->assertEquals(400 * 60, ini_get('session.gc_maxlifetime')); + + $_SESSION = null; + Configure::write('Session', array( + 'defaults' => 'cake', + 'timeout' => 400, + 'cookieTimeout' => 600 + )); + TestCakeSession::start(); + $this->assertEquals(600, Configure::read('Session.cookieTimeout')); + $this->assertEquals(400, Configure::read('Session.timeout')); + } + +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Datasource/DataSourceTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Datasource/DataSourceTest.php new file mode 100644 index 0000000..3bb9bd0 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Datasource/DataSourceTest.php @@ -0,0 +1,250 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The Open Group Test Suite License + * Redistributions of files must retain the above copyright notice. + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Model.Datasource + * @since CakePHP(tm) v 1.2.0.4206 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ + +App::uses('Model', 'Model'); +App::uses('DataSource', 'Model/Datasource'); + +/** + * TestSource + * + * @package Cake.Test.Case.Model.Datasource + */ +class TestSource extends DataSource { + +/** + * _schema + * @var type + */ + protected $_schema = array( + 'id' => array( + 'type' => 'integer', + 'null' => false, + 'key' => 'primary', + 'length' => 11, + ), + 'text' => array( + 'type' => 'string', + 'null' => true, + 'length' => 140, + ), + 'status' => array( + 'type' => 'string', + 'null' => true, + 'length' => 140, + ), + 'customField' => array( + 'type' => 'string', + 'null' => true, + 'length' => 255, + ), + ); + +/** + * listSources + * + * @return boolean + */ + public function listSources() { + return null; + } + +/** + * Returns the schema for the datasource to enable create/update + * + * @param object $Model + * @return array + */ + public function describe(Model $Model) { + return $this->_schema; + } + +/** + * Just return $func to pass to read() to figure out the COUNT + * Required for delete/update to work + * + * @param Model $Model + * @param type $func + * @param type $params + * @return array + */ + public function calculate(Model $Model, $func, $params = array()) { + return $func; + } + +} + +/** + * DataSourceTest class + * + * @package Cake.Test.Case.Model.Datasource + */ +class DataSourceTest extends CakeTestCase { + +/** + * Name of test source + * + * @var string + */ + public $sourceName = 'myapitest'; + +/** + * setUp method + * + * @return void + */ + public function setUp() { + parent::setUp(); + $this->Source = $this->getMock( + 'TestSource', + array('create', 'read', 'update', 'delete') + ); + ConnectionManager::create($this->sourceName, array( + 'datasource' => get_class($this->Source), + 'apiKey' => '1234abcd', + )); + $this->Model = $this->getMock( + 'Model', + array('getDataSource'), + array(array('ds' => $this->sourceName)) + ); + $this->Model->expects($this->any()) + ->method('getDataSource') + ->will($this->returnValue($this->Source)); + } + +/** + * tearDown method + * + * @return void + */ + public function tearDown() { + parent::tearDown(); + unset($this->Model, $this->Source); + ConnectionManager::drop($this->sourceName); + } + +/** + * testCreate + * + * @return void + */ + public function testCreate() { + $data = array( + $this->Model->alias => array( + 'text' => 'This is a test', + 'status' => 'Test status', + 'customField' => array( + 'array', 'field', 'type', + 'for', 'custom', 'datasources', + ), + ), + ); + $this->Source->expects($this->once()) + ->method('create') + ->with( + $this->equalTo($this->Model), + $this->equalTo(array_keys($data[$this->Model->alias])), + $this->equalTo(array_values($data[$this->Model->alias])) + ); + $this->Model->save($data); + } + +/** + * testRead + * + * @return void + */ + public function testRead() { + $expected = array( + 'conditions' => array('status' => 'test'), + 'fields' => null, + 'joins' => array(), + 'limit' => 10, + 'offset' => null, + 'order' => array(array('status')), + 'page' => 1, + 'group' => null, + 'callbacks' => true, + ); + $this->Source->expects($this->once()) + ->method('read') + ->with( + $this->anything(), + $this->equalTo($expected) + ); + $this->Model->find('all', array( + 'conditions' => array('status' => 'test'), + 'limit' => 10, + 'order' => array('status'), + )); + } + +/** + * testUpdate + * + * @return void + */ + public function testUpdate() { + $data = array( + $this->Model->alias => array( + 'id' => 1, + 'text' => 'This is a test', + 'status' => 'Test status', + 'customField' => array( + 'array', 'field', 'type', + 'for', 'custom', 'datasources', + ), + ), + ); + $this->Source->expects($this->any()) + ->method('read') + ->will($this->returnValue(array( + array($this->Model->alias => array('count' => 1)) + ))); + $this->Source->expects($this->once()) + ->method('update') + ->with( + $this->equalTo($this->Model), + $this->equalTo(array_keys($data[$this->Model->alias])), + $this->equalTo(array_values($data[$this->Model->alias])) + ); + $this->Model->save($data); + } + +/** + * testDelete + * + * @return void + */ + public function testDelete() { + $this->Source->expects($this->any()) + ->method('read') + ->will($this->returnValue(array( + array($this->Model->alias => array('count' => 1)) + ))); + $this->Source->expects($this->once()) + ->method('delete') + ->with( + $this->equalTo($this->Model), + $this->equalTo(array($this->Model->alias . '.id' => 1)) + ); + $this->Model->delete(1); + } + +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Datasource/Database/MysqlTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Datasource/Database/MysqlTest.php new file mode 100644 index 0000000..dcd9aef --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Datasource/Database/MysqlTest.php @@ -0,0 +1,3623 @@ +Dbo = ConnectionManager::getDataSource('test'); + if (!($this->Dbo instanceof Mysql)) { + $this->markTestSkipped('The MySQL extension is not available.'); + } + $this->_debug = Configure::read('debug'); + Configure::write('debug', 1); + $this->model = ClassRegistry::init('MysqlTestModel'); + } + +/** + * Sets up a Dbo class instance for testing + * + */ + public function tearDown() { + unset($this->model); + ClassRegistry::flush(); + Configure::write('debug', $this->_debug); + } + +/** + * Test Dbo value method + * + * @group quoting + */ + public function testQuoting() { + $result = $this->Dbo->fields($this->model); + $expected = array( + '`MysqlTestModel`.`id`', + '`MysqlTestModel`.`client_id`', + '`MysqlTestModel`.`name`', + '`MysqlTestModel`.`login`', + '`MysqlTestModel`.`passwd`', + '`MysqlTestModel`.`addr_1`', + '`MysqlTestModel`.`addr_2`', + '`MysqlTestModel`.`zip_code`', + '`MysqlTestModel`.`city`', + '`MysqlTestModel`.`country`', + '`MysqlTestModel`.`phone`', + '`MysqlTestModel`.`fax`', + '`MysqlTestModel`.`url`', + '`MysqlTestModel`.`email`', + '`MysqlTestModel`.`comments`', + '`MysqlTestModel`.`last_login`', + '`MysqlTestModel`.`created`', + '`MysqlTestModel`.`updated`' + ); + $this->assertEquals($expected, $result); + + $expected = 1.2; + $result = $this->Dbo->value(1.2, 'float'); + $this->assertEquals($expected, $result); + + $expected = "'1,2'"; + $result = $this->Dbo->value('1,2', 'float'); + $this->assertEquals($expected, $result); + + $expected = "'4713e29446'"; + $result = $this->Dbo->value('4713e29446'); + + $this->assertEquals($expected, $result); + + $expected = 'NULL'; + $result = $this->Dbo->value('', 'integer'); + $this->assertEquals($expected, $result); + + $expected = "'0'"; + $result = $this->Dbo->value('', 'boolean'); + $this->assertEquals($expected, $result); + + $expected = 10010001; + $result = $this->Dbo->value(10010001); + $this->assertEquals($expected, $result); + + $expected = "'00010010001'"; + $result = $this->Dbo->value('00010010001'); + $this->assertEquals($expected, $result); + } + +/** + * test that localized floats don't cause trouble. + * + * @group quoting + * @return void + */ + public function testLocalizedFloats() { + $this->skipIf(DS === '\\', 'The locale is not supported in Windows and affect the others tests.'); + + $restore = setlocale(LC_NUMERIC, 0); + setlocale(LC_NUMERIC, 'de_DE'); + + $result = $this->Dbo->value(3.141593); + $this->assertEquals('3.141593', $result); + + $result = $this->db->value(3.141593, 'float'); + $this->assertEquals('3.141593', $result); + + $result = $this->db->value(1234567.11, 'float'); + $this->assertEquals('1234567.11', $result); + + $result = $this->db->value(123456.45464748, 'float'); + $this->assertContains('123456.454647', $result); + + $result = $this->db->value(0.987654321, 'float'); + $this->assertEquals('0.987654321', (string)$result); + + $result = $this->db->value(2.2E-54, 'float'); + $this->assertEquals('2.2E-54', (string)$result); + + $result = $this->db->value(2.2E-54); + $this->assertEquals('2.2E-54', (string)$result); + + setlocale(LC_NUMERIC, $restore); + } + +/** + * test that scientific notations are working correctly + * + * @return void + */ + public function testScientificNotation() { + $result = $this->db->value(2.2E-54, 'float'); + $this->assertEquals('2.2E-54', (string)$result); + + $result = $this->db->value(2.2E-54); + $this->assertEquals('2.2E-54', (string)$result); + } + +/** + * testTinyintCasting method + * + * + * @return void + */ + public function testTinyintCasting() { + $this->Dbo->cacheSources = false; + $tableName = 'tinyint_' . uniqid(); + $this->Dbo->rawQuery('CREATE TABLE ' . $this->Dbo->fullTableName($tableName) . ' (id int(11) AUTO_INCREMENT, bool tinyint(1), small_int tinyint(2), primary key(id));'); + + $this->model = new CakeTestModel(array( + 'name' => 'Tinyint', 'table' => $tableName, 'ds' => 'test' + )); + + $result = $this->model->schema(); + $this->assertEquals('boolean', $result['bool']['type']); + $this->assertEquals('integer', $result['small_int']['type']); + + $this->assertTrue((bool)$this->model->save(array('bool' => 5, 'small_int' => 5))); + $result = $this->model->find('first'); + $this->assertSame($result['Tinyint']['bool'], true); + $this->assertSame($result['Tinyint']['small_int'], '5'); + $this->model->deleteAll(true); + + $this->assertTrue((bool)$this->model->save(array('bool' => 0, 'small_int' => 100))); + $result = $this->model->find('first'); + $this->assertSame($result['Tinyint']['bool'], false); + $this->assertSame($result['Tinyint']['small_int'], '100'); + $this->model->deleteAll(true); + + $this->assertTrue((bool)$this->model->save(array('bool' => true, 'small_int' => 0))); + $result = $this->model->find('first'); + $this->assertSame($result['Tinyint']['bool'], true); + $this->assertSame($result['Tinyint']['small_int'], '0'); + $this->model->deleteAll(true); + + $this->Dbo->rawQuery('DROP TABLE ' . $this->Dbo->fullTableName($tableName)); + } + +/** + * testLastAffected method + * + * + * @return void + */ + public function testLastAffected() { + $this->Dbo->cacheSources = false; + $tableName = 'tinyint_' . uniqid(); + $this->Dbo->rawQuery('CREATE TABLE ' . $this->Dbo->fullTableName($tableName) . ' (id int(11) AUTO_INCREMENT, bool tinyint(1), small_int tinyint(2), primary key(id));'); + + $this->model = new CakeTestModel(array( + 'name' => 'Tinyint', 'table' => $tableName, 'ds' => 'test' + )); + + $this->assertTrue((bool)$this->model->save(array('bool' => 5, 'small_int' => 5))); + $this->assertEquals(1, $this->model->find('count')); + $this->model->deleteAll(true); + $result = $this->Dbo->lastAffected(); + $this->assertEquals(1, $result); + $this->assertEquals(0, $this->model->find('count')); + + $this->Dbo->rawQuery('DROP TABLE ' . $this->Dbo->fullTableName($tableName)); + } + +/** + * testIndexDetection method + * + * @group indices + * @return void + */ + public function testIndexDetection() { + $this->Dbo->cacheSources = false; + + $name = $this->Dbo->fullTableName('simple'); + $this->Dbo->rawQuery('CREATE TABLE ' . $name . ' (id int(11) AUTO_INCREMENT, bool tinyint(1), small_int tinyint(2), primary key(id));'); + $expected = array('PRIMARY' => array('column' => 'id', 'unique' => 1)); + $result = $this->Dbo->index('simple', false); + $this->Dbo->rawQuery('DROP TABLE ' . $name); + $this->assertEquals($expected, $result); + + $name = $this->Dbo->fullTableName('with_a_key'); + $this->Dbo->rawQuery('CREATE TABLE ' . $name . ' (id int(11) AUTO_INCREMENT, bool tinyint(1), small_int tinyint(2), primary key(id), KEY `pointless_bool` ( `bool` ));'); + $expected = array( + 'PRIMARY' => array('column' => 'id', 'unique' => 1), + 'pointless_bool' => array('column' => 'bool', 'unique' => 0), + ); + $result = $this->Dbo->index('with_a_key', false); + $this->Dbo->rawQuery('DROP TABLE ' . $name); + $this->assertEquals($expected, $result); + + $name = $this->Dbo->fullTableName('with_two_keys'); + $this->Dbo->rawQuery('CREATE TABLE ' . $name . ' (id int(11) AUTO_INCREMENT, bool tinyint(1), small_int tinyint(2), primary key(id), KEY `pointless_bool` ( `bool` ), KEY `pointless_small_int` ( `small_int` ));'); + $expected = array( + 'PRIMARY' => array('column' => 'id', 'unique' => 1), + 'pointless_bool' => array('column' => 'bool', 'unique' => 0), + 'pointless_small_int' => array('column' => 'small_int', 'unique' => 0), + ); + $result = $this->Dbo->index('with_two_keys', false); + $this->Dbo->rawQuery('DROP TABLE ' . $name); + $this->assertEquals($expected, $result); + + $name = $this->Dbo->fullTableName('with_compound_keys'); + $this->Dbo->rawQuery('CREATE TABLE ' . $name . ' (id int(11) AUTO_INCREMENT, bool tinyint(1), small_int tinyint(2), primary key(id), KEY `pointless_bool` ( `bool` ), KEY `pointless_small_int` ( `small_int` ), KEY `one_way` ( `bool`, `small_int` ));'); + $expected = array( + 'PRIMARY' => array('column' => 'id', 'unique' => 1), + 'pointless_bool' => array('column' => 'bool', 'unique' => 0), + 'pointless_small_int' => array('column' => 'small_int', 'unique' => 0), + 'one_way' => array('column' => array('bool', 'small_int'), 'unique' => 0), + ); + $result = $this->Dbo->index('with_compound_keys', false); + $this->Dbo->rawQuery('DROP TABLE ' . $name); + $this->assertEquals($expected, $result); + + $name = $this->Dbo->fullTableName('with_multiple_compound_keys'); + $this->Dbo->rawQuery('CREATE TABLE ' . $name . ' (id int(11) AUTO_INCREMENT, bool tinyint(1), small_int tinyint(2), primary key(id), KEY `pointless_bool` ( `bool` ), KEY `pointless_small_int` ( `small_int` ), KEY `one_way` ( `bool`, `small_int` ), KEY `other_way` ( `small_int`, `bool` ));'); + $expected = array( + 'PRIMARY' => array('column' => 'id', 'unique' => 1), + 'pointless_bool' => array('column' => 'bool', 'unique' => 0), + 'pointless_small_int' => array('column' => 'small_int', 'unique' => 0), + 'one_way' => array('column' => array('bool', 'small_int'), 'unique' => 0), + 'other_way' => array('column' => array('small_int', 'bool'), 'unique' => 0), + ); + $result = $this->Dbo->index('with_multiple_compound_keys', false); + $this->Dbo->rawQuery('DROP TABLE ' . $name); + $this->assertEquals($expected, $result); + } + +/** + * testBuildColumn method + * + * @return void + */ + public function testBuildColumn() { + $restore = $this->Dbo->columns; + $this->Dbo->columns = array('varchar(255)' => 1); + $data = array( + 'name' => 'testName', + 'type' => 'varchar(255)', + 'default', + 'null' => true, + 'key', + 'comment' => 'test' + ); + $result = $this->Dbo->buildColumn($data); + $expected = '`testName` DEFAULT NULL COMMENT \'test\''; + $this->assertEquals($expected, $result); + + $data = array( + 'name' => 'testName', + 'type' => 'varchar(255)', + 'default', + 'null' => true, + 'key', + 'charset' => 'utf8', + 'collate' => 'utf8_unicode_ci' + ); + $result = $this->Dbo->buildColumn($data); + $expected = '`testName` CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL'; + $this->assertEquals($expected, $result); + $this->Dbo->columns = $restore; + } + +/** + * MySQL 4.x returns index data in a different format, + * Using a mock ensure that MySQL 4.x output is properly parsed. + * + * @group indices + * @return void + */ + public function testIndexOnMySQL4Output() { + $name = $this->Dbo->fullTableName('simple'); + + $mockDbo = $this->getMock('Mysql', array('connect', '_execute', 'getVersion')); + $columnData = array( + array('0' => array( + 'Table' => 'with_compound_keys', + 'Non_unique' => '0', + 'Key_name' => 'PRIMARY', + 'Seq_in_index' => '1', + 'Column_name' => 'id', + 'Collation' => 'A', + 'Cardinality' => '0', + 'Sub_part' => null, + 'Packed' => null, + 'Null' => '', + 'Index_type' => 'BTREE', + 'Comment' => '' + )), + array('0' => array( + 'Table' => 'with_compound_keys', + 'Non_unique' => '1', + 'Key_name' => 'pointless_bool', + 'Seq_in_index' => '1', + 'Column_name' => 'bool', + 'Collation' => 'A', + 'Cardinality' => null, + 'Sub_part' => null, + 'Packed' => null, + 'Null' => 'YES', + 'Index_type' => 'BTREE', + 'Comment' => '' + )), + array('0' => array( + 'Table' => 'with_compound_keys', + 'Non_unique' => '1', + 'Key_name' => 'pointless_small_int', + 'Seq_in_index' => '1', + 'Column_name' => 'small_int', + 'Collation' => 'A', + 'Cardinality' => null, + 'Sub_part' => null, + 'Packed' => null, + 'Null' => 'YES', + 'Index_type' => 'BTREE', + 'Comment' => '' + )), + array('0' => array( + 'Table' => 'with_compound_keys', + 'Non_unique' => '1', + 'Key_name' => 'one_way', + 'Seq_in_index' => '1', + 'Column_name' => 'bool', + 'Collation' => 'A', + 'Cardinality' => null, + 'Sub_part' => null, + 'Packed' => null, + 'Null' => 'YES', + 'Index_type' => 'BTREE', + 'Comment' => '' + )), + array('0' => array( + 'Table' => 'with_compound_keys', + 'Non_unique' => '1', + 'Key_name' => 'one_way', + 'Seq_in_index' => '2', + 'Column_name' => 'small_int', + 'Collation' => 'A', + 'Cardinality' => null, + 'Sub_part' => null, + 'Packed' => null, + 'Null' => 'YES', + 'Index_type' => 'BTREE', + 'Comment' => '' + )) + ); + + $mockDbo->expects($this->once())->method('getVersion')->will($this->returnValue('4.1')); + $resultMock = $this->getMock('PDOStatement', array('fetch')); + $mockDbo->expects($this->once()) + ->method('_execute') + ->with('SHOW INDEX FROM ' . $name) + ->will($this->returnValue($resultMock)); + + foreach ($columnData as $i => $data) { + $resultMock->expects($this->at($i))->method('fetch')->will($this->returnValue((object)$data)); + } + + $result = $mockDbo->index($name, false); + $expected = array( + 'PRIMARY' => array('column' => 'id', 'unique' => 1), + 'pointless_bool' => array('column' => 'bool', 'unique' => 0), + 'pointless_small_int' => array('column' => 'small_int', 'unique' => 0), + 'one_way' => array('column' => array('bool', 'small_int'), 'unique' => 0), + ); + $this->assertEquals($expected, $result); + } + +/** + * testColumn method + * + * @return void + */ + public function testColumn() { + $result = $this->Dbo->column('varchar(50)'); + $expected = 'string'; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->column('text'); + $expected = 'text'; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->column('int(11)'); + $expected = 'integer'; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->column('int(11) unsigned'); + $expected = 'integer'; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->column('tinyint(1)'); + $expected = 'boolean'; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->column('boolean'); + $expected = 'boolean'; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->column('float'); + $expected = 'float'; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->column('float unsigned'); + $expected = 'float'; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->column('double unsigned'); + $expected = 'float'; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->column('decimal(14,7) unsigned'); + $expected = 'float'; + $this->assertEquals($expected, $result); + } + +/** + * testAlterSchemaIndexes method + * + * @group indices + * @return void + */ + public function testAlterSchemaIndexes() { + $this->Dbo->cacheSources = $this->Dbo->testing = false; + $table = $this->Dbo->fullTableName('altertest'); + + $schemaA = new CakeSchema(array( + 'name' => 'AlterTest1', + 'connection' => 'test', + 'altertest' => array( + 'id' => array('type' => 'integer', 'null' => false, 'default' => 0), + 'name' => array('type' => 'string', 'null' => false, 'length' => 50), + 'group1' => array('type' => 'integer', 'null' => true), + 'group2' => array('type' => 'integer', 'null' => true) + ))); + $result = $this->Dbo->createSchema($schemaA); + $this->assertContains('`id` int(11) DEFAULT 0 NOT NULL,', $result); + $this->assertContains('`name` varchar(50) NOT NULL,', $result); + $this->assertContains('`group1` int(11) DEFAULT NULL', $result); + $this->assertContains('`group2` int(11) DEFAULT NULL', $result); + + //Test that the string is syntactically correct + $query = $this->Dbo->getConnection()->prepare($result); + $this->assertEquals($query->queryString, $result); + + $schemaB = new CakeSchema(array( + 'name' => 'AlterTest2', + 'connection' => 'test', + 'altertest' => array( + 'id' => array('type' => 'integer', 'null' => false, 'default' => 0), + 'name' => array('type' => 'string', 'null' => false, 'length' => 50), + 'group1' => array('type' => 'integer', 'null' => true), + 'group2' => array('type' => 'integer', 'null' => true), + 'indexes' => array( + 'name_idx' => array('column' => 'name', 'unique' => 0), + 'group_idx' => array('column' => 'group1', 'unique' => 0), + 'compound_idx' => array('column' => array('group1', 'group2'), 'unique' => 0), + 'PRIMARY' => array('column' => 'id', 'unique' => 1)) + ))); + + $result = $this->Dbo->alterSchema($schemaB->compare($schemaA)); + $this->assertContains("ALTER TABLE $table", $result); + $this->assertContains('ADD KEY name_idx (`name`),', $result); + $this->assertContains('ADD KEY group_idx (`group1`),', $result); + $this->assertContains('ADD KEY compound_idx (`group1`, `group2`),', $result); + $this->assertContains('ADD PRIMARY KEY (`id`);', $result); + + //Test that the string is syntactically correct + $query = $this->Dbo->getConnection()->prepare($result); + $this->assertEquals($query->queryString, $result); + + // Change three indexes, delete one and add another one + $schemaC = new CakeSchema(array( + 'name' => 'AlterTest3', + 'connection' => 'test', + 'altertest' => array( + 'id' => array('type' => 'integer', 'null' => false, 'default' => 0), + 'name' => array('type' => 'string', 'null' => false, 'length' => 50), + 'group1' => array('type' => 'integer', 'null' => true), + 'group2' => array('type' => 'integer', 'null' => true), + 'indexes' => array( + 'name_idx' => array('column' => 'name', 'unique' => 1), + 'group_idx' => array('column' => 'group2', 'unique' => 0), + 'compound_idx' => array('column' => array('group2', 'group1'), 'unique' => 0), + 'id_name_idx' => array('column' => array('id', 'name'), 'unique' => 0)) + ))); + + $result = $this->Dbo->alterSchema($schemaC->compare($schemaB)); + $this->assertContains("ALTER TABLE $table", $result); + $this->assertContains('DROP PRIMARY KEY,', $result); + $this->assertContains('DROP KEY name_idx,', $result); + $this->assertContains('DROP KEY group_idx,', $result); + $this->assertContains('DROP KEY compound_idx,', $result); + $this->assertContains('ADD KEY id_name_idx (`id`, `name`),', $result); + $this->assertContains('ADD UNIQUE KEY name_idx (`name`),', $result); + $this->assertContains('ADD KEY group_idx (`group2`),', $result); + $this->assertContains('ADD KEY compound_idx (`group2`, `group1`);', $result); + + $query = $this->Dbo->getConnection()->prepare($result); + $this->assertEquals($query->queryString, $result); + + // Compare us to ourself. + $this->assertEquals(array(), $schemaC->compare($schemaC)); + + // Drop the indexes + $result = $this->Dbo->alterSchema($schemaA->compare($schemaC)); + + $this->assertContains("ALTER TABLE $table", $result); + $this->assertContains('DROP KEY name_idx,', $result); + $this->assertContains('DROP KEY group_idx,', $result); + $this->assertContains('DROP KEY compound_idx,', $result); + $this->assertContains('DROP KEY id_name_idx;', $result); + + $query = $this->Dbo->getConnection()->prepare($result); + $this->assertEquals($query->queryString, $result); + } + +/** + * test saving and retrieval of blobs + * + * @return void + */ + public function testBlobSaving() { + $this->loadFixtures('BinaryTest'); + $this->Dbo->cacheSources = false; + $data = file_get_contents(CAKE . 'Test' . DS . 'test_app' . DS . 'webroot' . DS . 'img' . DS . 'cake.power.gif'); + + $model = new CakeTestModel(array('name' => 'BinaryTest', 'ds' => 'test')); + $model->save(compact('data')); + + $result = $model->find('first'); + $this->assertEquals($data, $result['BinaryTest']['data']); + } + +/** + * test altering the table settings with schema. + * + * @return void + */ + public function testAlteringTableParameters() { + $this->Dbo->cacheSources = $this->Dbo->testing = false; + + $schemaA = new CakeSchema(array( + 'name' => 'AlterTest1', + 'connection' => 'test', + 'altertest' => array( + 'id' => array('type' => 'integer', 'null' => false, 'default' => 0), + 'name' => array('type' => 'string', 'null' => false, 'length' => 50), + 'tableParameters' => array( + 'charset' => 'latin1', + 'collate' => 'latin1_general_ci', + 'engine' => 'MyISAM' + ) + ) + )); + $this->Dbo->rawQuery($this->Dbo->createSchema($schemaA)); + $schemaB = new CakeSchema(array( + 'name' => 'AlterTest1', + 'connection' => 'test', + 'altertest' => array( + 'id' => array('type' => 'integer', 'null' => false, 'default' => 0), + 'name' => array('type' => 'string', 'null' => false, 'length' => 50), + 'tableParameters' => array( + 'charset' => 'utf8', + 'collate' => 'utf8_general_ci', + 'engine' => 'InnoDB' + ) + ) + )); + $result = $this->Dbo->alterSchema($schemaB->compare($schemaA)); + $this->assertContains('DEFAULT CHARSET=utf8', $result); + $this->assertContains('ENGINE=InnoDB', $result); + $this->assertContains('COLLATE=utf8_general_ci', $result); + + $this->Dbo->rawQuery($result); + $result = $this->Dbo->listDetailedSources($this->Dbo->fullTableName('altertest', false, false)); + $this->assertEquals('utf8_general_ci', $result['Collation']); + $this->assertEquals('InnoDB', $result['Engine']); + $this->assertEquals('utf8', $result['charset']); + + $this->Dbo->rawQuery($this->Dbo->dropSchema($schemaA)); + } + +/** + * test alterSchema on two tables. + * + * @return void + */ + public function testAlteringTwoTables() { + $schema1 = new CakeSchema(array( + 'name' => 'AlterTest1', + 'connection' => 'test', + 'altertest' => array( + 'id' => array('type' => 'integer', 'null' => false, 'default' => 0), + 'name' => array('type' => 'string', 'null' => false, 'length' => 50), + ), + 'other_table' => array( + 'id' => array('type' => 'integer', 'null' => false, 'default' => 0), + 'name' => array('type' => 'string', 'null' => false, 'length' => 50), + ) + )); + $schema2 = new CakeSchema(array( + 'name' => 'AlterTest1', + 'connection' => 'test', + 'altertest' => array( + 'id' => array('type' => 'integer', 'null' => false, 'default' => 0), + 'field_two' => array('type' => 'string', 'null' => false, 'length' => 50), + ), + 'other_table' => array( + 'id' => array('type' => 'integer', 'null' => false, 'default' => 0), + 'field_two' => array('type' => 'string', 'null' => false, 'length' => 50), + ) + )); + $result = $this->Dbo->alterSchema($schema2->compare($schema1)); + $this->assertEquals(2, substr_count($result, 'field_two'), 'Too many fields'); + } + +/** + * testReadTableParameters method + * + * @return void + */ + public function testReadTableParameters() { + $this->Dbo->cacheSources = $this->Dbo->testing = false; + $tableName = 'tinyint_' . uniqid(); + $table = $this->Dbo->fullTableName($tableName); + $this->Dbo->rawQuery('CREATE TABLE ' . $table . ' (id int(11) AUTO_INCREMENT, bool tinyint(1), small_int tinyint(2), primary key(id)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;'); + $result = $this->Dbo->readTableParameters($this->Dbo->fullTableName($tableName, false, false)); + $this->Dbo->rawQuery('DROP TABLE ' . $table); + $expected = array( + 'charset' => 'utf8', + 'collate' => 'utf8_unicode_ci', + 'engine' => 'InnoDB'); + $this->assertEquals($expected, $result); + + $table = $this->Dbo->fullTableName($tableName); + $this->Dbo->rawQuery('CREATE TABLE ' . $table . ' (id int(11) AUTO_INCREMENT, bool tinyint(1), small_int tinyint(2), primary key(id)) ENGINE=MyISAM DEFAULT CHARSET=cp1250 COLLATE=cp1250_general_ci;'); + $result = $this->Dbo->readTableParameters($this->Dbo->fullTableName($tableName, false, false)); + $this->Dbo->rawQuery('DROP TABLE ' . $table); + $expected = array( + 'charset' => 'cp1250', + 'collate' => 'cp1250_general_ci', + 'engine' => 'MyISAM'); + $this->assertEquals($expected, $result); + } + +/** + * testBuildTableParameters method + * + * @return void + */ + public function testBuildTableParameters() { + $this->Dbo->cacheSources = $this->Dbo->testing = false; + $data = array( + 'charset' => 'utf8', + 'collate' => 'utf8_unicode_ci', + 'engine' => 'InnoDB'); + $result = $this->Dbo->buildTableParameters($data); + $expected = array( + 'DEFAULT CHARSET=utf8', + 'COLLATE=utf8_unicode_ci', + 'ENGINE=InnoDB'); + $this->assertEquals($expected, $result); + } + +/** + * testBuildTableParameters method + * + * @return void + */ + public function testGetCharsetName() { + $this->Dbo->cacheSources = $this->Dbo->testing = false; + $result = $this->Dbo->getCharsetName('utf8_unicode_ci'); + $this->assertEquals('utf8', $result); + $result = $this->Dbo->getCharsetName('cp1250_general_ci'); + $this->assertEquals('cp1250', $result); + } + +/** + * test that changing the virtualFieldSeparator allows for __ fields. + * + * @return void + */ + public function testVirtualFieldSeparators() { + $this->loadFixtures('BinaryTest'); + $model = new CakeTestModel(array('table' => 'binary_tests', 'ds' => 'test', 'name' => 'BinaryTest')); + $model->virtualFields = array( + 'other__field' => 'SUM(id)' + ); + + $this->Dbo->virtualFieldSeparator = '_$_'; + $result = $this->Dbo->fields($model, null, array('data', 'other__field')); + + $expected = array('`BinaryTest`.`data`', '(SUM(id)) AS `BinaryTest_$_other__field`'); + $this->assertEquals($expected, $result); + } + +/** + * Test describe() on a fixture. + * + * @return void + */ + public function testDescribe() { + $this->loadFixtures('Apple'); + + $model = new Apple(); + $result = $this->Dbo->describe($model); + + $this->assertTrue(isset($result['id'])); + $this->assertTrue(isset($result['color'])); + + $result = $this->Dbo->describe($model->useTable); + + $this->assertTrue(isset($result['id'])); + $this->assertTrue(isset($result['color'])); + } + +/** + * test that a describe() gets additional fieldParameters + * + * @return void + */ + public function testDescribeGettingFieldParameters() { + $schema = new CakeSchema(array( + 'connection' => 'test', + 'testdescribes' => array( + 'id' => array('type' => 'integer', 'key' => 'primary'), + 'stringy' => array( + 'type' => 'string', + 'null' => true, + 'charset' => 'cp1250', + 'collate' => 'cp1250_general_ci', + ), + 'other_col' => array( + 'type' => 'string', + 'null' => false, + 'charset' => 'latin1', + 'comment' => 'Test Comment' + ) + ) + )); + + $this->Dbo->execute($this->Dbo->createSchema($schema)); + $model = new CakeTestModel(array('table' => 'testdescribes', 'name' => 'Testdescribes')); + $result = $model->getDataSource()->describe($model); + $this->Dbo->execute($this->Dbo->dropSchema($schema)); + + $this->assertEquals('cp1250_general_ci', $result['stringy']['collate']); + $this->assertEquals('cp1250', $result['stringy']['charset']); + $this->assertEquals('Test Comment', $result['other_col']['comment']); + } + +/** + * Tests that listSources method sends the correct query and parses the result accordingly + * @return void + */ + public function testListSources() { + $db = $this->getMock('Mysql', array('connect', '_execute')); + $queryResult = $this->getMock('PDOStatement'); + $db->expects($this->once()) + ->method('_execute') + ->with('SHOW TABLES FROM `cake`') + ->will($this->returnValue($queryResult)); + $queryResult->expects($this->at(0)) + ->method('fetch') + ->will($this->returnValue(array('cake_table'))); + $queryResult->expects($this->at(1)) + ->method('fetch') + ->will($this->returnValue(array('another_table'))); + $queryResult->expects($this->at(2)) + ->method('fetch') + ->will($this->returnValue(null)); + + $tables = $db->listSources(); + $this->assertEquals(array('cake_table', 'another_table'), $tables); + } + +/** + * test that listDetailedSources with a named table that doesn't exist. + * + * @return void + */ + public function testListDetailedSourcesNamed() { + $this->loadFixtures('Apple'); + + $result = $this->Dbo->listDetailedSources('imaginary'); + $this->assertEquals(array(), $result, 'Should be empty when table does not exist.'); + + $result = $this->Dbo->listDetailedSources(); + $tableName = $this->Dbo->fullTableName('apples', false, false); + $this->assertTrue(isset($result[$tableName]), 'Key should exist'); + } + +/** + * Tests that getVersion method sends the correct query for getting the mysql version + * @return void + */ + public function testGetVersion() { + $version = $this->Dbo->getVersion(); + $this->assertTrue(is_string($version)); + } + +/** + * Tests that getVersion method sends the correct query for getting the client encoding + * @return void + */ + public function testGetEncoding() { + $db = $this->getMock('Mysql', array('connect', '_execute')); + $queryResult = $this->getMock('PDOStatement'); + + $db->expects($this->once()) + ->method('_execute') + ->with('SHOW VARIABLES LIKE ?', array('character_set_client')) + ->will($this->returnValue($queryResult)); + $result = new StdClass; + $result->Value = 'utf-8'; + $queryResult->expects($this->once()) + ->method('fetchObject') + ->will($this->returnValue($result)); + + $encoding = $db->getEncoding(); + $this->assertEquals('utf-8', $encoding); + } + +/** + * testFieldDoubleEscaping method + * + * @return void + */ + public function testFieldDoubleEscaping() { + $db = $this->Dbo->config['database']; + $test = $this->getMock('Mysql', array('connect', '_execute', 'execute')); + $test->config['database'] = $db; + + $this->Model = $this->getMock('Article2', array('getDataSource')); + $this->Model->alias = 'Article'; + $this->Model->expects($this->any()) + ->method('getDataSource') + ->will($this->returnValue($test)); + + $this->assertEquals('`Article`.`id`', $this->Model->escapeField()); + $result = $test->fields($this->Model, null, $this->Model->escapeField()); + $this->assertEquals(array('`Article`.`id`'), $result); + + $test->expects($this->at(0))->method('execute') + ->with('SELECT `Article`.`id` FROM ' . $test->fullTableName('articles') . ' AS `Article` WHERE 1 = 1'); + + $result = $test->read($this->Model, array( + 'fields' => $this->Model->escapeField(), + 'conditions' => null, + 'recursive' => -1 + )); + + $test->startQuote = '['; + $test->endQuote = ']'; + $this->assertEquals('[Article].[id]', $this->Model->escapeField()); + + $result = $test->fields($this->Model, null, $this->Model->escapeField()); + $this->assertEquals(array('[Article].[id]'), $result); + + $test->expects($this->at(0))->method('execute') + ->with('SELECT [Article].[id] FROM ' . $test->fullTableName('articles') . ' AS [Article] WHERE 1 = 1'); + $result = $test->read($this->Model, array( + 'fields' => $this->Model->escapeField(), + 'conditions' => null, + 'recursive' => -1 + )); + } + +/** + * testGenerateAssociationQuerySelfJoin method + * + * @return void + */ + public function testGenerateAssociationQuerySelfJoin() { + $this->Dbo = $this->getMock('Mysql', array('connect', '_execute', 'execute')); + $this->startTime = microtime(true); + $this->Model = new Article2(); + $this->_buildRelatedModels($this->Model); + $this->_buildRelatedModels($this->Model->Category2); + $this->Model->Category2->ChildCat = new Category2(); + $this->Model->Category2->ParentCat = new Category2(); + + $queryData = array(); + + foreach ($this->Model->Category2->associations() as $type) { + foreach ($this->Model->Category2->{$type} as $assoc => $assocData) { + $linkModel = $this->Model->Category2->{$assoc}; + $external = isset($assocData['external']); + + if ($this->Model->Category2->alias == $linkModel->alias && $type != 'hasAndBelongsToMany' && $type != 'hasMany') { + $result = $this->Dbo->generateAssociationQuery($this->Model->Category2, $linkModel, $type, $assoc, $assocData, $queryData, $external, $null); + $this->assertFalse(empty($result)); + } else { + if ($this->Model->Category2->useDbConfig == $linkModel->useDbConfig) { + $result = $this->Dbo->generateAssociationQuery($this->Model->Category2, $linkModel, $type, $assoc, $assocData, $queryData, $external, $null); + $this->assertFalse(empty($result)); + } + } + } + } + + $query = $this->Dbo->generateAssociationQuery($this->Model->Category2, $null, null, null, null, $queryData, false, $null); + $this->assertRegExp('/^SELECT\s+(.+)FROM(.+)`Category2`\.`group_id`\s+=\s+`Group`\.`id`\)\s+LEFT JOIN(.+)WHERE\s+1 = 1\s*$/', $query); + + $this->Model = new TestModel4(); + $this->Model->schema(); + $this->_buildRelatedModels($this->Model); + + $binding = array('type' => 'belongsTo', 'model' => 'TestModel4Parent'); + $queryData = array(); + $resultSet = null; + $null = null; + + $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding); + + $_queryData = $queryData; + $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet); + $this->assertTrue($result); + + $expected = array( + 'conditions' => array(), + 'fields' => array( + '`TestModel4`.`id`', + '`TestModel4`.`name`', + '`TestModel4`.`created`', + '`TestModel4`.`updated`', + '`TestModel4Parent`.`id`', + '`TestModel4Parent`.`name`', + '`TestModel4Parent`.`created`', + '`TestModel4Parent`.`updated`' + ), + 'joins' => array( + array( + 'table' => $this->Dbo->fullTableName($this->Model), + 'alias' => 'TestModel4Parent', + 'type' => 'LEFT', + 'conditions' => '`TestModel4`.`parent_id` = `TestModel4Parent`.`id`' + ) + ), + 'order' => array(), + 'limit' => array(), + 'offset' => array(), + 'group' => array(), + 'callbacks' => null + ); + $queryData['joins'][0]['table'] = $this->Dbo->fullTableName($queryData['joins'][0]['table']); + $this->assertEquals($expected, $queryData); + + $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null); + $this->assertRegExp('/^SELECT\s+`TestModel4`\.`id`, `TestModel4`\.`name`, `TestModel4`\.`created`, `TestModel4`\.`updated`, `TestModel4Parent`\.`id`, `TestModel4Parent`\.`name`, `TestModel4Parent`\.`created`, `TestModel4Parent`\.`updated`\s+/', $result); + $this->assertRegExp('/FROM\s+\S+`test_model4` AS `TestModel4`\s+LEFT JOIN\s+\S+`test_model4` AS `TestModel4Parent`/', $result); + $this->assertRegExp('/\s+ON\s+\(`TestModel4`.`parent_id` = `TestModel4Parent`.`id`\)\s+WHERE/', $result); + $this->assertRegExp('/\s+WHERE\s+1 = 1\s+$/', $result); + + $params['assocData']['type'] = 'INNER'; + $this->Model->belongsTo['TestModel4Parent']['type'] = 'INNER'; + $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $_queryData, $params['external'], $resultSet); + $this->assertTrue($result); + $this->assertEquals('INNER', $_queryData['joins'][0]['type']); + } + +/** + * buildRelatedModels method + * + * @param Model $model + * @return void + */ + protected function _buildRelatedModels(Model $model) { + foreach ($model->associations() as $type) { + foreach ($model->{$type} as $assoc => $assocData) { + if (is_string($assocData)) { + $className = $assocData; + } elseif (isset($assocData['className'])) { + $className = $assocData['className']; + } + $model->$className = new $className(); + $model->$className->schema(); + } + } + } + +/** + * &_prepareAssociationQuery method + * + * @param Model $model + * @param array $queryData + * @param array $binding + * @return void + */ + protected function &_prepareAssociationQuery(Model $model, &$queryData, $binding) { + $type = $binding['type']; + $assoc = $binding['model']; + $assocData = $model->{$type}[$assoc]; + $className = $assocData['className']; + + $linkModel = $model->{$className}; + $external = isset($assocData['external']); + $queryData = $this->_scrubQueryData($queryData); + + $result = array_merge(array('linkModel' => &$linkModel), compact('type', 'assoc', 'assocData', 'external')); + return $result; + } + +/** + * Helper method copied from DboSource::_scrubQueryData() + * + * @param array $data + * @return array + */ + protected function _scrubQueryData($data) { + static $base = null; + if ($base === null) { + $base = array_fill_keys(array('conditions', 'fields', 'joins', 'order', 'limit', 'offset', 'group'), array()); + $base['callbacks'] = null; + } + return (array)$data + $base; + } + +/** + * testGenerateInnerJoinAssociationQuery method + * + * @return void + */ + public function testGenerateInnerJoinAssociationQuery() { + $db = $this->Dbo->config['database']; + $test = $this->getMock('Mysql', array('connect', '_execute', 'execute')); + $test->config['database'] = $db; + + $this->Model = $this->getMock('TestModel9', array('getDataSource')); + $this->Model->expects($this->any()) + ->method('getDataSource') + ->will($this->returnValue($test)); + + $this->Model->TestModel8 = $this->getMock('TestModel8', array('getDataSource')); + $this->Model->TestModel8->expects($this->any()) + ->method('getDataSource') + ->will($this->returnValue($test)); + + $testModel8Table = $this->Model->TestModel8->getDataSource()->fullTableName($this->Model->TestModel8); + + $test->expects($this->at(0))->method('execute') + ->with($this->stringContains('`TestModel9` LEFT JOIN ' . $testModel8Table)); + + $test->expects($this->at(1))->method('execute') + ->with($this->stringContains('TestModel9` INNER JOIN ' . $testModel8Table)); + + $test->read($this->Model, array('recursive' => 1)); + $this->Model->belongsTo['TestModel8']['type'] = 'INNER'; + $test->read($this->Model, array('recursive' => 1)); + } + +/** + * testGenerateAssociationQuerySelfJoinWithConditionsInHasOneBinding method + * + * @return void + */ + public function testGenerateAssociationQuerySelfJoinWithConditionsInHasOneBinding() { + $this->Model = new TestModel8(); + $this->Model->schema(); + $this->_buildRelatedModels($this->Model); + + $binding = array('type' => 'hasOne', 'model' => 'TestModel9'); + $queryData = array(); + $resultSet = null; + $null = null; + + $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding); + $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet); + $this->assertTrue($result); + + $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null); + $this->assertRegExp('/^SELECT\s+`TestModel8`\.`id`, `TestModel8`\.`test_model9_id`, `TestModel8`\.`name`, `TestModel8`\.`created`, `TestModel8`\.`updated`, `TestModel9`\.`id`, `TestModel9`\.`test_model8_id`, `TestModel9`\.`name`, `TestModel9`\.`created`, `TestModel9`\.`updated`\s+/', $result); + $this->assertRegExp('/FROM\s+\S+`test_model8` AS `TestModel8`\s+LEFT JOIN\s+\S+`test_model9` AS `TestModel9`/', $result); + $this->assertRegExp('/\s+ON\s+\(`TestModel9`\.`name` != \'mariano\'\s+AND\s+`TestModel9`.`test_model8_id` = `TestModel8`.`id`\)\s+WHERE/', $result); + $this->assertRegExp('/\s+WHERE\s+(?:\()?1\s+=\s+1(?:\))?\s*$/', $result); + } + +/** + * testGenerateAssociationQuerySelfJoinWithConditionsInBelongsToBinding method + * + * @return void + */ + public function testGenerateAssociationQuerySelfJoinWithConditionsInBelongsToBinding() { + $this->Model = new TestModel9(); + $this->Model->schema(); + $this->_buildRelatedModels($this->Model); + + $binding = array('type' => 'belongsTo', 'model' => 'TestModel8'); + $queryData = array(); + $resultSet = null; + $null = null; + + $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding); + $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet); + $this->assertTrue($result); + + $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null); + $this->assertRegExp('/^SELECT\s+`TestModel9`\.`id`, `TestModel9`\.`test_model8_id`, `TestModel9`\.`name`, `TestModel9`\.`created`, `TestModel9`\.`updated`, `TestModel8`\.`id`, `TestModel8`\.`test_model9_id`, `TestModel8`\.`name`, `TestModel8`\.`created`, `TestModel8`\.`updated`\s+/', $result); + $this->assertRegExp('/FROM\s+\S+`test_model9` AS `TestModel9`\s+LEFT JOIN\s+\S+`test_model8` AS `TestModel8`/', $result); + $this->assertRegExp('/\s+ON\s+\(`TestModel8`\.`name` != \'larry\'\s+AND\s+`TestModel9`.`test_model8_id` = `TestModel8`.`id`\)\s+WHERE/', $result); + $this->assertRegExp('/\s+WHERE\s+(?:\()?1\s+=\s+1(?:\))?\s*$/', $result); + } + +/** + * testGenerateAssociationQuerySelfJoinWithConditions method + * + * @return void + */ + public function testGenerateAssociationQuerySelfJoinWithConditions() { + $this->Model = new TestModel4(); + $this->Model->schema(); + $this->_buildRelatedModels($this->Model); + + $binding = array('type' => 'belongsTo', 'model' => 'TestModel4Parent'); + $queryData = array('conditions' => array('TestModel4Parent.name !=' => 'mariano')); + $resultSet = null; + $null = null; + + $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding); + + $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet); + $this->assertTrue($result); + + $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null); + $this->assertRegExp('/^SELECT\s+`TestModel4`\.`id`, `TestModel4`\.`name`, `TestModel4`\.`created`, `TestModel4`\.`updated`, `TestModel4Parent`\.`id`, `TestModel4Parent`\.`name`, `TestModel4Parent`\.`created`, `TestModel4Parent`\.`updated`\s+/', $result); + $this->assertRegExp('/FROM\s+\S+`test_model4` AS `TestModel4`\s+LEFT JOIN\s+\S+`test_model4` AS `TestModel4Parent`/', $result); + $this->assertRegExp('/\s+ON\s+\(`TestModel4`.`parent_id` = `TestModel4Parent`.`id`\)\s+WHERE/', $result); + $this->assertRegExp('/\s+WHERE\s+(?:\()?`TestModel4Parent`.`name`\s+!=\s+\'mariano\'(?:\))?\s*$/', $result); + + $this->Featured2 = new Featured2(); + $this->Featured2->schema(); + + $this->Featured2->bindModel(array( + 'belongsTo' => array( + 'ArticleFeatured2' => array( + 'conditions' => 'ArticleFeatured2.published = \'Y\'', + 'fields' => 'id, title, user_id, published' + ) + ) + )); + + $this->_buildRelatedModels($this->Featured2); + + $binding = array('type' => 'belongsTo', 'model' => 'ArticleFeatured2'); + $queryData = array('conditions' => array()); + $resultSet = null; + $null = null; + + $params = &$this->_prepareAssociationQuery($this->Featured2, $queryData, $binding); + + $result = $this->Dbo->generateAssociationQuery($this->Featured2, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet); + $this->assertTrue($result); + $result = $this->Dbo->generateAssociationQuery($this->Featured2, $null, null, null, null, $queryData, false, $null); + + $this->assertRegExp( + '/^SELECT\s+`Featured2`\.`id`, `Featured2`\.`article_id`, `Featured2`\.`category_id`, `Featured2`\.`name`,\s+' . + '`ArticleFeatured2`\.`id`, `ArticleFeatured2`\.`title`, `ArticleFeatured2`\.`user_id`, `ArticleFeatured2`\.`published`\s+' . + 'FROM\s+\S+`featured2` AS `Featured2`\s+LEFT JOIN\s+\S+`article_featured` AS `ArticleFeatured2`' . + '\s+ON\s+\(`ArticleFeatured2`.`published` = \'Y\'\s+AND\s+`Featured2`\.`article_featured2_id` = `ArticleFeatured2`\.`id`\)' . + '\s+WHERE\s+1\s+=\s+1\s*$/', + $result + ); + } + +/** + * testGenerateAssociationQueryHasOne method + * + * @return void + */ + public function testGenerateAssociationQueryHasOne() { + $this->Model = new TestModel4(); + $this->Model->schema(); + $this->_buildRelatedModels($this->Model); + + $binding = array('type' => 'hasOne', 'model' => 'TestModel5'); + + $queryData = array(); + $resultSet = null; + $null = null; + + $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding); + + $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet); + $this->assertTrue($result); + + $testModel5Table = $this->Dbo->fullTableName($this->Model->TestModel5); + $result = $this->Dbo->buildJoinStatement($queryData['joins'][0]); + $expected = ' LEFT JOIN ' . $testModel5Table . ' AS `TestModel5` ON (`TestModel5`.`test_model4_id` = `TestModel4`.`id`)'; + $this->assertEquals(trim($expected), trim($result)); + + $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null); + $this->assertRegExp('/^SELECT\s+`TestModel4`\.`id`, `TestModel4`\.`name`, `TestModel4`\.`created`, `TestModel4`\.`updated`, `TestModel5`\.`id`, `TestModel5`\.`test_model4_id`, `TestModel5`\.`name`, `TestModel5`\.`created`, `TestModel5`\.`updated`\s+/', $result); + $this->assertRegExp('/\s+FROM\s+\S+`test_model4` AS `TestModel4`\s+LEFT JOIN\s+/', $result); + $this->assertRegExp('/`test_model5` AS `TestModel5`\s+ON\s+\(`TestModel5`.`test_model4_id` = `TestModel4`.`id`\)\s+WHERE/', $result); + $this->assertRegExp('/\s+WHERE\s+(?:\()?\s*1 = 1\s*(?:\))?\s*$/', $result); + } + +/** + * testGenerateAssociationQueryHasOneWithConditions method + * + * @return void + */ + public function testGenerateAssociationQueryHasOneWithConditions() { + $this->Model = new TestModel4(); + $this->Model->schema(); + $this->_buildRelatedModels($this->Model); + + $binding = array('type' => 'hasOne', 'model' => 'TestModel5'); + + $queryData = array('conditions' => array('TestModel5.name !=' => 'mariano')); + $resultSet = null; + $null = null; + + $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding); + + $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet); + $this->assertTrue($result); + + $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null); + + $this->assertRegExp('/^SELECT\s+`TestModel4`\.`id`, `TestModel4`\.`name`, `TestModel4`\.`created`, `TestModel4`\.`updated`, `TestModel5`\.`id`, `TestModel5`\.`test_model4_id`, `TestModel5`\.`name`, `TestModel5`\.`created`, `TestModel5`\.`updated`\s+/', $result); + $this->assertRegExp('/\s+FROM\s+\S+`test_model4` AS `TestModel4`\s+LEFT JOIN\s+\S+`test_model5` AS `TestModel5`/', $result); + $this->assertRegExp('/\s+ON\s+\(`TestModel5`.`test_model4_id`\s+=\s+`TestModel4`.`id`\)\s+WHERE/', $result); + $this->assertRegExp('/\s+WHERE\s+(?:\()?\s*`TestModel5`.`name`\s+!=\s+\'mariano\'\s*(?:\))?\s*$/', $result); + } + +/** + * testGenerateAssociationQueryBelongsTo method + * + * @return void + */ + public function testGenerateAssociationQueryBelongsTo() { + $this->Model = new TestModel5(); + $this->Model->schema(); + $this->_buildRelatedModels($this->Model); + + $binding = array('type' => 'belongsTo', 'model' => 'TestModel4'); + $queryData = array(); + $resultSet = null; + $null = null; + + $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding); + + $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet); + $this->assertTrue($result); + + $testModel4Table = $this->Dbo->fullTableName($this->Model->TestModel4, true, true); + $result = $this->Dbo->buildJoinStatement($queryData['joins'][0]); + $expected = ' LEFT JOIN ' . $testModel4Table . ' AS `TestModel4` ON (`TestModel5`.`test_model4_id` = `TestModel4`.`id`)'; + $this->assertEquals(trim($expected), trim($result)); + + $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null); + $this->assertRegExp('/^SELECT\s+`TestModel5`\.`id`, `TestModel5`\.`test_model4_id`, `TestModel5`\.`name`, `TestModel5`\.`created`, `TestModel5`\.`updated`, `TestModel4`\.`id`, `TestModel4`\.`name`, `TestModel4`\.`created`, `TestModel4`\.`updated`\s+/', $result); + $this->assertRegExp('/\s+FROM\s+\S+`test_model5` AS `TestModel5`\s+LEFT JOIN\s+\S+`test_model4` AS `TestModel4`/', $result); + $this->assertRegExp('/\s+ON\s+\(`TestModel5`.`test_model4_id` = `TestModel4`.`id`\)\s+WHERE\s+/', $result); + $this->assertRegExp('/\s+WHERE\s+(?:\()?\s*1 = 1\s*(?:\))?\s*$/', $result); + } + +/** + * testGenerateAssociationQueryBelongsToWithConditions method + * + * @return void + */ + public function testGenerateAssociationQueryBelongsToWithConditions() { + $this->Model = new TestModel5(); + $this->Model->schema(); + $this->_buildRelatedModels($this->Model); + + $binding = array('type' => 'belongsTo', 'model' => 'TestModel4'); + $queryData = array('conditions' => array('TestModel5.name !=' => 'mariano')); + $resultSet = null; + $null = null; + + $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding); + + $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet); + $this->assertTrue($result); + + $testModel4Table = $this->Dbo->fullTableName($this->Model->TestModel4, true, true); + $result = $this->Dbo->buildJoinStatement($queryData['joins'][0]); + $expected = ' LEFT JOIN ' . $testModel4Table . ' AS `TestModel4` ON (`TestModel5`.`test_model4_id` = `TestModel4`.`id`)'; + $this->assertEquals(trim($expected), trim($result)); + + $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null); + $this->assertRegExp('/^SELECT\s+`TestModel5`\.`id`, `TestModel5`\.`test_model4_id`, `TestModel5`\.`name`, `TestModel5`\.`created`, `TestModel5`\.`updated`, `TestModel4`\.`id`, `TestModel4`\.`name`, `TestModel4`\.`created`, `TestModel4`\.`updated`\s+/', $result); + $this->assertRegExp('/\s+FROM\s+\S+`test_model5` AS `TestModel5`\s+LEFT JOIN\s+\S+`test_model4` AS `TestModel4`/', $result); + $this->assertRegExp('/\s+ON\s+\(`TestModel5`.`test_model4_id` = `TestModel4`.`id`\)\s+WHERE\s+/', $result); + $this->assertRegExp('/\s+WHERE\s+`TestModel5`.`name` != \'mariano\'\s*$/', $result); + } + +/** + * testGenerateAssociationQueryHasMany method + * + * @return void + */ + public function testGenerateAssociationQueryHasMany() { + $this->Model = new TestModel5(); + $this->Model->schema(); + $this->_buildRelatedModels($this->Model); + + $binding = array('type' => 'hasMany', 'model' => 'TestModel6'); + $queryData = array(); + $resultSet = null; + $null = null; + + $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding); + + $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet); + + $this->assertRegExp('/^SELECT\s+`TestModel6`\.`id`, `TestModel6`\.`test_model5_id`, `TestModel6`\.`name`, `TestModel6`\.`created`, `TestModel6`\.`updated`\s+/', $result); + $this->assertRegExp('/\s+FROM\s+\S+`test_model6` AS `TestModel6`\s+WHERE/', $result); + $this->assertRegExp('/\s+WHERE\s+`TestModel6`.`test_model5_id`\s+=\s+\({\$__cakeID__\$}\)/', $result); + + $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null); + $this->assertRegExp('/^SELECT\s+`TestModel5`\.`id`, `TestModel5`\.`test_model4_id`, `TestModel5`\.`name`, `TestModel5`\.`created`, `TestModel5`\.`updated`\s+/', $result); + $this->assertRegExp('/\s+FROM\s+\S+`test_model5` AS `TestModel5`\s+WHERE\s+/', $result); + $this->assertRegExp('/\s+WHERE\s+(?:\()?\s*1 = 1\s*(?:\))?\s*$/', $result); + } + +/** + * testGenerateAssociationQueryHasManyWithLimit method + * + * @return void + */ + public function testGenerateAssociationQueryHasManyWithLimit() { + $this->Model = new TestModel5(); + $this->Model->schema(); + $this->_buildRelatedModels($this->Model); + + $this->Model->hasMany['TestModel6']['limit'] = 2; + + $binding = array('type' => 'hasMany', 'model' => 'TestModel6'); + $queryData = array(); + $resultSet = null; + $null = null; + + $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding); + + $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet); + $this->assertRegExp( + '/^SELECT\s+' . + '`TestModel6`\.`id`, `TestModel6`\.`test_model5_id`, `TestModel6`\.`name`, `TestModel6`\.`created`, `TestModel6`\.`updated`\s+' . + 'FROM\s+\S+`test_model6` AS `TestModel6`\s+WHERE\s+' . + '`TestModel6`.`test_model5_id`\s+=\s+\({\$__cakeID__\$}\)\s*' . + 'LIMIT \d*' . + '\s*$/', $result + ); + + $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null); + $this->assertRegExp( + '/^SELECT\s+' . + '`TestModel5`\.`id`, `TestModel5`\.`test_model4_id`, `TestModel5`\.`name`, `TestModel5`\.`created`, `TestModel5`\.`updated`\s+' . + 'FROM\s+\S+`test_model5` AS `TestModel5`\s+WHERE\s+' . + '(?:\()?\s*1 = 1\s*(?:\))?' . + '\s*$/', $result + ); + } + +/** + * testGenerateAssociationQueryHasManyWithConditions method + * + * @return void + */ + public function testGenerateAssociationQueryHasManyWithConditions() { + $this->Model = new TestModel5(); + $this->Model->schema(); + $this->_buildRelatedModels($this->Model); + + $binding = array('type' => 'hasMany', 'model' => 'TestModel6'); + $queryData = array('conditions' => array('TestModel5.name !=' => 'mariano')); + $resultSet = null; + $null = null; + + $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding); + + $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet); + $this->assertRegExp('/^SELECT\s+`TestModel6`\.`id`, `TestModel6`\.`test_model5_id`, `TestModel6`\.`name`, `TestModel6`\.`created`, `TestModel6`\.`updated`\s+/', $result); + $this->assertRegExp('/\s+FROM\s+\S+`test_model6` AS `TestModel6`\s+WHERE\s+/', $result); + $this->assertRegExp('/WHERE\s+(?:\()?`TestModel6`\.`test_model5_id`\s+=\s+\({\$__cakeID__\$}\)(?:\))?/', $result); + + $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null); + $this->assertRegExp('/^SELECT\s+`TestModel5`\.`id`, `TestModel5`\.`test_model4_id`, `TestModel5`\.`name`, `TestModel5`\.`created`, `TestModel5`\.`updated`\s+/', $result); + $this->assertRegExp('/\s+FROM\s+\S+`test_model5` AS `TestModel5`\s+WHERE\s+/', $result); + $this->assertRegExp('/\s+WHERE\s+(?:\()?`TestModel5`.`name`\s+!=\s+\'mariano\'(?:\))?\s*$/', $result); + } + +/** + * testGenerateAssociationQueryHasManyWithOffsetAndLimit method + * + * @return void + */ + public function testGenerateAssociationQueryHasManyWithOffsetAndLimit() { + $this->Model = new TestModel5(); + $this->Model->schema(); + $this->_buildRelatedModels($this->Model); + + $backup = $this->Model->hasMany['TestModel6']; + + $this->Model->hasMany['TestModel6']['offset'] = 2; + $this->Model->hasMany['TestModel6']['limit'] = 5; + + $binding = array('type' => 'hasMany', 'model' => 'TestModel6'); + $queryData = array(); + $resultSet = null; + $null = null; + + $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding); + + $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet); + + $this->assertRegExp('/^SELECT\s+`TestModel6`\.`id`, `TestModel6`\.`test_model5_id`, `TestModel6`\.`name`, `TestModel6`\.`created`, `TestModel6`\.`updated`\s+/', $result); + $this->assertRegExp('/\s+FROM\s+\S+`test_model6` AS `TestModel6`\s+WHERE\s+/', $result); + $this->assertRegExp('/WHERE\s+(?:\()?`TestModel6`\.`test_model5_id`\s+=\s+\({\$__cakeID__\$}\)(?:\))?/', $result); + $this->assertRegExp('/\s+LIMIT 2,\s*5\s*$/', $result); + + $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null); + $this->assertRegExp('/^SELECT\s+`TestModel5`\.`id`, `TestModel5`\.`test_model4_id`, `TestModel5`\.`name`, `TestModel5`\.`created`, `TestModel5`\.`updated`\s+/', $result); + $this->assertRegExp('/\s+FROM\s+\S+`test_model5` AS `TestModel5`\s+WHERE\s+/', $result); + $this->assertRegExp('/\s+WHERE\s+(?:\()?1\s+=\s+1(?:\))?\s*$/', $result); + + $this->Model->hasMany['TestModel6'] = $backup; + } + +/** + * testGenerateAssociationQueryHasManyWithPageAndLimit method + * + * @return void + */ + public function testGenerateAssociationQueryHasManyWithPageAndLimit() { + $this->Model = new TestModel5(); + $this->Model->schema(); + $this->_buildRelatedModels($this->Model); + + $backup = $this->Model->hasMany['TestModel6']; + + $this->Model->hasMany['TestModel6']['page'] = 2; + $this->Model->hasMany['TestModel6']['limit'] = 5; + + $binding = array('type' => 'hasMany', 'model' => 'TestModel6'); + $queryData = array(); + $resultSet = null; + $null = null; + + $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding); + + $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet); + $this->assertRegExp('/^SELECT\s+`TestModel6`\.`id`, `TestModel6`\.`test_model5_id`, `TestModel6`\.`name`, `TestModel6`\.`created`, `TestModel6`\.`updated`\s+/', $result); + $this->assertRegExp('/\s+FROM\s+\S+`test_model6` AS `TestModel6`\s+WHERE\s+/', $result); + $this->assertRegExp('/WHERE\s+(?:\()?`TestModel6`\.`test_model5_id`\s+=\s+\({\$__cakeID__\$}\)(?:\))?/', $result); + $this->assertRegExp('/\s+LIMIT 5,\s*5\s*$/', $result); + + $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null); + $this->assertRegExp('/^SELECT\s+`TestModel5`\.`id`, `TestModel5`\.`test_model4_id`, `TestModel5`\.`name`, `TestModel5`\.`created`, `TestModel5`\.`updated`\s+/', $result); + $this->assertRegExp('/\s+FROM\s+\S+`test_model5` AS `TestModel5`\s+WHERE\s+/', $result); + $this->assertRegExp('/\s+WHERE\s+(?:\()?1\s+=\s+1(?:\))?\s*$/', $result); + + $this->Model->hasMany['TestModel6'] = $backup; + } + +/** + * testGenerateAssociationQueryHasManyWithFields method + * + * @return void + */ + public function testGenerateAssociationQueryHasManyWithFields() { + $this->Model = new TestModel5(); + $this->Model->schema(); + $this->_buildRelatedModels($this->Model); + + $binding = array('type' => 'hasMany', 'model' => 'TestModel6'); + $queryData = array('fields' => array('`TestModel5`.`name`')); + $resultSet = null; + $null = null; + + $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding); + + $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet); + $this->assertRegExp('/^SELECT\s+`TestModel6`\.`id`, `TestModel6`\.`test_model5_id`, `TestModel6`\.`name`, `TestModel6`\.`created`, `TestModel6`\.`updated`\s+/', $result); + $this->assertRegExp('/\s+FROM\s+\S+`test_model6` AS `TestModel6`\s+WHERE\s+/', $result); + $this->assertRegExp('/WHERE\s+(?:\()?`TestModel6`\.`test_model5_id`\s+=\s+\({\$__cakeID__\$}\)(?:\))?/', $result); + + $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null); + $this->assertRegExp('/^SELECT\s+`TestModel5`\.`name`, `TestModel5`\.`id`\s+/', $result); + $this->assertRegExp('/\s+FROM\s+\S+`test_model5` AS `TestModel5`\s+WHERE\s+/', $result); + $this->assertRegExp('/\s+WHERE\s+(?:\()?1\s+=\s+1(?:\))?\s*$/', $result); + + $binding = array('type' => 'hasMany', 'model' => 'TestModel6'); + $queryData = array('fields' => array('`TestModel5`.`id`, `TestModel5`.`name`')); + $resultSet = null; + $null = null; + + $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding); + + $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet); + $this->assertRegExp('/^SELECT\s+`TestModel6`\.`id`, `TestModel6`\.`test_model5_id`, `TestModel6`\.`name`, `TestModel6`\.`created`, `TestModel6`\.`updated`\s+/', $result); + $this->assertRegExp('/\s+FROM\s+\S+`test_model6` AS `TestModel6`\s+WHERE\s+/', $result); + $this->assertRegExp('/WHERE\s+(?:\()?`TestModel6`\.`test_model5_id`\s+=\s+\({\$__cakeID__\$}\)(?:\))?/', $result); + + $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null); + $this->assertRegExp('/^SELECT\s+`TestModel5`\.`id`, `TestModel5`\.`name`\s+/', $result); + $this->assertRegExp('/\s+FROM\s+\S+`test_model5` AS `TestModel5`\s+WHERE\s+/', $result); + $this->assertRegExp('/\s+WHERE\s+(?:\()?1\s+=\s+1(?:\))?\s*$/', $result); + + $binding = array('type' => 'hasMany', 'model' => 'TestModel6'); + $queryData = array('fields' => array('`TestModel5`.`name`', '`TestModel5`.`created`')); + $resultSet = null; + $null = null; + + $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding); + + $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet); + $this->assertRegExp('/^SELECT\s+`TestModel6`\.`id`, `TestModel6`\.`test_model5_id`, `TestModel6`\.`name`, `TestModel6`\.`created`, `TestModel6`\.`updated`\s+/', $result); + $this->assertRegExp('/\s+FROM\s+\S+`test_model6` AS `TestModel6`\s+WHERE\s+/', $result); + $this->assertRegExp('/WHERE\s+(?:\()?`TestModel6`\.`test_model5_id`\s+=\s+\({\$__cakeID__\$}\)(?:\))?/', $result); + + $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null); + $this->assertRegExp('/^SELECT\s+`TestModel5`\.`name`, `TestModel5`\.`created`, `TestModel5`\.`id`\s+/', $result); + $this->assertRegExp('/\s+FROM\s+\S+`test_model5` AS `TestModel5`\s+WHERE\s+/', $result); + $this->assertRegExp('/\s+WHERE\s+(?:\()?1\s+=\s+1(?:\))?\s*$/', $result); + + $this->Model->hasMany['TestModel6']['fields'] = array('name'); + + $binding = array('type' => 'hasMany', 'model' => 'TestModel6'); + $queryData = array('fields' => array('`TestModel5`.`id`', '`TestModel5`.`name`')); + $resultSet = null; + $null = null; + + $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding); + + $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet); + $this->assertRegExp('/^SELECT\s+`TestModel6`\.`name`, `TestModel6`\.`test_model5_id`\s+/', $result); + $this->assertRegExp('/\s+FROM\s+\S+`test_model6` AS `TestModel6`\s+WHERE\s+/', $result); + $this->assertRegExp('/WHERE\s+(?:\()?`TestModel6`\.`test_model5_id`\s+=\s+\({\$__cakeID__\$}\)(?:\))?/', $result); + + $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null); + $this->assertRegExp('/^SELECT\s+`TestModel5`\.`id`, `TestModel5`\.`name`\s+/', $result); + $this->assertRegExp('/\s+FROM\s+\S+`test_model5` AS `TestModel5`\s+WHERE\s+/', $result); + $this->assertRegExp('/\s+WHERE\s+(?:\()?1\s+=\s+1(?:\))?\s*$/', $result); + + unset($this->Model->hasMany['TestModel6']['fields']); + + $this->Model->hasMany['TestModel6']['fields'] = array('id', 'name'); + + $binding = array('type' => 'hasMany', 'model' => 'TestModel6'); + $queryData = array('fields' => array('`TestModel5`.`id`', '`TestModel5`.`name`')); + $resultSet = null; + $null = null; + + $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding); + + $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet); + $this->assertRegExp('/^SELECT\s+`TestModel6`\.`id`, `TestModel6`\.`name`, `TestModel6`\.`test_model5_id`\s+/', $result); + $this->assertRegExp('/\s+FROM\s+\S+`test_model6` AS `TestModel6`\s+WHERE\s+/', $result); + $this->assertRegExp('/WHERE\s+(?:\()?`TestModel6`\.`test_model5_id`\s+=\s+\({\$__cakeID__\$}\)(?:\))?/', $result); + + $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null); + $this->assertRegExp('/^SELECT\s+`TestModel5`\.`id`, `TestModel5`\.`name`\s+/', $result); + $this->assertRegExp('/\s+FROM\s+\S+`test_model5` AS `TestModel5`\s+WHERE\s+/', $result); + $this->assertRegExp('/\s+WHERE\s+(?:\()?1\s+=\s+1(?:\))?\s*$/', $result); + + unset($this->Model->hasMany['TestModel6']['fields']); + + $this->Model->hasMany['TestModel6']['fields'] = array('test_model5_id', 'name'); + + $binding = array('type' => 'hasMany', 'model' => 'TestModel6'); + $queryData = array('fields' => array('`TestModel5`.`id`', '`TestModel5`.`name`')); + $resultSet = null; + $null = null; + + $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding); + + $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet); + $this->assertRegExp('/^SELECT\s+`TestModel6`\.`test_model5_id`, `TestModel6`\.`name`\s+/', $result); + $this->assertRegExp('/\s+FROM\s+\S+`test_model6` AS `TestModel6`\s+WHERE\s+/', $result); + $this->assertRegExp('/WHERE\s+(?:\()?`TestModel6`\.`test_model5_id`\s+=\s+\({\$__cakeID__\$}\)(?:\))?/', $result); + + $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null); + $this->assertRegExp('/^SELECT\s+`TestModel5`\.`id`, `TestModel5`\.`name`\s+/', $result); + $this->assertRegExp('/\s+FROM\s+\S+`test_model5` AS `TestModel5`\s+WHERE\s+/', $result); + $this->assertRegExp('/\s+WHERE\s+(?:\()?1\s+=\s+1(?:\))?\s*$/', $result); + + unset($this->Model->hasMany['TestModel6']['fields']); + } + +/** + * test generateAssociationQuery with a hasMany and an aggregate function. + * + * @return void + */ + public function testGenerateAssociationQueryHasManyAndAggregateFunction() { + $this->Model = new TestModel5(); + $this->Model->schema(); + $this->_buildRelatedModels($this->Model); + + $binding = array('type' => 'hasMany', 'model' => 'TestModel6'); + $queryData = array('fields' => array('MIN(`TestModel5`.`test_model4_id`)')); + $resultSet = null; + $null = null; + + $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding); + $this->Model->recursive = 0; + + $result = $this->Dbo->generateAssociationQuery($this->Model, $null, $params['type'], $params['assoc'], $params['assocData'], $queryData, false, $resultSet); + $this->assertRegExp('/^SELECT\s+MIN\(`TestModel5`\.`test_model4_id`\)\s+FROM/', $result); + } + +/** + * testGenerateAssociationQueryHasAndBelongsToMany method + * + * @return void + */ + public function testGenerateAssociationQueryHasAndBelongsToMany() { + $this->Model = new TestModel4(); + $this->Model->schema(); + $this->_buildRelatedModels($this->Model); + + $binding = array('type' => 'hasAndBelongsToMany', 'model' => 'TestModel7'); + $queryData = array(); + $resultSet = null; + $null = null; + + $params = $this->_prepareAssociationQuery($this->Model, $queryData, $binding); + + $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet); + $assocTable = $this->Dbo->fullTableName($this->Model->TestModel4TestModel7, true, true); + $this->assertRegExp('/^SELECT\s+`TestModel7`\.`id`, `TestModel7`\.`name`, `TestModel7`\.`created`, `TestModel7`\.`updated`, `TestModel4TestModel7`\.`test_model4_id`, `TestModel4TestModel7`\.`test_model7_id`\s+/', $result); + $this->assertRegExp('/\s+FROM\s+\S+`test_model7` AS `TestModel7`\s+JOIN\s+' . $assocTable . '/', $result); + $this->assertRegExp('/\s+ON\s+\(`TestModel4TestModel7`\.`test_model4_id`\s+=\s+{\$__cakeID__\$}\s+AND/', $result); + $this->assertRegExp('/\s+AND\s+`TestModel4TestModel7`\.`test_model7_id`\s+=\s+`TestModel7`\.`id`\)/', $result); + $this->assertRegExp('/WHERE\s+(?:\()?1 = 1(?:\))?\s*$/', $result); + + $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null); + $this->assertRegExp('/^SELECT\s+`TestModel4`\.`id`, `TestModel4`\.`name`, `TestModel4`\.`created`, `TestModel4`\.`updated`\s+/', $result); + $this->assertRegExp('/\s+FROM\s+\S+`test_model4` AS `TestModel4`\s+WHERE/', $result); + $this->assertRegExp('/\s+WHERE\s+(?:\()?1 = 1(?:\))?\s*$/', $result); + } + +/** + * testGenerateAssociationQueryHasAndBelongsToManyWithConditions method + * + * @return void + */ + public function testGenerateAssociationQueryHasAndBelongsToManyWithConditions() { + $this->Model = new TestModel4(); + $this->Model->schema(); + $this->_buildRelatedModels($this->Model); + + $binding = array('type' => 'hasAndBelongsToMany', 'model' => 'TestModel7'); + $queryData = array('conditions' => array('TestModel4.name !=' => 'mariano')); + $resultSet = null; + $null = null; + + $params = $this->_prepareAssociationQuery($this->Model, $queryData, $binding); + + $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet); + $this->assertRegExp('/^SELECT\s+`TestModel7`\.`id`, `TestModel7`\.`name`, `TestModel7`\.`created`, `TestModel7`\.`updated`, `TestModel4TestModel7`\.`test_model4_id`, `TestModel4TestModel7`\.`test_model7_id`\s+/', $result); + $this->assertRegExp('/\s+FROM\s+\S+`test_model7`\s+AS\s+`TestModel7`\s+JOIN\s+\S+`test_model4_test_model7`\s+AS\s+`TestModel4TestModel7`/', $result); + $this->assertRegExp('/\s+ON\s+\(`TestModel4TestModel7`\.`test_model4_id`\s+=\s+{\$__cakeID__\$}/', $result); + $this->assertRegExp('/\s+AND\s+`TestModel4TestModel7`\.`test_model7_id`\s+=\s+`TestModel7`\.`id`\)\s+WHERE\s+/', $result); + + $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null); + $this->assertRegExp('/^SELECT\s+`TestModel4`\.`id`, `TestModel4`\.`name`, `TestModel4`\.`created`, `TestModel4`\.`updated`\s+/', $result); + $this->assertRegExp('/\s+FROM\s+\S+`test_model4` AS `TestModel4`\s+WHERE\s+(?:\()?`TestModel4`.`name`\s+!=\s+\'mariano\'(?:\))?\s*$/', $result); + } + +/** + * testGenerateAssociationQueryHasAndBelongsToManyWithOffsetAndLimit method + * + * @return void + */ + public function testGenerateAssociationQueryHasAndBelongsToManyWithOffsetAndLimit() { + $this->Model = new TestModel4(); + $this->Model->schema(); + $this->_buildRelatedModels($this->Model); + + $backup = $this->Model->hasAndBelongsToMany['TestModel7']; + + $this->Model->hasAndBelongsToMany['TestModel7']['offset'] = 2; + $this->Model->hasAndBelongsToMany['TestModel7']['limit'] = 5; + + $binding = array('type' => 'hasAndBelongsToMany', 'model' => 'TestModel7'); + $queryData = array(); + $resultSet = null; + $null = null; + + $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding); + + $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet); + $this->assertRegExp('/^SELECT\s+`TestModel7`\.`id`, `TestModel7`\.`name`, `TestModel7`\.`created`, `TestModel7`\.`updated`, `TestModel4TestModel7`\.`test_model4_id`, `TestModel4TestModel7`\.`test_model7_id`\s+/', $result); + $this->assertRegExp('/\s+FROM\s+\S+`test_model7`\s+AS\s+`TestModel7`\s+JOIN\s+\S+`test_model4_test_model7`\s+AS\s+`TestModel4TestModel7`/', $result); + $this->assertRegExp('/\s+ON\s+\(`TestModel4TestModel7`\.`test_model4_id`\s+=\s+{\$__cakeID__\$}\s+/', $result); + $this->assertRegExp('/\s+AND\s+`TestModel4TestModel7`\.`test_model7_id`\s+=\s+`TestModel7`\.`id`\)\s+WHERE\s+/', $result); + $this->assertRegExp('/\s+(?:\()?1\s+=\s+1(?:\))?\s*\s+LIMIT 2,\s*5\s*$/', $result); + + $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null); + $this->assertRegExp('/^SELECT\s+`TestModel4`\.`id`, `TestModel4`\.`name`, `TestModel4`\.`created`, `TestModel4`\.`updated`\s+/', $result); + $this->assertRegExp('/\s+FROM\s+\S+`test_model4` AS `TestModel4`\s+WHERE\s+(?:\()?1\s+=\s+1(?:\))?\s*$/', $result); + + $this->Model->hasAndBelongsToMany['TestModel7'] = $backup; + } + +/** + * testGenerateAssociationQueryHasAndBelongsToManyWithPageAndLimit method + * + * @return void + */ + public function testGenerateAssociationQueryHasAndBelongsToManyWithPageAndLimit() { + $this->Model = new TestModel4(); + $this->Model->schema(); + $this->_buildRelatedModels($this->Model); + + $backup = $this->Model->hasAndBelongsToMany['TestModel7']; + + $this->Model->hasAndBelongsToMany['TestModel7']['page'] = 2; + $this->Model->hasAndBelongsToMany['TestModel7']['limit'] = 5; + + $binding = array('type' => 'hasAndBelongsToMany', 'model' => 'TestModel7'); + $queryData = array(); + $resultSet = null; + $null = null; + + $params = &$this->_prepareAssociationQuery($this->Model, $queryData, $binding); + + $result = $this->Dbo->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet); + $this->assertRegExp('/^SELECT\s+`TestModel7`\.`id`, `TestModel7`\.`name`, `TestModel7`\.`created`, `TestModel7`\.`updated`, `TestModel4TestModel7`\.`test_model4_id`, `TestModel4TestModel7`\.`test_model7_id`\s+/', $result); + $this->assertRegExp('/\s+FROM\s+\S+`test_model7`\s+AS\s+`TestModel7`\s+JOIN\s+\S+`test_model4_test_model7`\s+AS\s+`TestModel4TestModel7`/', $result); + $this->assertRegExp('/\s+ON\s+\(`TestModel4TestModel7`\.`test_model4_id`\s+=\s+{\$__cakeID__\$}/', $result); + $this->assertRegExp('/\s+AND\s+`TestModel4TestModel7`\.`test_model7_id`\s+=\s+`TestModel7`\.`id`\)\s+WHERE\s+/', $result); + $this->assertRegExp('/\s+(?:\()?1\s+=\s+1(?:\))?\s*\s+LIMIT 5,\s*5\s*$/', $result); + + $result = $this->Dbo->generateAssociationQuery($this->Model, $null, null, null, null, $queryData, false, $null); + $this->assertRegExp('/^SELECT\s+`TestModel4`\.`id`, `TestModel4`\.`name`, `TestModel4`\.`created`, `TestModel4`\.`updated`\s+/', $result); + $this->assertRegExp('/\s+FROM\s+\S+`test_model4` AS `TestModel4`\s+WHERE\s+(?:\()?1\s+=\s+1(?:\))?\s*$/', $result); + + $this->Model->hasAndBelongsToMany['TestModel7'] = $backup; + } + +/** + * testSelectDistict method + * + * @return void + */ + public function testSelectDistict() { + $this->Model = new TestModel4(); + $result = $this->Dbo->fields($this->Model, 'Vendor', "DISTINCT Vendor.id, Vendor.name"); + $expected = array('DISTINCT `Vendor`.`id`', '`Vendor`.`name`'); + $this->assertEquals($expected, $result); + } + +/** + * testStringConditionsParsing method + * + * @return void + */ + public function testStringConditionsParsing() { + $result = $this->Dbo->conditions("ProjectBid.project_id = Project.id"); + $expected = " WHERE `ProjectBid`.`project_id` = `Project`.`id`"; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions("Candy.name LIKE 'a' AND HardCandy.name LIKE 'c'"); + $expected = " WHERE `Candy`.`name` LIKE 'a' AND `HardCandy`.`name` LIKE 'c'"; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions("HardCandy.name LIKE 'a' AND Candy.name LIKE 'c'"); + $expected = " WHERE `HardCandy`.`name` LIKE 'a' AND `Candy`.`name` LIKE 'c'"; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions("Post.title = '1.1'"); + $expected = " WHERE `Post`.`title` = '1.1'"; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions("User.id != 0 AND User.user LIKE '%arr%'"); + $expected = " WHERE `User`.`id` != 0 AND `User`.`user` LIKE '%arr%'"; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions("SUM(Post.comments_count) > 500"); + $expected = " WHERE SUM(`Post`.`comments_count`) > 500"; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions("(Post.created < '" . date('Y-m-d H:i:s') . "') GROUP BY YEAR(Post.created), MONTH(Post.created)"); + $expected = " WHERE (`Post`.`created` < '" . date('Y-m-d H:i:s') . "') GROUP BY YEAR(`Post`.`created`), MONTH(`Post`.`created`)"; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions("score BETWEEN 90.1 AND 95.7"); + $expected = " WHERE score BETWEEN 90.1 AND 95.7"; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions(array('score' => array(2 => 1, 2, 10))); + $expected = " WHERE score IN (1, 2, 10)"; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions("Aro.rght = Aro.lft + 1.1"); + $expected = " WHERE `Aro`.`rght` = `Aro`.`lft` + 1.1"; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions("(Post.created < '" . date('Y-m-d H:i:s') . "') GROUP BY YEAR(Post.created), MONTH(Post.created)"); + $expected = " WHERE (`Post`.`created` < '" . date('Y-m-d H:i:s') . "') GROUP BY YEAR(`Post`.`created`), MONTH(`Post`.`created`)"; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions('Sportstaette.sportstaette LIKE "%ru%" AND Sportstaette.sportstaettenart_id = 2'); + $expected = ' WHERE `Sportstaette`.`sportstaette` LIKE "%ru%" AND `Sportstaette`.`sportstaettenart_id` = 2'; + $this->assertRegExp('/\s*WHERE\s+`Sportstaette`\.`sportstaette`\s+LIKE\s+"%ru%"\s+AND\s+`Sports/', $result); + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions('Sportstaette.sportstaettenart_id = 2 AND Sportstaette.sportstaette LIKE "%ru%"'); + $expected = ' WHERE `Sportstaette`.`sportstaettenart_id` = 2 AND `Sportstaette`.`sportstaette` LIKE "%ru%"'; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions('SUM(Post.comments_count) > 500 AND NOT Post.title IS NULL AND NOT Post.extended_title IS NULL'); + $expected = ' WHERE SUM(`Post`.`comments_count`) > 500 AND NOT `Post`.`title` IS NULL AND NOT `Post`.`extended_title` IS NULL'; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions('NOT Post.title IS NULL AND NOT Post.extended_title IS NULL AND SUM(Post.comments_count) > 500'); + $expected = ' WHERE NOT `Post`.`title` IS NULL AND NOT `Post`.`extended_title` IS NULL AND SUM(`Post`.`comments_count`) > 500'; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions('NOT Post.extended_title IS NULL AND NOT Post.title IS NULL AND Post.title != "" AND SPOON(SUM(Post.comments_count) + 1.1) > 500'); + $expected = ' WHERE NOT `Post`.`extended_title` IS NULL AND NOT `Post`.`title` IS NULL AND `Post`.`title` != "" AND SPOON(SUM(`Post`.`comments_count`) + 1.1) > 500'; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions('NOT Post.title_extended IS NULL AND NOT Post.title IS NULL AND Post.title_extended != Post.title'); + $expected = ' WHERE NOT `Post`.`title_extended` IS NULL AND NOT `Post`.`title` IS NULL AND `Post`.`title_extended` != `Post`.`title`'; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions("Comment.id = 'a'"); + $expected = " WHERE `Comment`.`id` = 'a'"; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions("lower(Article.title) LIKE 'a%'"); + $expected = " WHERE lower(`Article`.`title`) LIKE 'a%'"; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions('((MATCH(Video.title) AGAINST(\'My Search*\' IN BOOLEAN MODE) * 2) + (MATCH(Video.description) AGAINST(\'My Search*\' IN BOOLEAN MODE) * 0.4) + (MATCH(Video.tags) AGAINST(\'My Search*\' IN BOOLEAN MODE) * 1.5))'); + $expected = ' WHERE ((MATCH(`Video`.`title`) AGAINST(\'My Search*\' IN BOOLEAN MODE) * 2) + (MATCH(`Video`.`description`) AGAINST(\'My Search*\' IN BOOLEAN MODE) * 0.4) + (MATCH(`Video`.`tags`) AGAINST(\'My Search*\' IN BOOLEAN MODE) * 1.5))'; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions('DATEDIFF(NOW(),Article.published) < 1 && Article.live=1'); + $expected = " WHERE DATEDIFF(NOW(),`Article`.`published`) < 1 && `Article`.`live`=1"; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions('file = "index.html"'); + $expected = ' WHERE file = "index.html"'; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions("file = 'index.html'"); + $expected = " WHERE file = 'index.html'"; + $this->assertEquals($expected, $result); + + $letter = $letter = 'd.a'; + $conditions = array('Company.name like ' => $letter . '%'); + $result = $this->Dbo->conditions($conditions); + $expected = " WHERE `Company`.`name` like 'd.a%'"; + $this->assertEquals($expected, $result); + + $conditions = array('Artist.name' => 'JUDY and MARY'); + $result = $this->Dbo->conditions($conditions); + $expected = " WHERE `Artist`.`name` = 'JUDY and MARY'"; + $this->assertEquals($expected, $result); + + $conditions = array('Artist.name' => 'JUDY AND MARY'); + $result = $this->Dbo->conditions($conditions); + $expected = " WHERE `Artist`.`name` = 'JUDY AND MARY'"; + $this->assertEquals($expected, $result); + + $conditions = array('Company.name similar to ' => 'a word'); + $result = $this->Dbo->conditions($conditions); + $expected = " WHERE `Company`.`name` similar to 'a word'"; + $this->assertEquals($expected, $result); + } + +/** + * testQuotesInStringConditions method + * + * @return void + */ + public function testQuotesInStringConditions() { + $result = $this->Dbo->conditions('Member.email = \'mariano@cricava.com\''); + $expected = ' WHERE `Member`.`email` = \'mariano@cricava.com\''; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions('Member.email = "mariano@cricava.com"'); + $expected = ' WHERE `Member`.`email` = "mariano@cricava.com"'; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions('Member.email = \'mariano@cricava.com\' AND Member.user LIKE \'mariano.iglesias%\''); + $expected = ' WHERE `Member`.`email` = \'mariano@cricava.com\' AND `Member`.`user` LIKE \'mariano.iglesias%\''; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions('Member.email = "mariano@cricava.com" AND Member.user LIKE "mariano.iglesias%"'); + $expected = ' WHERE `Member`.`email` = "mariano@cricava.com" AND `Member`.`user` LIKE "mariano.iglesias%"'; + $this->assertEquals($expected, $result); + } + +/** + * testParenthesisInStringConditions method + * + * @return void + */ + public function testParenthesisInStringConditions() { + $result = $this->Dbo->conditions('Member.name = \'(lu\''); + $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\(lu\'$/', $result); + + $result = $this->Dbo->conditions('Member.name = \')lu\''); + $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\)lu\'$/', $result); + + $result = $this->Dbo->conditions('Member.name = \'va(lu\''); + $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'va\(lu\'$/', $result); + + $result = $this->Dbo->conditions('Member.name = \'va)lu\''); + $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'va\)lu\'$/', $result); + + $result = $this->Dbo->conditions('Member.name = \'va(lu)\''); + $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'va\(lu\)\'$/', $result); + + $result = $this->Dbo->conditions('Member.name = \'va(lu)e\''); + $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'va\(lu\)e\'$/', $result); + + $result = $this->Dbo->conditions('Member.name = \'(mariano)\''); + $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\(mariano\)\'$/', $result); + + $result = $this->Dbo->conditions('Member.name = \'(mariano)iglesias\''); + $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\(mariano\)iglesias\'$/', $result); + + $result = $this->Dbo->conditions('Member.name = \'(mariano) iglesias\''); + $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\(mariano\) iglesias\'$/', $result); + + $result = $this->Dbo->conditions('Member.name = \'(mariano word) iglesias\''); + $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\(mariano word\) iglesias\'$/', $result); + + $result = $this->Dbo->conditions('Member.name = \'(mariano.iglesias)\''); + $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\(mariano.iglesias\)\'$/', $result); + + $result = $this->Dbo->conditions('Member.name = \'Mariano Iglesias (mariano.iglesias)\''); + $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'Mariano Iglesias \(mariano.iglesias\)\'$/', $result); + + $result = $this->Dbo->conditions('Member.name = \'Mariano Iglesias (mariano.iglesias) CakePHP\''); + $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'Mariano Iglesias \(mariano.iglesias\) CakePHP\'$/', $result); + + $result = $this->Dbo->conditions('Member.name = \'(mariano.iglesias) CakePHP\''); + $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\(mariano.iglesias\) CakePHP\'$/', $result); + } + +/** + * testParenthesisInArrayConditions method + * + * @return void + */ + public function testParenthesisInArrayConditions() { + $result = $this->Dbo->conditions(array('Member.name' => '(lu')); + $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\(lu\'$/', $result); + + $result = $this->Dbo->conditions(array('Member.name' => ')lu')); + $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\)lu\'$/', $result); + + $result = $this->Dbo->conditions(array('Member.name' => 'va(lu')); + $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'va\(lu\'$/', $result); + + $result = $this->Dbo->conditions(array('Member.name' => 'va)lu')); + $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'va\)lu\'$/', $result); + + $result = $this->Dbo->conditions(array('Member.name' => 'va(lu)')); + $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'va\(lu\)\'$/', $result); + + $result = $this->Dbo->conditions(array('Member.name' => 'va(lu)e')); + $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'va\(lu\)e\'$/', $result); + + $result = $this->Dbo->conditions(array('Member.name' => '(mariano)')); + $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\(mariano\)\'$/', $result); + + $result = $this->Dbo->conditions(array('Member.name' => '(mariano)iglesias')); + $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\(mariano\)iglesias\'$/', $result); + + $result = $this->Dbo->conditions(array('Member.name' => '(mariano) iglesias')); + $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\(mariano\) iglesias\'$/', $result); + + $result = $this->Dbo->conditions(array('Member.name' => '(mariano word) iglesias')); + $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\(mariano word\) iglesias\'$/', $result); + + $result = $this->Dbo->conditions(array('Member.name' => '(mariano.iglesias)')); + $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\(mariano.iglesias\)\'$/', $result); + + $result = $this->Dbo->conditions(array('Member.name' => 'Mariano Iglesias (mariano.iglesias)')); + $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'Mariano Iglesias \(mariano.iglesias\)\'$/', $result); + + $result = $this->Dbo->conditions(array('Member.name' => 'Mariano Iglesias (mariano.iglesias) CakePHP')); + $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'Mariano Iglesias \(mariano.iglesias\) CakePHP\'$/', $result); + + $result = $this->Dbo->conditions(array('Member.name' => '(mariano.iglesias) CakePHP')); + $this->assertRegExp('/^\s+WHERE\s+`Member`.`name`\s+=\s+\'\(mariano.iglesias\) CakePHP\'$/', $result); + } + +/** + * testArrayConditionsParsing method + * + * @return void + */ + public function testArrayConditionsParsing() { + $this->loadFixtures('Post', 'Author'); + $result = $this->Dbo->conditions(array('Stereo.type' => 'in dash speakers')); + $this->assertRegExp("/^\s+WHERE\s+`Stereo`.`type`\s+=\s+'in dash speakers'/", $result); + + $result = $this->Dbo->conditions(array('Candy.name LIKE' => 'a', 'HardCandy.name LIKE' => 'c')); + $this->assertRegExp("/^\s+WHERE\s+`Candy`.`name` LIKE\s+'a'\s+AND\s+`HardCandy`.`name`\s+LIKE\s+'c'/", $result); + + $result = $this->Dbo->conditions(array('HardCandy.name LIKE' => 'a', 'Candy.name LIKE' => 'c')); + $expected = " WHERE `HardCandy`.`name` LIKE 'a' AND `Candy`.`name` LIKE 'c'"; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions(array('HardCandy.name LIKE' => 'a%', 'Candy.name LIKE' => '%c%')); + $expected = " WHERE `HardCandy`.`name` LIKE 'a%' AND `Candy`.`name` LIKE '%c%'"; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions(array('HardCandy.name LIKE' => 'to be or%', 'Candy.name LIKE' => '%not to be%')); + $expected = " WHERE `HardCandy`.`name` LIKE 'to be or%' AND `Candy`.`name` LIKE '%not to be%'"; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions(array('score BETWEEN ? AND ?' => array(90.1, 95.7))); + $expected = " WHERE `score` BETWEEN 90.1 AND 95.7"; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions(array('Post.title' => 1.1)); + $expected = " WHERE `Post`.`title` = 1.1"; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions(array('Post.title' => 1.1), true, true, new Post()); + $expected = " WHERE `Post`.`title` = '1.1'"; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions(array('SUM(Post.comments_count) >' => '500')); + $expected = " WHERE SUM(`Post`.`comments_count`) > '500'"; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions(array('MAX(Post.rating) >' => '50')); + $expected = " WHERE MAX(`Post`.`rating`) > '50'"; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions(array('lower(Article.title)' => 'secrets')); + $expected = " WHERE lower(`Article`.`title`) = 'secrets'"; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions(array('title LIKE' => '%hello')); + $expected = " WHERE `title` LIKE '%hello'"; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions(array('Post.name' => 'mad(g)ik')); + $expected = " WHERE `Post`.`name` = 'mad(g)ik'"; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions(array('score' => array(1, 2, 10))); + $expected = " WHERE score IN (1, 2, 10)"; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions(array('score' => array())); + $expected = " WHERE `score` IS NULL"; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions(array('score !=' => array())); + $expected = " WHERE `score` IS NOT NULL"; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions(array('score !=' => '20')); + $expected = " WHERE `score` != '20'"; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions(array('score >' => '20')); + $expected = " WHERE `score` > '20'"; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions(array('client_id >' => '20'), true, true, new TestModel()); + $expected = " WHERE `client_id` > 20"; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions(array('OR' => array( + array('User.user' => 'mariano'), + array('User.user' => 'nate') + ))); + + $expected = " WHERE ((`User`.`user` = 'mariano') OR (`User`.`user` = 'nate'))"; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions(array('or' => array( + 'score BETWEEN ? AND ?' => array('4', '5'), 'rating >' => '20' + ))); + $expected = " WHERE ((`score` BETWEEN '4' AND '5') OR (`rating` > '20'))"; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions(array('or' => array( + 'score BETWEEN ? AND ?' => array('4', '5'), array('score >' => '20') + ))); + $expected = " WHERE ((`score` BETWEEN '4' AND '5') OR (`score` > '20'))"; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions(array('and' => array( + 'score BETWEEN ? AND ?' => array('4', '5'), array('score >' => '20') + ))); + $expected = " WHERE ((`score` BETWEEN '4' AND '5') AND (`score` > '20'))"; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions(array( + 'published' => 1, 'or' => array('score >' => '2', array('score >' => '20')) + )); + $expected = " WHERE `published` = 1 AND ((`score` > '2') OR (`score` > '20'))"; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions(array(array('Project.removed' => false))); + $expected = " WHERE `Project`.`removed` = '0'"; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions(array(array('Project.removed' => true))); + $expected = " WHERE `Project`.`removed` = '1'"; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions(array(array('Project.removed' => null))); + $expected = " WHERE `Project`.`removed` IS NULL"; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions(array(array('Project.removed !=' => null))); + $expected = " WHERE `Project`.`removed` IS NOT NULL"; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions(array('(Usergroup.permissions) & 4' => 4)); + $expected = " WHERE (`Usergroup`.`permissions`) & 4 = 4"; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions(array('((Usergroup.permissions) & 4)' => 4)); + $expected = " WHERE ((`Usergroup`.`permissions`) & 4) = 4"; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions(array('Post.modified >=' => 'DATE_SUB(NOW(), INTERVAL 7 DAY)')); + $expected = " WHERE `Post`.`modified` >= 'DATE_SUB(NOW(), INTERVAL 7 DAY)'"; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions(array('Post.modified >= DATE_SUB(NOW(), INTERVAL 7 DAY)')); + $expected = " WHERE `Post`.`modified` >= DATE_SUB(NOW(), INTERVAL 7 DAY)"; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions(array( + 'NOT' => array('Course.id' => null, 'Course.vet' => 'N', 'level_of_education_id' => array(912,999)), + 'Enrollment.yearcompleted >' => '0') + ); + $this->assertRegExp('/^\s*WHERE\s+\(NOT\s+\(`Course`\.`id` IS NULL\)\s+AND NOT\s+\(`Course`\.`vet`\s+=\s+\'N\'\)\s+AND NOT\s+\(level_of_education_id IN \(912, 999\)\)\)\s+AND\s+`Enrollment`\.`yearcompleted`\s+>\s+\'0\'\s*$/', $result); + + $result = $this->Dbo->conditions(array('id <>' => '8')); + $this->assertRegExp('/^\s*WHERE\s+`id`\s+<>\s+\'8\'\s*$/', $result); + + $result = $this->Dbo->conditions(array('TestModel.field =' => 'gribe$@()lu')); + $expected = " WHERE `TestModel`.`field` = 'gribe$@()lu'"; + $this->assertEquals($expected, $result); + + $conditions['NOT'] = array('Listing.expiration BETWEEN ? AND ?' => array("1", "100")); + $conditions[0]['OR'] = array( + "Listing.title LIKE" => "%term%", + "Listing.description LIKE" => "%term%" + ); + $conditions[1]['OR'] = array( + "Listing.title LIKE" => "%term_2%", + "Listing.description LIKE" => "%term_2%" + ); + $result = $this->Dbo->conditions($conditions); + $expected = " WHERE NOT (`Listing`.`expiration` BETWEEN '1' AND '100') AND" . + " ((`Listing`.`title` LIKE '%term%') OR (`Listing`.`description` LIKE '%term%')) AND" . + " ((`Listing`.`title` LIKE '%term_2%') OR (`Listing`.`description` LIKE '%term_2%'))"; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions(array('MD5(CONCAT(Reg.email,Reg.id))' => 'blah')); + $expected = " WHERE MD5(CONCAT(`Reg`.`email`,`Reg`.`id`)) = 'blah'"; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions(array( + 'MD5(CONCAT(Reg.email,Reg.id))' => array('blah', 'blahblah') + )); + $expected = " WHERE MD5(CONCAT(`Reg`.`email`,`Reg`.`id`)) IN ('blah', 'blahblah')"; + $this->assertEquals($expected, $result); + + $conditions = array('id' => array(2, 5, 6, 9, 12, 45, 78, 43, 76)); + $result = $this->Dbo->conditions($conditions); + $expected = " WHERE id IN (2, 5, 6, 9, 12, 45, 78, 43, 76)"; + $this->assertEquals($expected, $result); + + $conditions = array('title' => 'user(s)'); + $result = $this->Dbo->conditions($conditions); + $expected = " WHERE `title` = 'user(s)'"; + $this->assertEquals($expected, $result); + + $conditions = array('title' => 'user(s) data'); + $result = $this->Dbo->conditions($conditions); + $expected = " WHERE `title` = 'user(s) data'"; + $this->assertEquals($expected, $result); + + $conditions = array('title' => 'user(s,arg) data'); + $result = $this->Dbo->conditions($conditions); + $expected = " WHERE `title` = 'user(s,arg) data'"; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions(array("Book.book_name" => 'Java(TM)')); + $expected = " WHERE `Book`.`book_name` = 'Java(TM)'"; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions(array("Book.book_name" => 'Java(TM) ')); + $expected = " WHERE `Book`.`book_name` = 'Java(TM) '"; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions(array("Book.id" => 0)); + $expected = " WHERE `Book`.`id` = 0"; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions(array("Book.id" => null)); + $expected = " WHERE `Book`.`id` IS NULL"; + $this->assertEquals($expected, $result); + + $conditions = array('MysqlModel.id' => ''); + $result = $this->Dbo->conditions($conditions, true, true, $this->model); + $expected = " WHERE `MysqlModel`.`id` IS NULL"; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions(array('Listing.beds >=' => 0)); + $expected = " WHERE `Listing`.`beds` >= 0"; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions(array( + 'ASCII(SUBSTRING(keyword, 1, 1)) BETWEEN ? AND ?' => array(65, 90) + )); + $expected = ' WHERE ASCII(SUBSTRING(keyword, 1, 1)) BETWEEN 65 AND 90'; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions(array('or' => array( + '? BETWEEN Model.field1 AND Model.field2' => '2009-03-04' + ))); + $expected = " WHERE '2009-03-04' BETWEEN Model.field1 AND Model.field2"; + $this->assertEquals($expected, $result); + } + +/** + * testArrayConditionsParsingComplexKeys method + * + * @return void + */ + public function testArrayConditionsParsingComplexKeys() { + $result = $this->Dbo->conditions(array( + 'CAST(Book.created AS DATE)' => '2008-08-02' + )); + $expected = " WHERE CAST(`Book`.`created` AS DATE) = '2008-08-02'"; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions(array( + 'CAST(Book.created AS DATE) <=' => '2008-08-02' + )); + $expected = " WHERE CAST(`Book`.`created` AS DATE) <= '2008-08-02'"; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions(array( + '(Stats.clicks * 100) / Stats.views >' => 50 + )); + $expected = " WHERE (`Stats`.`clicks` * 100) / `Stats`.`views` > 50"; + $this->assertEquals($expected, $result); + } + +/** + * testMixedConditionsParsing method + * + * @return void + */ + public function testMixedConditionsParsing() { + $conditions[] = 'User.first_name = \'Firstname\''; + $conditions[] = array('User.last_name' => 'Lastname'); + $result = $this->Dbo->conditions($conditions); + $expected = " WHERE `User`.`first_name` = 'Firstname' AND `User`.`last_name` = 'Lastname'"; + $this->assertEquals($expected, $result); + + $conditions = array( + 'Thread.project_id' => 5, + 'Thread.buyer_id' => 14, + '1=1 GROUP BY Thread.project_id' + ); + $result = $this->Dbo->conditions($conditions); + $this->assertRegExp('/^\s*WHERE\s+`Thread`.`project_id`\s*=\s*5\s+AND\s+`Thread`.`buyer_id`\s*=\s*14\s+AND\s+1\s*=\s*1\s+GROUP BY `Thread`.`project_id`$/', $result); + } + +/** + * testConditionsOptionalArguments method + * + * @return void + */ + public function testConditionsOptionalArguments() { + $result = $this->Dbo->conditions(array('Member.name' => 'Mariano'), true, false); + $this->assertRegExp('/^\s*`Member`.`name`\s*=\s*\'Mariano\'\s*$/', $result); + + $result = $this->Dbo->conditions(array(), true, false); + $this->assertRegExp('/^\s*1\s*=\s*1\s*$/', $result); + } + +/** + * testConditionsWithModel + * + * @return void + */ + public function testConditionsWithModel() { + $this->Model = new Article2(); + + $result = $this->Dbo->conditions(array('Article2.viewed >=' => 0), true, true, $this->Model); + $expected = " WHERE `Article2`.`viewed` >= 0"; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions(array('Article2.viewed >=' => '0'), true, true, $this->Model); + $expected = " WHERE `Article2`.`viewed` >= 0"; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions(array('Article2.viewed >=' => '1'), true, true, $this->Model); + $expected = " WHERE `Article2`.`viewed` >= 1"; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions(array('Article2.rate_sum BETWEEN ? AND ?' => array(0, 10)), true, true, $this->Model); + $expected = " WHERE `Article2`.`rate_sum` BETWEEN 0 AND 10"; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions(array('Article2.rate_sum BETWEEN ? AND ?' => array('0', '10')), true, true, $this->Model); + $expected = " WHERE `Article2`.`rate_sum` BETWEEN 0 AND 10"; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->conditions(array('Article2.rate_sum BETWEEN ? AND ?' => array('1', '10')), true, true, $this->Model); + $expected = " WHERE `Article2`.`rate_sum` BETWEEN 1 AND 10"; + $this->assertEquals($expected, $result); + } + +/** + * testFieldParsing method + * + * @return void + */ + public function testFieldParsing() { + $this->Model = new TestModel(); + $result = $this->Dbo->fields($this->Model, 'Vendor', "Vendor.id, COUNT(Model.vendor_id) AS `Vendor`.`count`"); + $expected = array('`Vendor`.`id`', 'COUNT(`Model`.`vendor_id`) AS `Vendor`.`count`'); + $this->assertEquals($expected, $result); + + $result = $this->Dbo->fields($this->Model, 'Vendor', "`Vendor`.`id`, COUNT(`Model`.`vendor_id`) AS `Vendor`.`count`"); + $expected = array('`Vendor`.`id`', 'COUNT(`Model`.`vendor_id`) AS `Vendor`.`count`'); + $this->assertEquals($expected, $result); + + $result = $this->Dbo->fields($this->Model, 'Post', "CONCAT(REPEAT(' ', COUNT(Parent.name) - 1), Node.name) AS name, Node.created"); + $expected = array("CONCAT(REPEAT(' ', COUNT(`Parent`.`name`) - 1), Node.name) AS name", "`Node`.`created`"); + $this->assertEquals($expected, $result); + + $result = $this->Dbo->fields($this->Model, null, 'round( (3.55441 * fooField), 3 ) AS test'); + $this->assertEquals(array('round( (3.55441 * fooField), 3 ) AS test'), $result); + + $result = $this->Dbo->fields($this->Model, null, 'ROUND(`Rating`.`rate_total` / `Rating`.`rate_count`,2) AS rating'); + $this->assertEquals(array('ROUND(`Rating`.`rate_total` / `Rating`.`rate_count`,2) AS rating'), $result); + + $result = $this->Dbo->fields($this->Model, null, 'ROUND(Rating.rate_total / Rating.rate_count,2) AS rating'); + $this->assertEquals(array('ROUND(Rating.rate_total / Rating.rate_count,2) AS rating'), $result); + + $result = $this->Dbo->fields($this->Model, 'Post', "Node.created, CONCAT(REPEAT(' ', COUNT(Parent.name) - 1), Node.name) AS name"); + $expected = array("`Node`.`created`", "CONCAT(REPEAT(' ', COUNT(`Parent`.`name`) - 1), Node.name) AS name"); + $this->assertEquals($expected, $result); + + $result = $this->Dbo->fields($this->Model, 'Post', "2.2,COUNT(*), SUM(Something.else) as sum, Node.created, CONCAT(REPEAT(' ', COUNT(Parent.name) - 1), Node.name) AS name,Post.title,Post.1,1.1"); + $expected = array( + '2.2', 'COUNT(*)', 'SUM(`Something`.`else`) as sum', '`Node`.`created`', + "CONCAT(REPEAT(' ', COUNT(`Parent`.`name`) - 1), Node.name) AS name", '`Post`.`title`', '`Post`.`1`', '1.1' + ); + $this->assertEquals($expected, $result); + + $result = $this->Dbo->fields($this->Model, null, "(`Provider`.`star_total` / `Provider`.`total_ratings`) as `rating`"); + $expected = array("(`Provider`.`star_total` / `Provider`.`total_ratings`) as `rating`"); + $this->assertEquals($expected, $result); + + $result = $this->Dbo->fields($this->Model, 'Post'); + $expected = array( + '`Post`.`id`', '`Post`.`client_id`', '`Post`.`name`', '`Post`.`login`', + '`Post`.`passwd`', '`Post`.`addr_1`', '`Post`.`addr_2`', '`Post`.`zip_code`', + '`Post`.`city`', '`Post`.`country`', '`Post`.`phone`', '`Post`.`fax`', + '`Post`.`url`', '`Post`.`email`', '`Post`.`comments`', '`Post`.`last_login`', + '`Post`.`created`', '`Post`.`updated`' + ); + $this->assertEquals($expected, $result); + + $result = $this->Dbo->fields($this->Model, 'Other'); + $expected = array( + '`Other`.`id`', '`Other`.`client_id`', '`Other`.`name`', '`Other`.`login`', + '`Other`.`passwd`', '`Other`.`addr_1`', '`Other`.`addr_2`', '`Other`.`zip_code`', + '`Other`.`city`', '`Other`.`country`', '`Other`.`phone`', '`Other`.`fax`', + '`Other`.`url`', '`Other`.`email`', '`Other`.`comments`', '`Other`.`last_login`', + '`Other`.`created`', '`Other`.`updated`' + ); + $this->assertEquals($expected, $result); + + $result = $this->Dbo->fields($this->Model, null, array(), false); + $expected = array('id', 'client_id', 'name', 'login', 'passwd', 'addr_1', 'addr_2', 'zip_code', 'city', 'country', 'phone', 'fax', 'url', 'email', 'comments', 'last_login', 'created', 'updated'); + $this->assertEquals($expected, $result); + + $result = $this->Dbo->fields($this->Model, null, 'COUNT(*)'); + $expected = array('COUNT(*)'); + $this->assertEquals($expected, $result); + + $result = $this->Dbo->fields($this->Model, null, 'SUM(Thread.unread_buyer) AS ' . $this->Dbo->name('sum_unread_buyer')); + $expected = array('SUM(`Thread`.`unread_buyer`) AS `sum_unread_buyer`'); + $this->assertEquals($expected, $result); + + $result = $this->Dbo->fields($this->Model, null, 'name, count(*)'); + $expected = array('`TestModel`.`name`', 'count(*)'); + $this->assertEquals($expected, $result); + + $result = $this->Dbo->fields($this->Model, null, 'count(*), name'); + $expected = array('count(*)', '`TestModel`.`name`'); + $this->assertEquals($expected, $result); + + $result = $this->Dbo->fields( + $this->Model, null, 'field1, field2, field3, count(*), name' + ); + $expected = array( + '`TestModel`.`field1`', '`TestModel`.`field2`', + '`TestModel`.`field3`', 'count(*)', '`TestModel`.`name`' + ); + $this->assertEquals($expected, $result); + + $result = $this->Dbo->fields($this->Model, null, array('dayofyear(now())')); + $expected = array('dayofyear(now())'); + $this->assertEquals($expected, $result); + + $result = $this->Dbo->fields($this->Model, null, array('MAX(Model.field) As Max')); + $expected = array('MAX(`Model`.`field`) As Max'); + $this->assertEquals($expected, $result); + + $result = $this->Dbo->fields($this->Model, null, array('Model.field AS AnotherName')); + $expected = array('`Model`.`field` AS `AnotherName`'); + $this->assertEquals($expected, $result); + + $result = $this->Dbo->fields($this->Model, null, array('field AS AnotherName')); + $expected = array('`field` AS `AnotherName`'); + $this->assertEquals($expected, $result); + + $result = $this->Dbo->fields($this->Model, null, array( + 'TestModel.field AS AnotherName' + )); + $expected = array('`TestModel`.`field` AS `AnotherName`'); + $this->assertEquals($expected, $result); + + $result = $this->Dbo->fields($this->Model, 'Foo', array( + 'id', 'title', '(user_count + discussion_count + post_count) AS score' + )); + $expected = array( + '`Foo`.`id`', + '`Foo`.`title`', + '(user_count + discussion_count + post_count) AS score' + ); + $this->assertEquals($expected, $result); + } + +/** + * test that fields() will accept objects made from DboSource::expression + * + * @return void + */ + public function testFieldsWithExpression() { + $this->Model = new TestModel; + $expression = $this->Dbo->expression("CASE Sample.id WHEN 1 THEN 'Id One' ELSE 'Other Id' END AS case_col"); + $result = $this->Dbo->fields($this->Model, null, array("id", $expression)); + $expected = array( + '`TestModel`.`id`', + "CASE Sample.id WHEN 1 THEN 'Id One' ELSE 'Other Id' END AS case_col" + ); + $this->assertEquals($expected, $result); + } + +/** + * testRenderStatement method + * + * @return void + */ + public function testRenderStatement() { + $result = $this->Dbo->renderStatement('select', array( + 'fields' => 'id', 'table' => 'table', 'conditions' => 'WHERE 1=1', + 'alias' => '', 'joins' => '', 'order' => '', 'limit' => '', 'group' => '' + )); + $this->assertRegExp('/^\s*SELECT\s+id\s+FROM\s+table\s+WHERE\s+1=1\s*$/', $result); + + $result = $this->Dbo->renderStatement('update', array('fields' => 'value=2', 'table' => 'table', 'conditions' => 'WHERE 1=1', 'alias' => '')); + $this->assertRegExp('/^\s*UPDATE\s+table\s+SET\s+value=2\s+WHERE\s+1=1\s*$/', $result); + + $result = $this->Dbo->renderStatement('update', array('fields' => 'value=2', 'table' => 'table', 'conditions' => 'WHERE 1=1', 'alias' => 'alias', 'joins' => '')); + $this->assertRegExp('/^\s*UPDATE\s+table\s+AS\s+alias\s+SET\s+value=2\s+WHERE\s+1=1\s*$/', $result); + + $result = $this->Dbo->renderStatement('delete', array('fields' => 'value=2', 'table' => 'table', 'conditions' => 'WHERE 1=1', 'alias' => '')); + $this->assertRegExp('/^\s*DELETE\s+FROM\s+table\s+WHERE\s+1=1\s*$/', $result); + + $result = $this->Dbo->renderStatement('delete', array('fields' => 'value=2', 'table' => 'table', 'conditions' => 'WHERE 1=1', 'alias' => 'alias', 'joins' => '')); + $this->assertRegExp('/^\s*DELETE\s+alias\s+FROM\s+table\s+AS\s+alias\s+WHERE\s+1=1\s*$/', $result); + } + +/** + * testSchema method + * + * @return void + */ + public function testSchema() { + $Schema = new CakeSchema(); + $Schema->tables = array('table' => array(), 'anotherTable' => array()); + + $result = $this->Dbo->dropSchema($Schema, 'non_existing'); + $this->assertTrue(empty($result)); + + $result = $this->Dbo->dropSchema($Schema, 'table'); + $this->assertRegExp('/^\s*DROP TABLE IF EXISTS\s+' . $this->Dbo->fullTableName('table') . ';\s*$/s', $result); + } + +/** + * testDropSchemaNoSchema method + * + * @expectedException PHPUnit_Framework_Error + * @return void + */ + public function testDropSchemaNoSchema() { + $result = $this->Dbo->dropSchema(null); + } + +/** + * testOrderParsing method + * + * @return void + */ + public function testOrderParsing() { + $result = $this->Dbo->order("ADDTIME(Event.time_begin, '-06:00:00') ASC"); + $expected = " ORDER BY ADDTIME(`Event`.`time_begin`, '-06:00:00') ASC"; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->order("title, id"); + $this->assertRegExp('/^\s*ORDER BY\s+`title`\s+ASC,\s+`id`\s+ASC\s*$/', $result); + + $result = $this->Dbo->order("title desc, id desc"); + $this->assertRegExp('/^\s*ORDER BY\s+`title`\s+desc,\s+`id`\s+desc\s*$/', $result); + + $result = $this->Dbo->order(array("title desc, id desc")); + $this->assertRegExp('/^\s*ORDER BY\s+`title`\s+desc,\s+`id`\s+desc\s*$/', $result); + + $result = $this->Dbo->order(array("title", "id")); + $this->assertRegExp('/^\s*ORDER BY\s+`title`\s+ASC,\s+`id`\s+ASC\s*$/', $result); + + $result = $this->Dbo->order(array(array('title'), array('id'))); + $this->assertRegExp('/^\s*ORDER BY\s+`title`\s+ASC,\s+`id`\s+ASC\s*$/', $result); + + $result = $this->Dbo->order(array("Post.title" => 'asc', "Post.id" => 'desc')); + $this->assertRegExp('/^\s*ORDER BY\s+`Post`.`title`\s+asc,\s+`Post`.`id`\s+desc\s*$/', $result); + + $result = $this->Dbo->order(array(array("Post.title" => 'asc', "Post.id" => 'desc'))); + $this->assertRegExp('/^\s*ORDER BY\s+`Post`.`title`\s+asc,\s+`Post`.`id`\s+desc\s*$/', $result); + + $result = $this->Dbo->order(array("title")); + $this->assertRegExp('/^\s*ORDER BY\s+`title`\s+ASC\s*$/', $result); + + $result = $this->Dbo->order(array(array("title"))); + $this->assertRegExp('/^\s*ORDER BY\s+`title`\s+ASC\s*$/', $result); + + $result = $this->Dbo->order("Dealer.id = 7 desc, Dealer.id = 3 desc, Dealer.title asc"); + $expected = " ORDER BY `Dealer`.`id` = 7 desc, `Dealer`.`id` = 3 desc, `Dealer`.`title` asc"; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->order(array("Page.name" => "='test' DESC")); + $this->assertRegExp("/^\s*ORDER BY\s+`Page`\.`name`\s*='test'\s+DESC\s*$/", $result); + + $result = $this->Dbo->order("Page.name = 'view' DESC"); + $this->assertRegExp("/^\s*ORDER BY\s+`Page`\.`name`\s*=\s*'view'\s+DESC\s*$/", $result); + + $result = $this->Dbo->order("(Post.views)"); + $this->assertRegExp("/^\s*ORDER BY\s+\(`Post`\.`views`\)\s+ASC\s*$/", $result); + + $result = $this->Dbo->order("(Post.views)*Post.views"); + $this->assertRegExp("/^\s*ORDER BY\s+\(`Post`\.`views`\)\*`Post`\.`views`\s+ASC\s*$/", $result); + + $result = $this->Dbo->order("(Post.views) * Post.views"); + $this->assertRegExp("/^\s*ORDER BY\s+\(`Post`\.`views`\) \* `Post`\.`views`\s+ASC\s*$/", $result); + + $result = $this->Dbo->order("(Model.field1 + Model.field2) * Model.field3"); + $this->assertRegExp("/^\s*ORDER BY\s+\(`Model`\.`field1` \+ `Model`\.`field2`\) \* `Model`\.`field3`\s+ASC\s*$/", $result); + + $result = $this->Dbo->order("Model.name+0 ASC"); + $this->assertRegExp("/^\s*ORDER BY\s+`Model`\.`name`\+0\s+ASC\s*$/", $result); + + $result = $this->Dbo->order("Anuncio.destaque & 2 DESC"); + $expected = ' ORDER BY `Anuncio`.`destaque` & 2 DESC'; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->order("3963.191 * id"); + $expected = ' ORDER BY 3963.191 * id ASC'; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->order(array('Property.sale_price IS NULL')); + $expected = ' ORDER BY `Property`.`sale_price` IS NULL ASC'; + $this->assertEquals($expected, $result); + } + +/** + * testComplexSortExpression method + * + * @return void + */ + public function testComplexSortExpression() { + $result = $this->Dbo->order(array('(Model.field > 100) DESC', 'Model.field ASC')); + $this->assertRegExp("/^\s*ORDER BY\s+\(`Model`\.`field`\s+>\s+100\)\s+DESC,\s+`Model`\.`field`\s+ASC\s*$/", $result); + } + +/** + * testCalculations method + * + * @return void + */ + public function testCalculations() { + $this->Model = new TestModel(); + $result = $this->Dbo->calculate($this->Model, 'count'); + $this->assertEquals('COUNT(*) AS `count`', $result); + + $result = $this->Dbo->calculate($this->Model, 'count', array('id')); + $this->assertEquals('COUNT(`id`) AS `count`', $result); + + $result = $this->Dbo->calculate( + $this->Model, + 'count', + array($this->Dbo->expression('DISTINCT id')) + ); + $this->assertEquals('COUNT(DISTINCT id) AS `count`', $result); + + $result = $this->Dbo->calculate($this->Model, 'count', array('id', 'id_count')); + $this->assertEquals('COUNT(`id`) AS `id_count`', $result); + + $result = $this->Dbo->calculate($this->Model, 'count', array('Model.id', 'id_count')); + $this->assertEquals('COUNT(`Model`.`id`) AS `id_count`', $result); + + $result = $this->Dbo->calculate($this->Model, 'max', array('id')); + $this->assertEquals('MAX(`id`) AS `id`', $result); + + $result = $this->Dbo->calculate($this->Model, 'max', array('Model.id', 'id')); + $this->assertEquals('MAX(`Model`.`id`) AS `id`', $result); + + $result = $this->Dbo->calculate($this->Model, 'max', array('`Model`.`id`', 'id')); + $this->assertEquals('MAX(`Model`.`id`) AS `id`', $result); + + $result = $this->Dbo->calculate($this->Model, 'min', array('`Model`.`id`', 'id')); + $this->assertEquals('MIN(`Model`.`id`) AS `id`', $result); + + $result = $this->Dbo->calculate($this->Model, 'min', 'left'); + $this->assertEquals('MIN(`left`) AS `left`', $result); + } + +/** + * testLength method + * + * @return void + */ + public function testLength() { + $result = $this->Dbo->length('varchar(255)'); + $expected = 255; + $this->assertSame($expected, $result); + + $result = $this->Dbo->length('int(11)'); + $expected = 11; + $this->assertSame($expected, $result); + + $result = $this->Dbo->length('float(5,3)'); + $expected = '5,3'; + $this->assertSame($expected, $result); + + $result = $this->Dbo->length('decimal(5,2)'); + $expected = '5,2'; + $this->assertSame($expected, $result); + + $result = $this->Dbo->length("enum('test','me','now')"); + $expected = 4; + $this->assertSame($expected, $result); + + $result = $this->Dbo->length("set('a','b','cd')"); + $expected = 2; + $this->assertSame($expected, $result); + + $result = $this->Dbo->length(false); + $this->assertTrue($result === null); + + $result = $this->Dbo->length('datetime'); + $expected = null; + $this->assertSame($expected, $result); + + $result = $this->Dbo->length('text'); + $expected = null; + $this->assertSame($expected, $result); + } + +/** + * testBuildIndex method + * + * @return void + */ + public function testBuildIndex() { + $data = array( + 'PRIMARY' => array('column' => 'id') + ); + $result = $this->Dbo->buildIndex($data); + $expected = array('PRIMARY KEY (`id`)'); + $this->assertSame($expected, $result); + + $data = array( + 'MyIndex' => array('column' => 'id', 'unique' => true) + ); + $result = $this->Dbo->buildIndex($data); + $expected = array('UNIQUE KEY `MyIndex` (`id`)'); + $this->assertEquals($expected, $result); + + $data = array( + 'MyIndex' => array('column' => array('id', 'name'), 'unique' => true) + ); + $result = $this->Dbo->buildIndex($data); + $expected = array('UNIQUE KEY `MyIndex` (`id`, `name`)'); + $this->assertEquals($expected, $result); + } + +/** + * testBuildColumn method + * + * @return void + */ + public function testBuildColumn2() { + $data = array( + 'name' => 'testName', + 'type' => 'string', + 'length' => 255, + 'default', + 'null' => true, + 'key' + ); + $result = $this->Dbo->buildColumn($data); + $expected = '`testName` varchar(255) DEFAULT NULL'; + $this->assertEquals($expected, $result); + + $data = array( + 'name' => 'int_field', + 'type' => 'integer', + 'default' => '', + 'null' => false, + ); + $restore = $this->Dbo->columns; + + $this->Dbo->columns = array('integer' => array('name' => 'int', 'limit' => '11', 'formatter' => 'intval'), ); + $result = $this->Dbo->buildColumn($data); + $expected = '`int_field` int(11) NOT NULL'; + $this->assertEquals($expected, $result); + + $this->Dbo->fieldParameters['param'] = array( + 'value' => 'COLLATE', + 'quote' => false, + 'join' => ' ', + 'column' => 'Collate', + 'position' => 'beforeDefault', + 'options' => array('GOOD', 'OK') + ); + $data = array( + 'name' => 'int_field', + 'type' => 'integer', + 'default' => '', + 'null' => false, + 'param' => 'BAD' + ); + $result = $this->Dbo->buildColumn($data); + $expected = '`int_field` int(11) NOT NULL'; + $this->assertEquals($expected, $result); + + $data = array( + 'name' => 'int_field', + 'type' => 'integer', + 'default' => '', + 'null' => false, + 'param' => 'GOOD' + ); + $result = $this->Dbo->buildColumn($data); + $expected = '`int_field` int(11) COLLATE GOOD NOT NULL'; + $this->assertEquals($expected, $result); + + $this->Dbo->columns = $restore; + + $data = array( + 'name' => 'created', + 'type' => 'timestamp', + 'default' => 'current_timestamp', + 'null' => false, + ); + $result = $this->Dbo->buildColumn($data); + $expected = '`created` timestamp DEFAULT CURRENT_TIMESTAMP NOT NULL'; + $this->assertEquals($expected, $result); + + $data = array( + 'name' => 'created', + 'type' => 'timestamp', + 'default' => 'CURRENT_TIMESTAMP', + 'null' => true, + ); + $result = $this->Dbo->buildColumn($data); + $expected = '`created` timestamp DEFAULT CURRENT_TIMESTAMP'; + $this->assertEquals($expected, $result); + + $data = array( + 'name' => 'modified', + 'type' => 'timestamp', + 'null' => true, + ); + $result = $this->Dbo->buildColumn($data); + $expected = '`modified` timestamp NULL'; + $this->assertEquals($expected, $result); + + $data = array( + 'name' => 'modified', + 'type' => 'timestamp', + 'default' => null, + 'null' => true, + ); + $result = $this->Dbo->buildColumn($data); + $expected = '`modified` timestamp NULL'; + $this->assertEquals($expected, $result); + } + +/** + * testBuildColumnBadType method + * + * @expectedException PHPUnit_Framework_Error + * @return void + */ + public function testBuildColumnBadType() { + $data = array( + 'name' => 'testName', + 'type' => 'varchar(255)', + 'default', + 'null' => true, + 'key' + ); + $this->Dbo->buildColumn($data); + } + +/** + * test hasAny() + * + * @return void + */ + public function testHasAny() { + $db = $this->Dbo->config['database']; + $this->Dbo = $this->getMock('Mysql', array('connect', '_execute', 'execute', 'value')); + $this->Dbo->config['database'] = $db; + + $this->Model = $this->getMock('TestModel', array('getDataSource')); + $this->Model->expects($this->any()) + ->method('getDataSource') + ->will($this->returnValue($this->Dbo)); + + $this->Dbo->expects($this->at(0))->method('value') + ->with('harry') + ->will($this->returnValue("'harry'")); + + $modelTable = $this->Dbo->fullTableName($this->Model); + $this->Dbo->expects($this->at(1))->method('execute') + ->with('SELECT COUNT(`TestModel`.`id`) AS count FROM ' . $modelTable . ' AS `TestModel` WHERE `TestModel`.`name` = \'harry\''); + $this->Dbo->expects($this->at(2))->method('execute') + ->with('SELECT COUNT(`TestModel`.`id`) AS count FROM ' . $modelTable . ' AS `TestModel` WHERE 1 = 1'); + + $this->Dbo->hasAny($this->Model, array('TestModel.name' => 'harry')); + $this->Dbo->hasAny($this->Model, array()); + } + +/** + * test fields generating usable virtual fields to use in query + * + * @return void + */ + public function testVirtualFields() { + $this->loadFixtures('Article', 'Comment', 'Tag'); + $this->Dbo->virtualFieldSeparator = '__'; + $Article = ClassRegistry::init('Article'); + $commentsTable = $this->Dbo->fullTableName('comments', false, false); + $Article->virtualFields = array( + 'this_moment' => 'NOW()', + 'two' => '1 + 1', + 'comment_count' => 'SELECT COUNT(*) FROM ' . $commentsTable . + ' WHERE Article.id = ' . $commentsTable . '.article_id' + ); + $result = $this->Dbo->fields($Article); + $expected = array( + '`Article`.`id`', + '`Article`.`user_id`', + '`Article`.`title`', + '`Article`.`body`', + '`Article`.`published`', + '`Article`.`created`', + '`Article`.`updated`', + '(NOW()) AS `Article__this_moment`', + '(1 + 1) AS `Article__two`', + "(SELECT COUNT(*) FROM $commentsTable WHERE `Article`.`id` = `$commentsTable`.`article_id`) AS `Article__comment_count`" + ); + + $this->assertEquals($expected, $result); + + $result = $this->Dbo->fields($Article, null, array('this_moment', 'title')); + $expected = array( + '`Article`.`title`', + '(NOW()) AS `Article__this_moment`', + ); + $this->assertEquals($expected, $result); + + $result = $this->Dbo->fields($Article, null, array('Article.title', 'Article.this_moment')); + $expected = array( + '`Article`.`title`', + '(NOW()) AS `Article__this_moment`', + ); + $this->assertEquals($expected, $result); + + $result = $this->Dbo->fields($Article, null, array('Article.this_moment', 'Article.title')); + $expected = array( + '`Article`.`title`', + '(NOW()) AS `Article__this_moment`', + ); + $this->assertEquals($expected, $result); + + $result = $this->Dbo->fields($Article, null, array('Article.*')); + $expected = array( + '`Article`.*', + '(NOW()) AS `Article__this_moment`', + '(1 + 1) AS `Article__two`', + "(SELECT COUNT(*) FROM $commentsTable WHERE `Article`.`id` = `$commentsTable`.`article_id`) AS `Article__comment_count`" + ); + $this->assertEquals($expected, $result); + + $result = $this->Dbo->fields($Article, null, array('*')); + $expected = array( + '*', + '(NOW()) AS `Article__this_moment`', + '(1 + 1) AS `Article__two`', + "(SELECT COUNT(*) FROM $commentsTable WHERE `Article`.`id` = `$commentsTable`.`article_id`) AS `Article__comment_count`" + ); + $this->assertEquals($expected, $result); + } + +/** + * test conditions to generate query conditions for virtual fields + * + * @return void + */ + public function testVirtualFieldsInConditions() { + $Article = ClassRegistry::init('Article'); + $commentsTable = $this->Dbo->fullTableName('comments', false, false); + + $Article->virtualFields = array( + 'this_moment' => 'NOW()', + 'two' => '1 + 1', + 'comment_count' => 'SELECT COUNT(*) FROM ' . $commentsTable . + ' WHERE Article.id = ' . $commentsTable . '.article_id' + ); + $conditions = array('two' => 2); + $result = $this->Dbo->conditions($conditions, true, false, $Article); + $expected = '(1 + 1) = 2'; + $this->assertEquals($expected, $result); + + $conditions = array('this_moment BETWEEN ? AND ?' => array(1,2)); + $expected = 'NOW() BETWEEN 1 AND 2'; + $result = $this->Dbo->conditions($conditions, true, false, $Article); + $this->assertEquals($expected, $result); + + $conditions = array('comment_count >' => 5); + $expected = "(SELECT COUNT(*) FROM $commentsTable WHERE `Article`.`id` = `$commentsTable`.`article_id`) > 5"; + $result = $this->Dbo->conditions($conditions, true, false, $Article); + $this->assertEquals($expected, $result); + + $conditions = array('NOT' => array('two' => 2)); + $result = $this->Dbo->conditions($conditions, true, false, $Article); + $expected = 'NOT ((1 + 1) = 2)'; + $this->assertEquals($expected, $result); + } + +/** + * test that virtualFields with complex functions and aliases work. + * + * @return void + */ + public function testConditionsWithComplexVirtualFields() { + $Article = ClassRegistry::init('Article', 'Comment', 'Tag'); + $Article->virtualFields = array( + 'distance' => 'ACOS(SIN(20 * PI() / 180) + * SIN(Article.latitude * PI() / 180) + + COS(20 * PI() / 180) + * COS(Article.latitude * PI() / 180) + * COS((50 - Article.longitude) * PI() / 180) + ) * 180 / PI() * 60 * 1.1515 * 1.609344' + ); + $conditions = array('distance >=' => 20); + $result = $this->Dbo->conditions($conditions, true, true, $Article); + + $this->assertRegExp('/\) >= 20/', $result); + $this->assertRegExp('/[`\'"]Article[`\'"].[`\'"]latitude[`\'"]/', $result); + $this->assertRegExp('/[`\'"]Article[`\'"].[`\'"]longitude[`\'"]/', $result); + } + +/** + * test calculate to generate claculate statements on virtual fields + * + * @return void + */ + public function testVirtualFieldsInCalculate() { + $Article = ClassRegistry::init('Article'); + $commentsTable = $this->Dbo->fullTableName('comments', false, false); + $Article->virtualFields = array( + 'this_moment' => 'NOW()', + 'two' => '1 + 1', + 'comment_count' => 'SELECT COUNT(*) FROM ' . $commentsTable . + ' WHERE Article.id = ' . $commentsTable . '.article_id' + ); + + $result = $this->Dbo->calculate($Article, 'count', array('this_moment')); + $expected = 'COUNT(NOW()) AS `count`'; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->calculate($Article, 'max', array('comment_count')); + $expected = "MAX(SELECT COUNT(*) FROM $commentsTable WHERE `Article`.`id` = `$commentsTable`.`article_id`) AS `comment_count`"; + $this->assertEquals($expected, $result); + } + +/** + * test reading virtual fields containing newlines when recursive > 0 + * + * @return void + */ + public function testReadVirtualFieldsWithNewLines() { + $Article = new Article(); + $Article->recursive = 1; + $Article->virtualFields = array( + 'test' => ' + User.id + User.id + ' + ); + $result = $this->Dbo->fields($Article, null, array()); + $result = $this->Dbo->fields($Article, $Article->alias, $result); + $this->assertRegExp('/[`\"]User[`\"]\.[`\"]id[`\"] \+ [`\"]User[`\"]\.[`\"]id[`\"]/', $result[7]); + } + +/** + * test group to generate GROUP BY statements on virtual fields + * + * @return void + */ + public function testVirtualFieldsInGroup() { + $Article = ClassRegistry::init('Article'); + $Article->virtualFields = array( + 'this_year' => 'YEAR(Article.created)' + ); + + $result = $this->Dbo->group('this_year', $Article); + + $expected = " GROUP BY (YEAR(`Article`.`created`))"; + $this->assertEquals($expected, $result); + } + +/** + * test that virtualFields with complex functions and aliases work. + * + * @return void + */ + public function testFieldsWithComplexVirtualFields() { + $Article = new Article(); + $Article->virtualFields = array( + 'distance' => 'ACOS(SIN(20 * PI() / 180) + * SIN(Article.latitude * PI() / 180) + + COS(20 * PI() / 180) + * COS(Article.latitude * PI() / 180) + * COS((50 - Article.longitude) * PI() / 180) + ) * 180 / PI() * 60 * 1.1515 * 1.609344' + ); + + $fields = array('id', 'distance'); + $result = $this->Dbo->fields($Article, null, $fields); + $qs = $this->Dbo->startQuote; + $qe = $this->Dbo->endQuote; + + $this->assertEquals("{$qs}Article{$qe}.{$qs}id{$qe}", $result[0]); + $this->assertRegExp('/Article__distance/', $result[1]); + $this->assertRegExp('/[`\'"]Article[`\'"].[`\'"]latitude[`\'"]/', $result[1]); + $this->assertRegExp('/[`\'"]Article[`\'"].[`\'"]longitude[`\'"]/', $result[1]); + } + +/** + * test that execute runs queries. + * + * @return void + */ + public function testExecute() { + $query = 'SELECT * FROM ' . $this->Dbo->fullTableName('articles') . ' WHERE 1 = 1'; + $this->Dbo->took = null; + $this->Dbo->affected = null; + $result = $this->Dbo->execute($query, array('log' => false)); + $this->assertNotNull($result, 'No query performed! %s'); + $this->assertNull($this->Dbo->took, 'Stats were set %s'); + $this->assertNull($this->Dbo->affected, 'Stats were set %s'); + + $result = $this->Dbo->execute($query); + $this->assertNotNull($result, 'No query performed! %s'); + $this->assertNotNull($this->Dbo->took, 'Stats were not set %s'); + $this->assertNotNull($this->Dbo->affected, 'Stats were not set %s'); + } + +/** + * test a full example of using virtual fields + * + * @return void + */ + public function testVirtualFieldsFetch() { + $this->loadFixtures('Article', 'Comment'); + + $Article = ClassRegistry::init('Article'); + $Article->virtualFields = array( + 'comment_count' => 'SELECT COUNT(*) FROM ' . $this->Dbo->fullTableName('comments') . + ' WHERE Article.id = ' . $this->Dbo->fullTableName('comments') . '.article_id' + ); + + $conditions = array('comment_count >' => 2); + $query = 'SELECT ' . join(',', $this->Dbo->fields($Article, null, array('id', 'comment_count'))) . + ' FROM ' . $this->Dbo->fullTableName($Article) . ' Article ' . $this->Dbo->conditions($conditions, true, true, $Article); + $result = $this->Dbo->fetchAll($query); + $expected = array(array( + 'Article' => array('id' => 1, 'comment_count' => 4) + )); + $this->assertEquals($expected, $result); + } + +/** + * test reading complex virtualFields with subqueries. + * + * @return void + */ + public function testVirtualFieldsComplexRead() { + $this->loadFixtures('DataTest', 'Article', 'Comment', 'User', 'Tag', 'ArticlesTag'); + + $Article = ClassRegistry::init('Article'); + $commentTable = $this->Dbo->fullTableName('comments'); + $Article = ClassRegistry::init('Article'); + $Article->virtualFields = array( + 'comment_count' => 'SELECT COUNT(*) FROM ' . $commentTable . + ' AS Comment WHERE Article.id = Comment.article_id' + ); + $result = $Article->find('all'); + $this->assertTrue(count($result) > 0); + $this->assertTrue($result[0]['Article']['comment_count'] > 0); + + $DataTest = ClassRegistry::init('DataTest'); + $DataTest->virtualFields = array( + 'complicated' => 'ACOS(SIN(20 * PI() / 180) + * SIN(DataTest.float * PI() / 180) + + COS(20 * PI() / 180) + * COS(DataTest.count * PI() / 180) + * COS((50 - DataTest.float) * PI() / 180) + ) * 180 / PI() * 60 * 1.1515 * 1.609344' + ); + $result = $DataTest->find('all'); + $this->assertTrue(count($result) > 0); + $this->assertTrue($result[0]['DataTest']['complicated'] > 0); + } + +/** + * testIntrospectType method + * + * @return void + */ + public function testIntrospectType() { + $this->assertEquals('integer', $this->Dbo->introspectType(0)); + $this->assertEquals('integer', $this->Dbo->introspectType(2)); + $this->assertEquals('string', $this->Dbo->introspectType('2')); + $this->assertEquals('string', $this->Dbo->introspectType('2.2')); + $this->assertEquals('float', $this->Dbo->introspectType(2.2)); + $this->assertEquals('string', $this->Dbo->introspectType('stringme')); + $this->assertEquals('string', $this->Dbo->introspectType('0stringme')); + + $data = array(2.2); + $this->assertEquals('float', $this->Dbo->introspectType($data)); + + $data = array('2.2'); + $this->assertEquals('float', $this->Dbo->introspectType($data)); + + $data = array(2); + $this->assertEquals('integer', $this->Dbo->introspectType($data)); + + $data = array('2'); + $this->assertEquals('integer', $this->Dbo->introspectType($data)); + + $data = array('string'); + $this->assertEquals('string', $this->Dbo->introspectType($data)); + + $data = array(2.2, '2.2'); + $this->assertEquals('float', $this->Dbo->introspectType($data)); + + $data = array(2, '2'); + $this->assertEquals('integer', $this->Dbo->introspectType($data)); + + $data = array('string one', 'string two'); + $this->assertEquals('string', $this->Dbo->introspectType($data)); + + $data = array('2.2', 3); + $this->assertEquals('integer', $this->Dbo->introspectType($data)); + + $data = array('2.2', '0stringme'); + $this->assertEquals('string', $this->Dbo->introspectType($data)); + + $data = array(2.2, 3); + $this->assertEquals('integer', $this->Dbo->introspectType($data)); + + $data = array(2.2, '0stringme'); + $this->assertEquals('string', $this->Dbo->introspectType($data)); + + $data = array(2, 'stringme'); + $this->assertEquals('string', $this->Dbo->introspectType($data)); + + $data = array(2, '2.2', 'stringgme'); + $this->assertEquals('string', $this->Dbo->introspectType($data)); + + $data = array(2, '2.2'); + $this->assertEquals('integer', $this->Dbo->introspectType($data)); + + $data = array(2, 2.2); + $this->assertEquals('integer', $this->Dbo->introspectType($data)); + + // null + $result = $this->Dbo->value(null, 'boolean'); + $this->assertEquals('NULL', $result); + + // EMPTY STRING + $result = $this->Dbo->value('', 'boolean'); + $this->assertEquals("'0'", $result); + + // BOOLEAN + $result = $this->Dbo->value('true', 'boolean'); + $this->assertEquals("'1'", $result); + + $result = $this->Dbo->value('false', 'boolean'); + $this->assertEquals("'1'", $result); + + $result = $this->Dbo->value(true, 'boolean'); + $this->assertEquals("'1'", $result); + + $result = $this->Dbo->value(false, 'boolean'); + $this->assertEquals("'0'", $result); + + $result = $this->Dbo->value(1, 'boolean'); + $this->assertEquals("'1'", $result); + + $result = $this->Dbo->value(0, 'boolean'); + $this->assertEquals("'0'", $result); + + $result = $this->Dbo->value('abc', 'boolean'); + $this->assertEquals("'1'", $result); + + $result = $this->Dbo->value(1.234, 'boolean'); + $this->assertEquals("'1'", $result); + + $result = $this->Dbo->value('1.234e05', 'boolean'); + $this->assertEquals("'1'", $result); + + // NUMBERS + $result = $this->Dbo->value(123, 'integer'); + $this->assertEquals(123, $result); + + $result = $this->Dbo->value('123', 'integer'); + $this->assertEquals('123', $result); + + $result = $this->Dbo->value('0123', 'integer'); + $this->assertEquals("'0123'", $result); + + $result = $this->Dbo->value('0x123ABC', 'integer'); + $this->assertEquals("'0x123ABC'", $result); + + $result = $this->Dbo->value('0x123', 'integer'); + $this->assertEquals("'0x123'", $result); + + $result = $this->Dbo->value(1.234, 'float'); + $this->assertEquals(1.234, $result); + + $result = $this->Dbo->value('1.234', 'float'); + $this->assertEquals('1.234', $result); + + $result = $this->Dbo->value(' 1.234 ', 'float'); + $this->assertEquals("' 1.234 '", $result); + + $result = $this->Dbo->value('1.234e05', 'float'); + $this->assertEquals("'1.234e05'", $result); + + $result = $this->Dbo->value('1.234e+5', 'float'); + $this->assertEquals("'1.234e+5'", $result); + + $result = $this->Dbo->value('1,234', 'float'); + $this->assertEquals("'1,234'", $result); + + $result = $this->Dbo->value('FFF', 'integer'); + $this->assertEquals("'FFF'", $result); + + $result = $this->Dbo->value('abc', 'integer'); + $this->assertEquals("'abc'", $result); + + // STRINGS + $result = $this->Dbo->value('123', 'string'); + $this->assertEquals("'123'", $result); + + $result = $this->Dbo->value(123, 'string'); + $this->assertEquals("'123'", $result); + + $result = $this->Dbo->value(1.234, 'string'); + $this->assertEquals("'1.234'", $result); + + $result = $this->Dbo->value('abc', 'string'); + $this->assertEquals("'abc'", $result); + + $result = $this->Dbo->value(' abc ', 'string'); + $this->assertEquals("' abc '", $result); + + $result = $this->Dbo->value('a bc', 'string'); + $this->assertEquals("'a bc'", $result); + } + +/** + * testRealQueries method + * + * @return void + */ + public function testRealQueries() { + $this->loadFixtures('Apple', 'Article', 'User', 'Comment', 'Tag', 'Sample', 'ArticlesTag'); + + $Apple = ClassRegistry::init('Apple'); + $Article = ClassRegistry::init('Article'); + + $result = $this->Dbo->rawQuery('SELECT color, name FROM ' . $this->Dbo->fullTableName('apples')); + $this->assertTrue(!empty($result)); + + $result = $this->Dbo->fetchRow($result); + $expected = array($this->Dbo->fullTableName('apples', false, false) => array( + 'color' => 'Red 1', + 'name' => 'Red Apple 1' + )); + $this->assertEquals($expected, $result); + + $result = $this->Dbo->fetchAll('SELECT name FROM ' . $this->Dbo->fullTableName('apples') . ' ORDER BY id'); + $expected = array( + array($this->Dbo->fullTableName('apples', false, false) => array('name' => 'Red Apple 1')), + array($this->Dbo->fullTableName('apples', false, false) => array('name' => 'Bright Red Apple')), + array($this->Dbo->fullTableName('apples', false, false) => array('name' => 'green blue')), + array($this->Dbo->fullTableName('apples', false, false) => array('name' => 'Test Name')), + array($this->Dbo->fullTableName('apples', false, false) => array('name' => 'Blue Green')), + array($this->Dbo->fullTableName('apples', false, false) => array('name' => 'My new apple')), + array($this->Dbo->fullTableName('apples', false, false) => array('name' => 'Some odd color')) + ); + $this->assertEquals($expected, $result); + + $result = $this->Dbo->field($this->Dbo->fullTableName('apples', false, false), 'SELECT color, name FROM ' . $this->Dbo->fullTableName('apples') . ' ORDER BY id'); + $expected = array( + 'color' => 'Red 1', + 'name' => 'Red Apple 1' + ); + $this->assertEquals($expected, $result); + + $Apple->unbindModel(array(), false); + $result = $this->Dbo->read($Apple, array( + 'fields' => array($Apple->escapeField('name')), + 'conditions' => null, + 'recursive' => -1 + )); + $expected = array( + array('Apple' => array('name' => 'Red Apple 1')), + array('Apple' => array('name' => 'Bright Red Apple')), + array('Apple' => array('name' => 'green blue')), + array('Apple' => array('name' => 'Test Name')), + array('Apple' => array('name' => 'Blue Green')), + array('Apple' => array('name' => 'My new apple')), + array('Apple' => array('name' => 'Some odd color')) + ); + $this->assertEquals($expected, $result); + + $result = $this->Dbo->read($Article, array( + 'fields' => array('id', 'user_id', 'title'), + 'conditions' => null, + 'recursive' => 1 + )); + + $this->assertTrue(Set::matches('/Article[id=1]', $result)); + $this->assertTrue(Set::matches('/Comment[id=1]', $result)); + $this->assertTrue(Set::matches('/Comment[id=2]', $result)); + $this->assertFalse(Set::matches('/Comment[id=10]', $result)); + } + +/** + * @expectedException MissingConnectionException + * @return void + */ + public function testExceptionOnBrokenConnection() { + $dbo = new Mysql(array( + 'driver' => 'mysql', + 'host' => 'imaginary_host', + 'login' => 'mark', + 'password' => 'inyurdatabase', + 'database' => 'imaginary' + )); + } + +/** + * testStatements method + * + * @return void + */ + public function testUpdateStatements() { + $this->loadFixtures('Article', 'User'); + $test = ConnectionManager::getDatasource('test'); + $db = $test->config['database']; + + $this->Dbo = $this->getMock('Mysql', array('execute'), array($test->config)); + + $this->Dbo->expects($this->at(0))->method('execute') + ->with("UPDATE `$db`.`articles` SET `field1` = 'value1' WHERE 1 = 1"); + + $this->Dbo->expects($this->at(1))->method('execute') + ->with("UPDATE `$db`.`articles` AS `Article` LEFT JOIN `$db`.`users` AS `User` ON " . + "(`Article`.`user_id` = `User`.`id`)" . + " SET `Article`.`field1` = 2 WHERE 2=2"); + + $this->Dbo->expects($this->at(2))->method('execute') + ->with("UPDATE `$db`.`articles` AS `Article` LEFT JOIN `$db`.`users` AS `User` ON " . + "(`Article`.`user_id` = `User`.`id`)" . + " SET `Article`.`field1` = 'value' WHERE `index` = 'val'"); + + $Article = new Article(); + + $this->Dbo->update($Article, array('field1'), array('value1')); + $this->Dbo->update($Article, array('field1'), array('2'), '2=2'); + $this->Dbo->update($Article, array('field1'), array("'value'"), array('index' => 'val')); + } + +/** + * Test deletes with a mock. + * + * @return void + */ + public function testDeleteStatements() { + $this->loadFixtures('Article', 'User'); + $test = ConnectionManager::getDatasource('test'); + $db = $test->config['database']; + + $this->Dbo = $this->getMock('Mysql', array('execute'), array($test->config)); + + $this->Dbo->expects($this->at(0))->method('execute') + ->with("DELETE FROM `$db`.`articles` WHERE 1 = 1"); + + $this->Dbo->expects($this->at(1))->method('execute') + ->with("DELETE `Article` FROM `$db`.`articles` AS `Article` LEFT JOIN `$db`.`users` AS `User` " . + "ON (`Article`.`user_id` = `User`.`id`)" . + " WHERE 1 = 1"); + + $this->Dbo->expects($this->at(2))->method('execute') + ->with("DELETE `Article` FROM `$db`.`articles` AS `Article` LEFT JOIN `$db`.`users` AS `User` " . + "ON (`Article`.`user_id` = `User`.`id`)" . + " WHERE 2=2"); + $Article = new Article(); + + $this->Dbo->delete($Article); + $this->Dbo->delete($Article, true); + $this->Dbo->delete($Article, '2=2'); + } + +/** + * Test truncate with a mock. + * + * @return void + */ + public function testTruncateStatements() { + $this->loadFixtures('Article', 'User'); + $db = ConnectionManager::getDatasource('test'); + $schema = $db->config['database']; + $Article = new Article(); + + $this->Dbo = $this->getMock('Mysql', array('execute'), array($db->config)); + + $this->Dbo->expects($this->at(0))->method('execute') + ->with("TRUNCATE TABLE `$schema`.`articles`"); + $this->Dbo->truncate($Article); + + $this->Dbo->expects($this->at(0))->method('execute') + ->with("TRUNCATE TABLE `$schema`.`articles`"); + $this->Dbo->truncate('articles'); + + // #2355: prevent duplicate prefix + $this->Dbo->config['prefix'] = 'tbl_'; + $Article->tablePrefix = 'tbl_'; + $this->Dbo->expects($this->at(0))->method('execute') + ->with("TRUNCATE TABLE `$schema`.`tbl_articles`"); + $this->Dbo->truncate($Article); + + $this->Dbo->expects($this->at(0))->method('execute') + ->with("TRUNCATE TABLE `$schema`.`tbl_articles`"); + $this->Dbo->truncate('articles'); + } + +/** + * Test nested transaction + * + * @return void + */ + public function testNestedTransaction() { + $nested = $this->Dbo->useNestedTransactions; + $this->Dbo->useNestedTransactions = true; + if ($this->Dbo->nestedTransactionSupported() === false) { + $this->Dbo->useNestedTransactions = $nested; + $this->skipIf(true, 'The MySQL server do not support nested transaction'); + } + + $this->loadFixtures('Inno'); + $model = ClassRegistry::init('Inno'); + $model->hasOne = $model->hasMany = $model->belongsTo = $model->hasAndBelongsToMany = array(); + $model->cacheQueries = false; + $this->Dbo->cacheMethods = false; + + $this->assertTrue($this->Dbo->begin()); + $this->assertNotEmpty($model->read(null, 1)); + + $this->assertTrue($this->Dbo->begin()); + $this->assertTrue($model->delete(1)); + $this->assertEmpty($model->read(null, 1)); + $this->assertTrue($this->Dbo->rollback()); + $this->assertNotEmpty($model->read(null, 1)); + + $this->assertTrue($this->Dbo->begin()); + $this->assertTrue($model->delete(1)); + $this->assertEmpty($model->read(null, 1)); + $this->assertTrue($this->Dbo->commit()); + $this->assertEmpty($model->read(null, 1)); + + $this->assertTrue($this->Dbo->rollback()); + $this->assertNotEmpty($model->read(null, 1)); + + $this->Dbo->useNestedTransactions = $nested; + } + +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Datasource/Database/PostgresTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Datasource/Database/PostgresTest.php new file mode 100644 index 0000000..2046e6b --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Datasource/Database/PostgresTest.php @@ -0,0 +1,945 @@ +simulated[] = $sql; + return null; + } + +/** + * getLastQuery method + * + * @return void + */ + public function getLastQuery() { + return $this->simulated[count($this->simulated) - 1]; + } + +} + +/** + * PostgresTestModel class + * + * @package Cake.Test.Case.Model.Datasource.Database + */ +class PostgresTestModel extends Model { + +/** + * name property + * + * @var string 'PostgresTestModel' + */ + public $name = 'PostgresTestModel'; + +/** + * useTable property + * + * @var bool false + */ + public $useTable = false; + +/** + * belongsTo property + * + * @var array + */ + public $belongsTo = array( + 'PostgresClientTestModel' => array( + 'foreignKey' => 'client_id' + ) + ); + +/** + * find method + * + * @param mixed $conditions + * @param mixed $fields + * @param mixed $order + * @param mixed $recursive + * @return void + */ + public function find($conditions = null, $fields = null, $order = null, $recursive = null) { + return $conditions; + } + +/** + * findAll method + * + * @param mixed $conditions + * @param mixed $fields + * @param mixed $order + * @param mixed $recursive + * @return void + */ + public function findAll($conditions = null, $fields = null, $order = null, $recursive = null) { + return $conditions; + } + +/** + * schema method + * + * @return void + */ + public function schema($field = false) { + return array( + 'id' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => '8'), + 'client_id' => array('type' => 'integer', 'null' => '', 'default' => '0', 'length' => '11'), + 'name' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'), + 'login' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'), + 'passwd' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '255'), + 'addr_1' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '255'), + 'addr_2' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '25'), + 'zip_code' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'), + 'city' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'), + 'country' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'), + 'phone' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'), + 'fax' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'), + 'url' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '255'), + 'email' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'), + 'comments' => array('type' => 'text', 'null' => '1', 'default' => '', 'length' => ''), + 'last_login' => array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => ''), + 'created' => array('type' => 'date', 'null' => '1', 'default' => '', 'length' => ''), + 'updated' => array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => null) + ); + } + +} + +/** + * PostgresClientTestModel class + * + * @package Cake.Test.Case.Model.Datasource.Database + */ +class PostgresClientTestModel extends Model { + +/** + * name property + * + * @var string 'PostgresClientTestModel' + */ + public $name = 'PostgresClientTestModel'; + +/** + * useTable property + * + * @var bool false + */ + public $useTable = false; + +/** + * schema method + * + * @return void + */ + public function schema($field = false) { + return array( + 'id' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => '8', 'key' => 'primary'), + 'name' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'), + 'email' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'), + 'created' => array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => ''), + 'updated' => array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => null) + ); + } + +} + +/** + * PostgresTest class + * + * @package Cake.Test.Case.Model.Datasource.Database + */ +class PostgresTest extends CakeTestCase { + +/** + * Do not automatically load fixtures for each test, they will be loaded manually + * using CakeTestCase::loadFixtures + * + * @var boolean + */ + public $autoFixtures = false; + +/** + * Fixtures + * + * @var object + */ + public $fixtures = array('core.user', 'core.binary_test', 'core.comment', 'core.article', + 'core.tag', 'core.articles_tag', 'core.attachment', 'core.person', 'core.post', 'core.author', + 'core.datatype', + ); + +/** + * Actual DB connection used in testing + * + * @var DboSource + */ + public $Dbo = null; + +/** + * Simulated DB connection used in testing + * + * @var DboSource + */ + public $Dbo2 = null; + +/** + * Sets up a Dbo class instance for testing + * + */ + public function setUp() { + Configure::write('Cache.disable', true); + $this->Dbo = ConnectionManager::getDataSource('test'); + $this->skipIf(!($this->Dbo instanceof Postgres)); + $this->Dbo2 = new DboPostgresTestDb($this->Dbo->config, false); + $this->model = new PostgresTestModel(); + } + +/** + * Sets up a Dbo class instance for testing + * + */ + public function tearDown() { + Configure::write('Cache.disable', false); + unset($this->Dbo2); + } + +/** + * Test field quoting method + * + */ + public function testFieldQuoting() { + $fields = array( + '"PostgresTestModel"."id" AS "PostgresTestModel__id"', + '"PostgresTestModel"."client_id" AS "PostgresTestModel__client_id"', + '"PostgresTestModel"."name" AS "PostgresTestModel__name"', + '"PostgresTestModel"."login" AS "PostgresTestModel__login"', + '"PostgresTestModel"."passwd" AS "PostgresTestModel__passwd"', + '"PostgresTestModel"."addr_1" AS "PostgresTestModel__addr_1"', + '"PostgresTestModel"."addr_2" AS "PostgresTestModel__addr_2"', + '"PostgresTestModel"."zip_code" AS "PostgresTestModel__zip_code"', + '"PostgresTestModel"."city" AS "PostgresTestModel__city"', + '"PostgresTestModel"."country" AS "PostgresTestModel__country"', + '"PostgresTestModel"."phone" AS "PostgresTestModel__phone"', + '"PostgresTestModel"."fax" AS "PostgresTestModel__fax"', + '"PostgresTestModel"."url" AS "PostgresTestModel__url"', + '"PostgresTestModel"."email" AS "PostgresTestModel__email"', + '"PostgresTestModel"."comments" AS "PostgresTestModel__comments"', + '"PostgresTestModel"."last_login" AS "PostgresTestModel__last_login"', + '"PostgresTestModel"."created" AS "PostgresTestModel__created"', + '"PostgresTestModel"."updated" AS "PostgresTestModel__updated"' + ); + + $result = $this->Dbo->fields($this->model); + $expected = $fields; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->fields($this->model, null, 'PostgresTestModel.*'); + $expected = $fields; + $this->assertEquals($expected, $result); + + $result = $this->Dbo->fields($this->model, null, array('*', 'AnotherModel.id', 'AnotherModel.name')); + $expected = array_merge($fields, array( + '"AnotherModel"."id" AS "AnotherModel__id"', + '"AnotherModel"."name" AS "AnotherModel__name"')); + $this->assertEquals($expected, $result); + + $result = $this->Dbo->fields($this->model, null, array('*', 'PostgresClientTestModel.*')); + $expected = array_merge($fields, array( + '"PostgresClientTestModel"."id" AS "PostgresClientTestModel__id"', + '"PostgresClientTestModel"."name" AS "PostgresClientTestModel__name"', + '"PostgresClientTestModel"."email" AS "PostgresClientTestModel__email"', + '"PostgresClientTestModel"."created" AS "PostgresClientTestModel__created"', + '"PostgresClientTestModel"."updated" AS "PostgresClientTestModel__updated"')); + $this->assertEquals($expected, $result); + } + +/** + * testColumnParsing method + * + * @return void + */ + public function testColumnParsing() { + $this->assertEquals('text', $this->Dbo2->column('text')); + $this->assertEquals('date', $this->Dbo2->column('date')); + $this->assertEquals('boolean', $this->Dbo2->column('boolean')); + $this->assertEquals('string', $this->Dbo2->column('character varying')); + $this->assertEquals('time', $this->Dbo2->column('time without time zone')); + $this->assertEquals('datetime', $this->Dbo2->column('timestamp without time zone')); + } + +/** + * testValueQuoting method + * + * @return void + */ + public function testValueQuoting() { + $this->assertEquals("1.200000", $this->Dbo->value(1.2, 'float')); + $this->assertEquals("'1,2'", $this->Dbo->value('1,2', 'float')); + + $this->assertEquals("0", $this->Dbo->value('0', 'integer')); + $this->assertEquals('NULL', $this->Dbo->value('', 'integer')); + $this->assertEquals('NULL', $this->Dbo->value('', 'float')); + $this->assertEquals("NULL", $this->Dbo->value('', 'integer', false)); + $this->assertEquals("NULL", $this->Dbo->value('', 'float', false)); + $this->assertEquals("'0.0'", $this->Dbo->value('0.0', 'float')); + + $this->assertEquals("'TRUE'", $this->Dbo->value('t', 'boolean')); + $this->assertEquals("'FALSE'", $this->Dbo->value('f', 'boolean')); + $this->assertEquals("'TRUE'", $this->Dbo->value(true)); + $this->assertEquals("'FALSE'", $this->Dbo->value(false)); + $this->assertEquals("'t'", $this->Dbo->value('t')); + $this->assertEquals("'f'", $this->Dbo->value('f')); + $this->assertEquals("'TRUE'", $this->Dbo->value('true', 'boolean')); + $this->assertEquals("'FALSE'", $this->Dbo->value('false', 'boolean')); + $this->assertEquals("'FALSE'", $this->Dbo->value('', 'boolean')); + $this->assertEquals("'FALSE'", $this->Dbo->value(0, 'boolean')); + $this->assertEquals("'TRUE'", $this->Dbo->value(1, 'boolean')); + $this->assertEquals("'TRUE'", $this->Dbo->value('1', 'boolean')); + $this->assertEquals("NULL", $this->Dbo->value(null, 'boolean')); + $this->assertEquals("NULL", $this->Dbo->value(array())); + } + +/** + * test that localized floats don't cause trouble. + * + * @return void + */ + public function testLocalizedFloats() { + $restore = setlocale(LC_NUMERIC, 0); + setlocale(LC_NUMERIC, 'de_DE'); + + $result = $this->db->value(3.141593, 'float'); + $this->assertEquals("3.141593", $result); + + $result = $this->db->value(3.14); + $this->assertEquals("3.140000", $result); + + setlocale(LC_NUMERIC, $restore); + } + +/** + * test that date and time columns do not generate errors with null and nullish values. + * + * @return void + */ + public function testDateAndTimeAsNull() { + $this->assertEquals('NULL', $this->Dbo->value(null, 'date')); + $this->assertEquals('NULL', $this->Dbo->value('', 'date')); + + $this->assertEquals('NULL', $this->Dbo->value('', 'datetime')); + $this->assertEquals('NULL', $this->Dbo->value(null, 'datetime')); + + $this->assertEquals('NULL', $this->Dbo->value('', 'timestamp')); + $this->assertEquals('NULL', $this->Dbo->value(null, 'timestamp')); + + $this->assertEquals('NULL', $this->Dbo->value('', 'time')); + $this->assertEquals('NULL', $this->Dbo->value(null, 'time')); + } + +/** + * Tests that different Postgres boolean 'flavors' are properly returned as native PHP booleans + * + * @return void + */ + public function testBooleanNormalization() { + $this->assertEquals(true, $this->Dbo2->boolean('t', false)); + $this->assertEquals(true, $this->Dbo2->boolean('true', false)); + $this->assertEquals(true, $this->Dbo2->boolean('TRUE', false)); + $this->assertEquals(true, $this->Dbo2->boolean(true, false)); + $this->assertEquals(true, $this->Dbo2->boolean(1, false)); + $this->assertEquals(true, $this->Dbo2->boolean(" ", false)); + + $this->assertEquals(false, $this->Dbo2->boolean('f', false)); + $this->assertEquals(false, $this->Dbo2->boolean('false', false)); + $this->assertEquals(false, $this->Dbo2->boolean('FALSE', false)); + $this->assertEquals(false, $this->Dbo2->boolean(false, false)); + $this->assertEquals(false, $this->Dbo2->boolean(0, false)); + $this->assertEquals(false, $this->Dbo2->boolean('', false)); + } + +/** + * test that default -> false in schemas works correctly. + * + * @return void + */ + public function testBooleanDefaultFalseInSchema() { + $this->loadFixtures('Datatype'); + + $model = new Model(array('name' => 'Datatype', 'table' => 'datatypes', 'ds' => 'test')); + $model->create(); + $this->assertSame(false, $model->data['Datatype']['bool']); + } + +/** + * testLastInsertIdMultipleInsert method + * + * @return void + */ + public function testLastInsertIdMultipleInsert() { + $this->loadFixtures('User'); + $db1 = ConnectionManager::getDataSource('test'); + + $table = $db1->fullTableName('users', false); + $password = '5f4dcc3b5aa765d61d8327deb882cf99'; + $db1->execute( + "INSERT INTO {$table} (\"user\", password) VALUES ('mariano', '{$password}')" + ); + + $this->assertEquals(5, $db1->lastInsertId($table)); + + $db1->execute("INSERT INTO {$table} (\"user\", password) VALUES ('hoge', '{$password}')"); + $this->assertEquals(6, $db1->lastInsertId($table)); + } + +/** + * Tests that column types without default lengths in $columns do not have length values + * applied when generating schemas. + * + * @return void + */ + public function testColumnUseLength() { + $result = array('name' => 'foo', 'type' => 'string', 'length' => 100, 'default' => 'FOO'); + $expected = '"foo" varchar(100) DEFAULT \'FOO\''; + $this->assertEquals($expected, $this->Dbo->buildColumn($result)); + + $result = array('name' => 'foo', 'type' => 'text', 'length' => 100, 'default' => 'FOO'); + $expected = '"foo" text DEFAULT \'FOO\''; + $this->assertEquals($expected, $this->Dbo->buildColumn($result)); + } + +/** + * Tests that binary data is escaped/unescaped properly on reads and writes + * + * @return void + */ + public function testBinaryDataIntegrity() { + $this->loadFixtures('BinaryTest'); + $data = '%PDF-1.3 + %ƒÂÚÂÎßÛ†–ƒ∆ + 4 0 obj + << /Length 5 0 R /Filter /FlateDecode >> + stream + xµYMì€∆Ω„WÃ%)nï0¯îâ-«é]Q"πXµáÿ•Ip - P V,]Ú#c˚ˇ‰ut¥†∏Ti9 Ü=”›Ø_˜4>à∑‚Épcé¢Pxæ®2q\' + 1UªbU ᡒ+ö«√[ıµ⁄ão"R∑"HiGæä€(å≠≈^Ãøsm?YlƒÃõªfi‹âEÚB&‚Î◊7bÒ^¸m°÷˛?2±Øs“fiu#®U√ˇú÷g¥C;ä")n})JºIÔ3ËSnÑÎ¥≤ıD∆¢∂Msx1üèG˚±Œ™⁄>¶ySïufØ ˝¸?UπÃã√6flÌÚC=øK?˝…s + ˛§¯ˇ:-˜ò7€ÓFæ∂∑Õ˛∆“V’>ılflëÅd«ÜQdI ›ÎB%W¿ΩıÉn~h vêCS>«é˛(ØôK!€¡zB!√ + [œÜ"ûß ·iH¸[Àºæ∑¯¡L,ÀÚAlS∫ˆ=∫Œ≤cÄr&ˆÈ:√ÿ£˚È«4fl•À]vc›bÅôÿî=siXe4/¡p]ã]ôÆIœ™ Ωflà_ƒ‚G?«7 ùÿ ı¯K4ïIpV◊÷·\'éµóªÚæ>î + ;›sú!2fl¬F•/f∑j£ + dw"IÊÜπ<ôÿˆ%IG1ytÛDflXg|Éòa§˜}C˛¿ÿe°G´Ú±jÍm~¿/∂hã<#-¥•ıùe87€t˜õ6w}´{æ + m‹ê– ∆¡ 6⁄\ + rAÀBùZ3aË‚r$G·$ó0Ñ üâUY4È™¡%C∑Ÿ2rcÍCäı + =Õec=ëR˝”eñ=ÊuNê°“√Ü ‹Ê9iÙ0˙AAEÍ ˙`∂£\'ûce•åƒX›ŸÁ´1SK{qdá"tÏ[wQ#SµBe∞∑µó…ÌV`B"Ñ≥„!è_Óφ-º*ºú¿Ë0ˆeê∂´ë+HFj…‡zvHÓN|ÔL÷ûñ3õÜ$z%sá…pÎóV38âs Çoµ•ß3†<9B·¨û~¢3)ÂxóÿÁCÕòÆ ∫Í=»ÿSπS;∆~±êÆTEp∑óÈ÷ÀuìDHÈ $ÉõæÜjû§"≤ÃONM®RËíRr{õS ∏Ê™op±W;ÂUÔ P∫kÔˇflTæ∑óflË” ÆC©Ô[≥◊HÁ˚¨hê"ÆbF?ú%h˙ˇ4xèÕ(ó2ÙáíM])Ñd|=fë-cI0ñL¢kÖêk‰Rƒ«ıÄWñ8mO3∏&√æËX¯Hó—ì]yF2»–˜ádàà‡‹Çο„≥7mªHAS∑¶.;Œx(1} _kd©.fidç48M\'àáªCp^Krí<ɉXÓıïl!Ì$N<ı∞B»G]…∂Ó¯>˛ÔbõÒπÀ•:ôO@È$pÖu‹Ê´-QqV ?V≥JÆÍqÛX8(lπï@zgÖ}Fe<ˇ‡Sñ“ÿ˜ê?6‡L∫Oß~µ –?ËeäÚ®YîÕ =Ü=¢DÁu*GvBk;)L¬N«î:flö∂≠ÇΩq„Ñm하Ë∂‚"û≥§:±≤i^ΩÑ!)Wıyŧô á„RÄ÷Òôc’≠—s™rı‚Pdêãh˘ßHVç5fifiÈF€çÌÛuçÖ/M=gëµ±ÿGû1coÔuñæ‘z®. õ∑7ÉÏÜÆ,°’H†ÍÉÌ∂7e º® íˆ⁄◊øNWK”ÂYµ‚ñé;µ¶gV-fl>µtË¥áßN2 ¯¶BaP-)eW.àôt^∏1›C∑Ö?L„&”5’4jvã–ªZ ÷+4% ´0l…»ú^°´© ûiπ∑é®óܱÒÿ‰ïˆÌ–dˆ◊Æ19rQ=Í|ı•rMæ¬;ò‰Y‰é9.” ‹˝V«ã¯∏,+ë®j*¡·/'; + + $model = new AppModel(array('name' => 'BinaryTest', 'ds' => 'test')); + $model->save(compact('data')); + + $result = $model->find('first'); + $this->assertEquals($data, $result['BinaryTest']['data']); + } + +/** + * Tests the syntax of generated schema indexes + * + * @return void + */ + public function testSchemaIndexSyntax() { + $schema = new CakeSchema(); + $schema->tables = array('i18n' => array( + 'id' => array( + 'type' => 'integer', 'null' => false, 'default' => null, + 'length' => 10, 'key' => 'primary' + ), + 'locale' => array('type' => 'string', 'null' => false, 'length' => 6, 'key' => 'index'), + 'model' => array('type' => 'string', 'null' => false, 'key' => 'index'), + 'foreign_key' => array( + 'type' => 'integer', 'null' => false, 'length' => 10, 'key' => 'index' + ), + 'field' => array('type' => 'string', 'null' => false, 'key' => 'index'), + 'content' => array('type' => 'text', 'null' => true, 'default' => null), + 'indexes' => array( + 'PRIMARY' => array('column' => 'id', 'unique' => 1), + 'locale' => array('column' => 'locale', 'unique' => 0), + 'model' => array('column' => 'model', 'unique' => 0), + 'row_id' => array('column' => 'foreign_key', 'unique' => 0), + 'field' => array('column' => 'field', 'unique' => 0) + ) + )); + + $result = $this->Dbo->createSchema($schema); + $this->assertNotRegExp('/^CREATE INDEX(.+);,$/', $result); + } + +/** + * testCakeSchema method + * + * Test that schema generated postgresql queries are valid. ref #5696 + * Check that the create statement for a schema generated table is the same as the original sql + * + * @return void + */ + public function testCakeSchema() { + $db1 = ConnectionManager::getDataSource('test'); + $db1->cacheSources = false; + + $db1->rawQuery('CREATE TABLE ' . $db1->fullTableName('datatype_tests') . ' ( + id serial NOT NULL, + "varchar" character varying(40) NOT NULL, + "full_length" character varying NOT NULL, + "timestamp" timestamp without time zone, + "date" date, + CONSTRAINT test_data_types_pkey PRIMARY KEY (id) + )'); + + $model = new Model(array('name' => 'DatatypeTest', 'ds' => 'test')); + $schema = new CakeSchema(array('connection' => 'test')); + $result = $schema->read(array( + 'connection' => 'test', + 'models' => array('DatatypeTest') + )); + $schema->tables = array('datatype_tests' => $result['tables']['missing']['datatype_tests']); + $result = $db1->createSchema($schema, 'datatype_tests'); + + $this->assertNotRegExp('/timestamp DEFAULT/', $result); + $this->assertRegExp('/\"full_length\"\s*text\s.*,/', $result); + $this->assertRegExp('/timestamp\s*,/', $result); + + $db1->query('DROP TABLE ' . $db1->fullTableName('datatype_tests')); + + $db1->query($result); + $result2 = $schema->read(array( + 'connection' => 'test', + 'models' => array('DatatypeTest') + )); + $schema->tables = array('datatype_tests' => $result2['tables']['missing']['datatype_tests']); + $result2 = $db1->createSchema($schema, 'datatype_tests'); + $this->assertEquals($result, $result2); + + $db1->query('DROP TABLE ' . $db1->fullTableName('datatype_tests')); + } + +/** + * Test index generation from table info. + * + * @return void + */ + public function testIndexGeneration() { + $name = $this->Dbo->fullTableName('index_test', false, false); + $this->Dbo->query('CREATE TABLE ' . $name . ' ("id" serial NOT NULL PRIMARY KEY, "bool" integer, "small_char" varchar(50), "description" varchar(40) )'); + $this->Dbo->query('CREATE INDEX pointless_bool ON ' . $name . '("bool")'); + $this->Dbo->query('CREATE UNIQUE INDEX char_index ON ' . $name . '("small_char")'); + $expected = array( + 'PRIMARY' => array('unique' => true, 'column' => 'id'), + 'pointless_bool' => array('unique' => false, 'column' => 'bool'), + 'char_index' => array('unique' => true, 'column' => 'small_char'), + ); + $result = $this->Dbo->index($name); + $this->Dbo->query('DROP TABLE ' . $name); + $this->assertEquals($expected, $result); + + $name = $this->Dbo->fullTableName('index_test_2', false, false); + $this->Dbo->query('CREATE TABLE ' . $name . ' ("id" serial NOT NULL PRIMARY KEY, "bool" integer, "small_char" varchar(50), "description" varchar(40) )'); + $this->Dbo->query('CREATE UNIQUE INDEX multi_col ON ' . $name . '("small_char", "bool")'); + $expected = array( + 'PRIMARY' => array('unique' => true, 'column' => 'id'), + 'multi_col' => array('unique' => true, 'column' => array('small_char', 'bool')), + ); + $result = $this->Dbo->index($name); + $this->Dbo->query('DROP TABLE ' . $name); + $this->assertEquals($expected, $result); + } + +/** + * Test the alterSchema capabilities of postgres + * + * @return void + */ + public function testAlterSchema() { + $Old = new CakeSchema(array( + 'connection' => 'test', + 'name' => 'AlterPosts', + 'alter_posts' => array( + 'id' => array('type' => 'integer', 'key' => 'primary'), + 'author_id' => array('type' => 'integer', 'null' => false), + 'title' => array('type' => 'string', 'null' => true), + 'body' => array('type' => 'text'), + 'published' => array('type' => 'string', 'length' => 1, 'default' => 'N'), + 'created' => array('type' => 'datetime'), + 'updated' => array('type' => 'datetime'), + ) + )); + $this->Dbo->query($this->Dbo->createSchema($Old)); + + $New = new CakeSchema(array( + 'connection' => 'test', + 'name' => 'AlterPosts', + 'alter_posts' => array( + 'id' => array('type' => 'integer', 'key' => 'primary'), + 'author_id' => array('type' => 'integer', 'null' => true), + 'title' => array('type' => 'string', 'null' => false, 'default' => 'my title'), + 'body' => array('type' => 'string', 'length' => 500), + 'status' => array('type' => 'integer', 'length' => 3, 'default' => 1), + 'created' => array('type' => 'datetime'), + 'updated' => array('type' => 'datetime'), + ) + )); + $this->Dbo->query($this->Dbo->alterSchema($New->compare($Old), 'alter_posts')); + + $model = new CakeTestModel(array('table' => 'alter_posts', 'ds' => 'test')); + $result = $model->schema(); + $this->assertTrue(isset($result['status'])); + $this->assertFalse(isset($result['published'])); + $this->assertEquals('string', $result['body']['type']); + $this->assertEquals(1, $result['status']['default']); + $this->assertEquals(true, $result['author_id']['null']); + $this->assertEquals(false, $result['title']['null']); + + $this->Dbo->query($this->Dbo->dropSchema($New)); + + $New = new CakeSchema(array( + 'connection' => 'test_suite', + 'name' => 'AlterPosts', + 'alter_posts' => array( + 'id' => array('type' => 'string', 'length' => 36, 'key' => 'primary'), + 'author_id' => array('type' => 'integer', 'null' => false), + 'title' => array('type' => 'string', 'null' => true), + 'body' => array('type' => 'text'), + 'published' => array('type' => 'string', 'length' => 1, 'default' => 'N'), + 'created' => array('type' => 'datetime'), + 'updated' => array('type' => 'datetime'), + ) + )); + $result = $this->Dbo->alterSchema($New->compare($Old), 'alter_posts'); + $this->assertNotRegExp('/varchar\(36\) NOT NULL/i', $result); + } + +/** + * Test the alter index capabilities of postgres + * + * @return void + */ + public function testAlterIndexes() { + $this->Dbo->cacheSources = false; + + $schema1 = new CakeSchema(array( + 'name' => 'AlterTest1', + 'connection' => 'test', + 'altertest' => array( + 'id' => array('type' => 'integer', 'null' => false, 'default' => 0), + 'name' => array('type' => 'string', 'null' => false, 'length' => 50), + 'group1' => array('type' => 'integer', 'null' => true), + 'group2' => array('type' => 'integer', 'null' => true) + ) + )); + + $this->Dbo->rawQuery($this->Dbo->createSchema($schema1)); + + $schema2 = new CakeSchema(array( + 'name' => 'AlterTest2', + 'connection' => 'test', + 'altertest' => array( + 'id' => array('type' => 'integer', 'null' => false, 'default' => 0), + 'name' => array('type' => 'string', 'null' => false, 'length' => 50), + 'group1' => array('type' => 'integer', 'null' => true), + 'group2' => array('type' => 'integer', 'null' => true), + 'indexes' => array( + 'name_idx' => array('unique' => false, 'column' => 'name'), + 'group_idx' => array('unique' => false, 'column' => 'group1'), + 'compound_idx' => array('unique' => false, 'column' => array('group1', 'group2')), + 'PRIMARY' => array('unique' => true, 'column' => 'id') + ) + ) + )); + $this->Dbo->query($this->Dbo->alterSchema($schema2->compare($schema1))); + + $indexes = $this->Dbo->index('altertest'); + $this->assertEquals($schema2->tables['altertest']['indexes'], $indexes); + + // Change three indexes, delete one and add another one + $schema3 = new CakeSchema(array( + 'name' => 'AlterTest3', + 'connection' => 'test', + 'altertest' => array( + 'id' => array('type' => 'integer', 'null' => false, 'default' => 0), + 'name' => array('type' => 'string', 'null' => false, 'length' => 50), + 'group1' => array('type' => 'integer', 'null' => true), + 'group2' => array('type' => 'integer', 'null' => true), + 'indexes' => array( + 'name_idx' => array('unique' => true, 'column' => 'name'), + 'group_idx' => array('unique' => false, 'column' => 'group2'), + 'compound_idx' => array('unique' => false, 'column' => array('group2', 'group1')), + 'another_idx' => array('unique' => false, 'column' => array('group1', 'name'))) + ))); + + $this->Dbo->query($this->Dbo->alterSchema($schema3->compare($schema2))); + + $indexes = $this->Dbo->index('altertest'); + $this->assertEquals($schema3->tables['altertest']['indexes'], $indexes); + + // Compare us to ourself. + $this->assertEquals(array(), $schema3->compare($schema3)); + + // Drop the indexes + $this->Dbo->query($this->Dbo->alterSchema($schema1->compare($schema3))); + + $indexes = $this->Dbo->index('altertest'); + $this->assertEquals(array(), $indexes); + + $this->Dbo->query($this->Dbo->dropSchema($schema1)); + } + +/** + * Test it is possible to use virtual field with postgresql + * + * @return void + */ + public function testVirtualFields() { + $this->loadFixtures('Article', 'Comment', 'User', 'Attachment', 'Tag', 'ArticlesTag'); + $Article = new Article; + $Article->virtualFields = array( + 'next_id' => 'Article.id + 1', + 'complex' => 'Article.title || Article.body', + 'functional' => 'COALESCE(User.user, Article.title)', + 'subquery' => 'SELECT count(*) FROM ' . $Article->Comment->table + ); + $result = $Article->find('first'); + $this->assertEquals(2, $result['Article']['next_id']); + $this->assertEquals($result['Article']['complex'], $result['Article']['title'] . $result['Article']['body']); + $this->assertEquals($result['Article']['functional'], $result['User']['user']); + $this->assertEquals(6, $result['Article']['subquery']); + } + +/** + * Test that virtual fields work with SQL constants + * + * @return void + */ + public function testVirtualFieldAsAConstant() { + $this->loadFixtures('Article', 'Comment'); + $Article = ClassRegistry::init('Article'); + $Article->virtualFields = array( + 'empty' => "NULL", + 'number' => 43, + 'truth' => 'TRUE' + ); + $result = $Article->find('first'); + $this->assertNull($result['Article']['empty']); + $this->assertTrue($result['Article']['truth']); + $this->assertEquals(43, $result['Article']['number']); + } + +/** + * Tests additional order options for postgres + * + * @return void + */ + public function testOrderAdditionalParams() { + $result = $this->Dbo->order(array('title' => 'DESC NULLS FIRST', 'body' => 'DESC')); + $expected = ' ORDER BY "title" DESC NULLS FIRST, "body" DESC'; + $this->assertEquals($expected, $result); + } + +/** + * Test it is possible to do a SELECT COUNT(DISTINCT Model.field) + * query in postgres and it gets correctly quoted + * + * @return void + */ + public function testQuoteDistinctInFunction() { + $this->loadFixtures('Article'); + $Article = new Article; + $result = $this->Dbo->fields($Article, null, array('COUNT(DISTINCT Article.id)')); + $expected = array('COUNT(DISTINCT "Article"."id")'); + $this->assertEquals($expected, $result); + + $result = $this->Dbo->fields($Article, null, array('COUNT(DISTINCT id)')); + $expected = array('COUNT(DISTINCT "id")'); + $this->assertEquals($expected, $result); + + $result = $this->Dbo->fields($Article, null, array('COUNT(DISTINCT FUNC(id))')); + $expected = array('COUNT(DISTINCT FUNC("id"))'); + $this->assertEquals($expected, $result); + } + +/** + * test that saveAll works even with conditions that lack a model name. + * + * @return void + */ + public function testUpdateAllWithNonQualifiedConditions() { + $this->loadFixtures('Article'); + $Article = new Article(); + $result = $Article->updateAll(array('title' => "'Awesome'"), array('title' => 'Third Article')); + $this->assertTrue($result); + + $result = $Article->find('count', array( + 'conditions' => array('Article.title' => 'Awesome') + )); + $this->assertEquals(1, $result, 'Article count is wrong or fixture has changed.'); + } + +/** + * test alterSchema on two tables. + * + * @return void + */ + public function testAlteringTwoTables() { + $schema1 = new CakeSchema(array( + 'name' => 'AlterTest1', + 'connection' => 'test', + 'altertest' => array( + 'id' => array('type' => 'integer', 'null' => false, 'default' => 0), + 'name' => array('type' => 'string', 'null' => false, 'length' => 50), + ), + 'other_table' => array( + 'id' => array('type' => 'integer', 'null' => false, 'default' => 0), + 'name' => array('type' => 'string', 'null' => false, 'length' => 50), + ) + )); + $schema2 = new CakeSchema(array( + 'name' => 'AlterTest1', + 'connection' => 'test', + 'altertest' => array( + 'id' => array('type' => 'integer', 'null' => false, 'default' => 0), + 'field_two' => array('type' => 'string', 'null' => false, 'length' => 50), + ), + 'other_table' => array( + 'id' => array('type' => 'integer', 'null' => false, 'default' => 0), + 'field_two' => array('type' => 'string', 'null' => false, 'length' => 50), + ) + )); + $result = $this->db->alterSchema($schema2->compare($schema1)); + $this->assertEquals(2, substr_count($result, 'field_two'), 'Too many fields'); + $this->assertFalse(strpos(';ALTER', $result), 'Too many semi colons'); + } + +/** + * test encoding setting. + * + * @return void + */ + public function testEncoding() { + $result = $this->Dbo->setEncoding('UTF8'); + $this->assertTrue($result); + + $result = $this->Dbo->getEncoding(); + $this->assertEquals('UTF8', $result); + + $result = $this->Dbo->setEncoding('EUC_JP'); /* 'EUC_JP' is right character code name in PostgreSQL */ + $this->assertTrue($result); + + $result = $this->Dbo->getEncoding(); + $this->assertEquals('EUC_JP', $result); + } + +/** + * Test truncate with a mock. + * + * @return void + */ + public function testTruncateStatements() { + $this->loadFixtures('Article', 'User'); + $db = ConnectionManager::getDatasource('test'); + $schema = $db->config['schema']; + $Article = new Article(); + + $this->Dbo = $this->getMock('Postgres', array('execute'), array($db->config)); + + $this->Dbo->expects($this->at(0))->method('execute') + ->with("DELETE FROM \"$schema\".\"articles\""); + $this->Dbo->truncate($Article); + + $this->Dbo->expects($this->at(0))->method('execute') + ->with("DELETE FROM \"$schema\".\"articles\""); + $this->Dbo->truncate('articles'); + + // #2355: prevent duplicate prefix + $this->Dbo->config['prefix'] = 'tbl_'; + $Article->tablePrefix = 'tbl_'; + $this->Dbo->expects($this->at(0))->method('execute') + ->with("DELETE FROM \"$schema\".\"tbl_articles\""); + $this->Dbo->truncate($Article); + + $this->Dbo->expects($this->at(0))->method('execute') + ->with("DELETE FROM \"$schema\".\"tbl_articles\""); + $this->Dbo->truncate('articles'); + } + +/** + * Test nested transaction + * + * @return void + */ + public function testNestedTransaction() { + $this->skipIf($this->Dbo->nestedTransactionSupported() === false, 'The Postgres server do not support nested transaction'); + + $this->loadFixtures('Article'); + $model = new Article(); + $model->hasOne = $model->hasMany = $model->belongsTo = $model->hasAndBelongsToMany = array(); + $model->cacheQueries = false; + $this->Dbo->cacheMethods = false; + + $this->assertTrue($this->Dbo->begin()); + $this->assertNotEmpty($model->read(null, 1)); + + $this->assertTrue($this->Dbo->begin()); + $this->assertTrue($model->delete(1)); + $this->assertEmpty($model->read(null, 1)); + $this->assertTrue($this->Dbo->rollback()); + $this->assertNotEmpty($model->read(null, 1)); + + $this->assertTrue($this->Dbo->begin()); + $this->assertTrue($model->delete(1)); + $this->assertEmpty($model->read(null, 1)); + $this->assertTrue($this->Dbo->commit()); + $this->assertEmpty($model->read(null, 1)); + + $this->assertTrue($this->Dbo->rollback()); + $this->assertNotEmpty($model->read(null, 1)); + } + +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Datasource/Database/SqliteTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Datasource/Database/SqliteTest.php new file mode 100644 index 0000000..f590cc7 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Datasource/Database/SqliteTest.php @@ -0,0 +1,419 @@ +simulated[] = $sql; + return null; + } + +/** + * getLastQuery method + * + * @return void + */ + public function getLastQuery() { + return $this->simulated[count($this->simulated) - 1]; + } + +} + +/** + * DboSqliteTest class + * + * @package Cake.Test.Case.Model.Datasource.Database + */ +class SqliteTest extends CakeTestCase { + +/** + * Do not automatically load fixtures for each test, they will be loaded manually using CakeTestCase::loadFixtures + * + * @var boolean + */ + public $autoFixtures = false; + +/** + * Fixtures + * + * @var object + */ + public $fixtures = array('core.user', 'core.uuid'); + +/** + * Actual DB connection used in testing + * + * @var DboSource + */ + public $Dbo = null; + +/** + * Sets up a Dbo class instance for testing + * + */ + public function setUp() { + parent::setUp(); + Configure::write('Cache.disable', true); + $this->Dbo = ConnectionManager::getDataSource('test'); + if (!$this->Dbo instanceof Sqlite) { + $this->markTestSkipped('The Sqlite extension is not available.'); + } + } + +/** + * Sets up a Dbo class instance for testing + * + */ + public function tearDown() { + parent::tearDown(); + Configure::write('Cache.disable', false); + } + +/** + * Tests that SELECT queries from DboSqlite::listSources() are not cached + * + */ + public function testTableListCacheDisabling() { + $this->assertFalse(in_array('foo_test', $this->Dbo->listSources())); + + $this->Dbo->query('CREATE TABLE foo_test (test VARCHAR(255))'); + $this->assertTrue(in_array('foo_test', $this->Dbo->listSources())); + + $this->Dbo->cacheSources = false; + $this->Dbo->query('DROP TABLE foo_test'); + $this->assertFalse(in_array('foo_test', $this->Dbo->listSources())); + } + +/** + * test Index introspection. + * + * @return void + */ + public function testIndex() { + $name = $this->Dbo->fullTableName('with_a_key', false, false); + $this->Dbo->query('CREATE TABLE ' . $name . ' ("id" int(11) PRIMARY KEY, "bool" int(1), "small_char" varchar(50), "description" varchar(40) );'); + $this->Dbo->query('CREATE INDEX pointless_bool ON ' . $name . '("bool")'); + $this->Dbo->query('CREATE UNIQUE INDEX char_index ON ' . $name . '("small_char")'); + $expected = array( + 'PRIMARY' => array('column' => 'id', 'unique' => 1), + 'pointless_bool' => array('column' => 'bool', 'unique' => 0), + 'char_index' => array('column' => 'small_char', 'unique' => 1), + + ); + $result = $this->Dbo->index($name); + $this->assertEquals($expected, $result); + $this->Dbo->query('DROP TABLE ' . $name); + + $this->Dbo->query('CREATE TABLE ' . $name . ' ("id" int(11) PRIMARY KEY, "bool" int(1), "small_char" varchar(50), "description" varchar(40) );'); + $this->Dbo->query('CREATE UNIQUE INDEX multi_col ON ' . $name . '("small_char", "bool")'); + $expected = array( + 'PRIMARY' => array('column' => 'id', 'unique' => 1), + 'multi_col' => array('column' => array('small_char', 'bool'), 'unique' => 1), + ); + $result = $this->Dbo->index($name); + $this->assertEquals($expected, $result); + $this->Dbo->query('DROP TABLE ' . $name); + } + +/** + * Tests that cached table descriptions are saved under the sanitized key name + * + */ + public function testCacheKeyName() { + Configure::write('Cache.disable', false); + + $dbName = 'db' . rand() . '$(*%&).db'; + $this->assertFalse(file_exists(TMP . $dbName)); + + $config = $this->Dbo->config; + $db = new Sqlite(array_merge($this->Dbo->config, array('database' => TMP . $dbName))); + $this->assertTrue(file_exists(TMP . $dbName)); + + $db->execute("CREATE TABLE test_list (id VARCHAR(255));"); + + $db->cacheSources = true; + $this->assertEquals(array('test_list'), $db->listSources()); + $db->cacheSources = false; + + $fileName = '_' . preg_replace('/[^A-Za-z0-9_\-+]/', '_', TMP . $dbName) . '_list'; + + $result = Cache::read($fileName, '_cake_model_'); + $this->assertEquals(array('test_list'), $result); + + Cache::delete($fileName, '_cake_model_'); + Configure::write('Cache.disable', true); + } + +/** + * test building columns with SQLite + * + * @return void + */ + public function testBuildColumn() { + $data = array( + 'name' => 'int_field', + 'type' => 'integer', + 'null' => false, + ); + $result = $this->Dbo->buildColumn($data); + $expected = '"int_field" integer NOT NULL'; + $this->assertEquals($expected, $result); + + $data = array( + 'name' => 'name', + 'type' => 'string', + 'length' => 20, + 'null' => false, + ); + $result = $this->Dbo->buildColumn($data); + $expected = '"name" varchar(20) NOT NULL'; + $this->assertEquals($expected, $result); + + $data = array( + 'name' => 'testName', + 'type' => 'string', + 'length' => 20, + 'default' => null, + 'null' => true, + 'collate' => 'NOCASE' + ); + $result = $this->Dbo->buildColumn($data); + $expected = '"testName" varchar(20) DEFAULT NULL COLLATE NOCASE'; + $this->assertEquals($expected, $result); + + $data = array( + 'name' => 'testName', + 'type' => 'string', + 'length' => 20, + 'default' => 'test-value', + 'null' => false, + ); + $result = $this->Dbo->buildColumn($data); + $expected = '"testName" varchar(20) DEFAULT \'test-value\' NOT NULL'; + $this->assertEquals($expected, $result); + + $data = array( + 'name' => 'testName', + 'type' => 'integer', + 'length' => 10, + 'default' => 10, + 'null' => false, + ); + $result = $this->Dbo->buildColumn($data); + $expected = '"testName" integer(10) DEFAULT 10 NOT NULL'; + $this->assertEquals($expected, $result); + + $data = array( + 'name' => 'testName', + 'type' => 'integer', + 'length' => 10, + 'default' => 10, + 'null' => false, + 'collate' => 'BADVALUE' + ); + $result = $this->Dbo->buildColumn($data); + $expected = '"testName" integer(10) DEFAULT 10 NOT NULL'; + $this->assertEquals($expected, $result); + } + +/** + * test describe() and normal results. + * + * @return void + */ + public function testDescribe() { + $this->loadFixtures('User'); + $Model = new Model(array('name' => 'User', 'ds' => 'test', 'table' => 'users')); + + $this->Dbo->cacheSources = true; + Configure::write('Cache.disable', false); + + $result = $this->Dbo->describe($Model); + $expected = array( + 'id' => array( + 'type' => 'integer', + 'key' => 'primary', + 'null' => false, + 'default' => null, + 'length' => 11 + ), + 'user' => array( + 'type' => 'string', + 'length' => 255, + 'null' => true, + 'default' => null + ), + 'password' => array( + 'type' => 'string', + 'length' => 255, + 'null' => true, + 'default' => null + ), + 'created' => array( + 'type' => 'datetime', + 'null' => true, + 'default' => null, + 'length' => null, + ), + 'updated' => array( + 'type' => 'datetime', + 'null' => true, + 'default' => null, + 'length' => null, + ) + ); + $this->assertEquals($expected, $result); + + $result = $this->Dbo->describe($Model->useTable); + $this->assertEquals($expected, $result); + + $result = Cache::read('test_users', '_cake_model_'); + $this->assertEquals($expected, $result); + } + +/** + * test that describe does not corrupt UUID primary keys + * + * @return void + */ + public function testDescribeWithUuidPrimaryKey() { + $tableName = 'uuid_tests'; + $this->Dbo->query("CREATE TABLE {$tableName} (id VARCHAR(36) PRIMARY KEY, name VARCHAR, created DATETIME, modified DATETIME)"); + $Model = new Model(array('name' => 'UuidTest', 'ds' => 'test', 'table' => 'uuid_tests')); + $result = $this->Dbo->describe($Model); + $expected = array( + 'type' => 'string', + 'length' => 36, + 'null' => false, + 'default' => null, + 'key' => 'primary', + ); + $this->assertEquals($expected, $result['id']); + $this->Dbo->query('DROP TABLE ' . $tableName); + + $tableName = 'uuid_tests'; + $this->Dbo->query("CREATE TABLE {$tableName} (id CHAR(36) PRIMARY KEY, name VARCHAR, created DATETIME, modified DATETIME)"); + $Model = new Model(array('name' => 'UuidTest', 'ds' => 'test', 'table' => 'uuid_tests')); + $result = $this->Dbo->describe($Model); + $expected = array( + 'type' => 'string', + 'length' => 36, + 'null' => false, + 'default' => null, + 'key' => 'primary', + ); + $this->assertEquals($expected, $result['id']); + $this->Dbo->query('DROP TABLE ' . $tableName); + } + +/** + * Test virtualFields with functions. + * + * @return void + */ + public function testVirtualFieldWithFunction() { + $this->loadFixtures('User'); + $User = ClassRegistry::init('User'); + $User->virtualFields = array('name' => 'SUBSTR(User.user, 5, LENGTH(User.user) - 4)'); + + $result = $User->find('first', array( + 'conditions' => array('User.user' => 'garrett') + )); + $this->assertEquals('ett', $result['User']['name']); + } + +/** + * Test that records can be inserted with uuid primary keys, and + * that the primary key is not blank + * + * @return void + */ + public function testUuidPrimaryKeyInsertion() { + $this->loadFixtures('Uuid'); + $Model = ClassRegistry::init('Uuid'); + + $data = array( + 'title' => 'A uuid should work', + 'count' => 10 + ); + $Model->create($data); + $this->assertTrue((bool)$Model->save()); + $result = $Model->read(); + + $this->assertEquals($data['title'], $result['Uuid']['title']); + $this->assertTrue(Validation::uuid($result['Uuid']['id']), 'Not a uuid'); + } + +/** + * Test nested transaction + * + * @return void + */ + public function testNestedTransaction() { + $this->skipIf($this->Dbo->nestedTransactionSupported() === false, 'The Sqlite version do not support nested transaction'); + + $this->loadFixtures('User'); + $model = new User(); + $model->hasOne = $model->hasMany = $model->belongsTo = $model->hasAndBelongsToMany = array(); + $model->cacheQueries = false; + $this->Dbo->cacheMethods = false; + + $this->assertTrue($this->Dbo->begin()); + $this->assertNotEmpty($model->read(null, 1)); + + $this->assertTrue($this->Dbo->begin()); + $this->assertTrue($model->delete(1)); + $this->assertEmpty($model->read(null, 1)); + $this->assertTrue($this->Dbo->rollback()); + $this->assertNotEmpty($model->read(null, 1)); + + $this->assertTrue($this->Dbo->begin()); + $this->assertTrue($model->delete(1)); + $this->assertEmpty($model->read(null, 1)); + $this->assertTrue($this->Dbo->commit()); + $this->assertEmpty($model->read(null, 1)); + + $this->assertTrue($this->Dbo->rollback()); + $this->assertNotEmpty($model->read(null, 1)); + } + +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Datasource/Database/SqlserverTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Datasource/Database/SqlserverTest.php new file mode 100644 index 0000000..e31595b --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Datasource/Database/SqlserverTest.php @@ -0,0 +1,679 @@ +simulated[] = $sql; + return empty($this->executeResultsStack) ? null : array_pop($this->executeResultsStack); + } + +/** + * fetchAll method + * + * @param mixed $sql + * @return void + */ + protected function _matchRecords(Model $model, $conditions = null) { + return $this->conditions(array('id' => array(1, 2))); + } + +/** + * getLastQuery method + * + * @return string + */ + public function getLastQuery() { + return $this->simulated[count($this->simulated) - 1]; + } + +/** + * getPrimaryKey method + * + * @param mixed $model + * @return string + */ + public function getPrimaryKey($model) { + return parent::_getPrimaryKey($model); + } + +/** + * clearFieldMappings method + * + * @return void + */ + public function clearFieldMappings() { + $this->_fieldMappings = array(); + } + +/** + * describe method + * + * @param object $model + * @return void + */ + public function describe($model) { + return empty($this->describe) ? parent::describe($model) : $this->describe; + } + +} + +/** + * SqlserverTestModel class + * + * @package Cake.Test.Case.Model.Datasource.Database + */ +class SqlserverTestModel extends CakeTestModel { + +/** + * name property + * + * @var string 'SqlserverTestModel' + */ + public $name = 'SqlserverTestModel'; + +/** + * useTable property + * + * @var bool false + */ + public $useTable = false; + +/** + * _schema property + * + * @var array + */ + protected $_schema = array( + 'id' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => '8', 'key' => 'primary'), + 'client_id' => array('type' => 'integer', 'null' => '', 'default' => '0', 'length' => '11'), + 'name' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'), + 'login' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'), + 'passwd' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '255'), + 'addr_1' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '255'), + 'addr_2' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '25'), + 'zip_code' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'), + 'city' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'), + 'country' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'), + 'phone' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'), + 'fax' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'), + 'url' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '255'), + 'email' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'), + 'comments' => array('type' => 'text', 'null' => '1', 'default' => '', 'length' => ''), + 'last_login' => array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => ''), + 'created' => array('type' => 'date', 'null' => '1', 'default' => '', 'length' => ''), + 'updated' => array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => null) + ); + +/** + * belongsTo property + * + * @var array + */ + public $belongsTo = array( + 'SqlserverClientTestModel' => array( + 'foreignKey' => 'client_id' + ) + ); + +/** + * find method + * + * @param mixed $conditions + * @param mixed $fields + * @param mixed $order + * @param mixed $recursive + * @return void + */ + public function find($conditions = null, $fields = null, $order = null, $recursive = null) { + return $conditions; + } + +} + +/** + * SqlserverClientTestModel class + * + * @package Cake.Test.Case.Model.Datasource.Database + */ +class SqlserverClientTestModel extends CakeTestModel { + +/** + * name property + * + * @var string 'SqlserverAssociatedTestModel' + */ + public $name = 'SqlserverClientTestModel'; + +/** + * useTable property + * + * @var bool false + */ + public $useTable = false; + +/** + * _schema property + * + * @var array + */ + protected $_schema = array( + 'id' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => '8', 'key' => 'primary'), + 'name' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'), + 'email' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'), + 'created' => array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => ''), + 'updated' => array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => null) + ); +} + +/** + * SqlserverTestResultIterator class + * + * @package Cake.Test.Case.Model.Datasource.Database + */ +class SqlserverTestResultIterator extends ArrayIterator { + +/** + * closeCursor method + * + * @return void + */ + public function closeCursor() { + } + +/** + * fetch method + * + * @return void + */ + public function fetch() { + if (!$this->valid()) { + return null; + } + $current = $this->current(); + $this->next(); + return $current; + } + +} + +/** + * SqlserverTest class + * + * @package Cake.Test.Case.Model.Datasource.Database + */ +class SqlserverTest extends CakeTestCase { + +/** + * The Dbo instance to be tested + * + * @var DboSource + */ + public $db = null; + +/** + * autoFixtures property + * + * @var bool false + */ + public $autoFixtures = false; + +/** + * fixtures property + * + * @var array + */ + public $fixtures = array('core.user', 'core.category', 'core.author', 'core.post'); + +/** + * Sets up a Dbo class instance for testing + * + */ + public function setUp() { + $this->Dbo = ConnectionManager::getDataSource('test'); + if (!($this->Dbo instanceof Sqlserver)) { + $this->markTestSkipped('Please configure the test datasource to use SQL Server.'); + } + $this->db = new SqlserverTestDb($this->Dbo->config); + $this->model = new SqlserverTestModel(); + } + +/** + * tearDown method + * + * @return void + */ + public function tearDown() { + unset($this->Dbo); + unset($this->model); + } + +/** + * testQuoting method + * + * @return void + */ + public function testQuoting() { + $expected = "1.2"; + $result = $this->db->value(1.2, 'float'); + $this->assertSame($expected, $result); + + $expected = "'1,2'"; + $result = $this->db->value('1,2', 'float'); + $this->assertSame($expected, $result); + + $expected = 'NULL'; + $result = $this->db->value('', 'integer'); + $this->assertSame($expected, $result); + + $expected = 'NULL'; + $result = $this->db->value('', 'float'); + $this->assertSame($expected, $result); + + $expected = "''"; + $result = $this->db->value('', 'binary'); + $this->assertSame($expected, $result); + } + +/** + * testFields method + * + * @return void + */ + public function testFields() { + $fields = array( + '[SqlserverTestModel].[id] AS [SqlserverTestModel__id]', + '[SqlserverTestModel].[client_id] AS [SqlserverTestModel__client_id]', + '[SqlserverTestModel].[name] AS [SqlserverTestModel__name]', + '[SqlserverTestModel].[login] AS [SqlserverTestModel__login]', + '[SqlserverTestModel].[passwd] AS [SqlserverTestModel__passwd]', + '[SqlserverTestModel].[addr_1] AS [SqlserverTestModel__addr_1]', + '[SqlserverTestModel].[addr_2] AS [SqlserverTestModel__addr_2]', + '[SqlserverTestModel].[zip_code] AS [SqlserverTestModel__zip_code]', + '[SqlserverTestModel].[city] AS [SqlserverTestModel__city]', + '[SqlserverTestModel].[country] AS [SqlserverTestModel__country]', + '[SqlserverTestModel].[phone] AS [SqlserverTestModel__phone]', + '[SqlserverTestModel].[fax] AS [SqlserverTestModel__fax]', + '[SqlserverTestModel].[url] AS [SqlserverTestModel__url]', + '[SqlserverTestModel].[email] AS [SqlserverTestModel__email]', + '[SqlserverTestModel].[comments] AS [SqlserverTestModel__comments]', + 'CONVERT(VARCHAR(20), [SqlserverTestModel].[last_login], 20) AS [SqlserverTestModel__last_login]', + '[SqlserverTestModel].[created] AS [SqlserverTestModel__created]', + 'CONVERT(VARCHAR(20), [SqlserverTestModel].[updated], 20) AS [SqlserverTestModel__updated]' + ); + + $result = $this->db->fields($this->model); + $expected = $fields; + $this->assertEquals($expected, $result); + + $this->db->clearFieldMappings(); + $result = $this->db->fields($this->model, null, 'SqlserverTestModel.*'); + $expected = $fields; + $this->assertEquals($expected, $result); + + $this->db->clearFieldMappings(); + $result = $this->db->fields($this->model, null, array('*', 'AnotherModel.id', 'AnotherModel.name')); + $expected = array_merge($fields, array( + '[AnotherModel].[id] AS [AnotherModel__id]', + '[AnotherModel].[name] AS [AnotherModel__name]')); + $this->assertEquals($expected, $result); + + $this->db->clearFieldMappings(); + $result = $this->db->fields($this->model, null, array('*', 'SqlserverClientTestModel.*')); + $expected = array_merge($fields, array( + '[SqlserverClientTestModel].[id] AS [SqlserverClientTestModel__id]', + '[SqlserverClientTestModel].[name] AS [SqlserverClientTestModel__name]', + '[SqlserverClientTestModel].[email] AS [SqlserverClientTestModel__email]', + 'CONVERT(VARCHAR(20), [SqlserverClientTestModel].[created], 20) AS [SqlserverClientTestModel__created]', + 'CONVERT(VARCHAR(20), [SqlserverClientTestModel].[updated], 20) AS [SqlserverClientTestModel__updated]')); + $this->assertEquals($expected, $result); + } + +/** + * testDistinctFields method + * + * @return void + */ + public function testDistinctFields() { + $result = $this->db->fields($this->model, null, array('DISTINCT Car.country_code')); + $expected = array('DISTINCT [Car].[country_code] AS [Car__country_code]'); + $this->assertEquals($expected, $result); + + $result = $this->db->fields($this->model, null, 'DISTINCT Car.country_code'); + $expected = array('DISTINCT [Car].[country_code] AS [Car__country_code]'); + $this->assertEquals($expected, $result); + } + +/** + * testDistinctWithLimit method + * + * @return void + */ + public function testDistinctWithLimit() { + $this->db->read($this->model, array( + 'fields' => array('DISTINCT SqlserverTestModel.city', 'SqlserverTestModel.country'), + 'limit' => 5 + )); + $result = $this->db->getLastQuery(); + $this->assertRegExp('/^SELECT DISTINCT TOP 5/', $result); + } + +/** + * testDescribe method + * + * @return void + */ + public function testDescribe() { + $SqlserverTableDescription = new SqlserverTestResultIterator(array( + (object)array( + 'Default' => '((0))', + 'Field' => 'count', + 'Key' => 0, + 'Length' => '4', + 'Null' => 'NO', + 'Type' => 'integer' + ), + (object)array( + 'Default' => '', + 'Field' => 'body', + 'Key' => 0, + 'Length' => '-1', + 'Null' => 'YES', + 'Type' => 'nvarchar' + ), + (object)array( + 'Default' => '', + 'Field' => 'published', + 'Key' => 0, + 'Type' => 'datetime2', + 'Length' => 8, + 'Null' => 'YES', + 'Size' => '' + ), + (object)array( + 'Default' => '', + 'Field' => 'id', + 'Key' => 1, + 'Type' => 'nchar', + 'Length' => 72, + 'Null' => 'NO', + 'Size' => '' + ) + )); + $this->db->executeResultsStack = array($SqlserverTableDescription); + $dummyModel = $this->model; + $result = $this->db->describe($dummyModel); + $expected = array( + 'count' => array( + 'type' => 'integer', + 'null' => false, + 'default' => '0', + 'length' => 4 + ), + 'body' => array( + 'type' => 'text', + 'null' => true, + 'default' => null, + 'length' => null + ), + 'published' => array( + 'type' => 'datetime', + 'null' => true, + 'default' => '', + 'length' => null + ), + 'id' => array( + 'type' => 'string', + 'null' => false, + 'default' => '', + 'length' => 36, + 'key' => 'primary' + ) + ); + $this->assertEquals($expected, $result); + } + +/** + * testBuildColumn + * + * @return void + */ + public function testBuildColumn() { + $column = array('name' => 'id', 'type' => 'integer', 'null' => false, 'default' => '', 'length' => '8', 'key' => 'primary'); + $result = $this->db->buildColumn($column); + $expected = '[id] int IDENTITY (1, 1) NOT NULL'; + $this->assertEquals($expected, $result); + + $column = array('name' => 'client_id', 'type' => 'integer', 'null' => false, 'default' => '0', 'length' => '11'); + $result = $this->db->buildColumn($column); + $expected = '[client_id] int DEFAULT 0 NOT NULL'; + $this->assertEquals($expected, $result); + + $column = array('name' => 'client_id', 'type' => 'integer', 'null' => true); + $result = $this->db->buildColumn($column); + $expected = '[client_id] int NULL'; + $this->assertEquals($expected, $result); + + // 'name' => 'type' format for columns + $column = array('type' => 'integer', 'name' => 'client_id'); + $result = $this->db->buildColumn($column); + $expected = '[client_id] int NULL'; + $this->assertEquals($expected, $result); + + $column = array('type' => 'string', 'name' => 'name'); + $result = $this->db->buildColumn($column); + $expected = '[name] nvarchar(255) NULL'; + $this->assertEquals($expected, $result); + + $column = array('name' => 'name', 'type' => 'string', 'null' => false, 'default' => '', 'length' => '255'); + $result = $this->db->buildColumn($column); + $expected = '[name] nvarchar(255) DEFAULT \'\' NOT NULL'; + $this->assertEquals($expected, $result); + + $column = array('name' => 'name', 'type' => 'string', 'null' => false, 'length' => '255'); + $result = $this->db->buildColumn($column); + $expected = '[name] nvarchar(255) NOT NULL'; + $this->assertEquals($expected, $result); + + $column = array('name' => 'name', 'type' => 'string', 'null' => false, 'default' => null, 'length' => '255'); + $result = $this->db->buildColumn($column); + $expected = '[name] nvarchar(255) NOT NULL'; + $this->assertEquals($expected, $result); + + $column = array('name' => 'name', 'type' => 'string', 'null' => true, 'default' => null, 'length' => '255'); + $result = $this->db->buildColumn($column); + $expected = '[name] nvarchar(255) NULL'; + $this->assertEquals($expected, $result); + + $column = array('name' => 'name', 'type' => 'string', 'null' => true, 'default' => '', 'length' => '255'); + $result = $this->db->buildColumn($column); + $expected = '[name] nvarchar(255) DEFAULT \'\''; + $this->assertEquals($expected, $result); + + $column = array('name' => 'body', 'type' => 'text'); + $result = $this->db->buildColumn($column); + $expected = '[body] nvarchar(MAX)'; + $this->assertEquals($expected, $result); + + $column = array( + 'name' => 'checked', + 'type' => 'boolean', + 'length' => 10, + 'default' => '1' + ); + $result = $this->db->buildColumn($column); + $expected = "[checked] bit DEFAULT '1'"; + $this->assertEquals($expected, $result); + } + +/** + * testBuildIndex method + * + * @return void + */ + public function testBuildIndex() { + $indexes = array( + 'PRIMARY' => array('column' => 'id', 'unique' => 1), + 'client_id' => array('column' => 'client_id', 'unique' => 1) + ); + $result = $this->db->buildIndex($indexes, 'items'); + $expected = array( + 'PRIMARY KEY ([id])', + 'ALTER TABLE items ADD CONSTRAINT client_id UNIQUE([client_id]);' + ); + $this->assertEquals($expected, $result); + + $indexes = array('client_id' => array('column' => 'client_id')); + $result = $this->db->buildIndex($indexes, 'items'); + $this->assertEquals(array(), $result); + + $indexes = array('client_id' => array('column' => array('client_id', 'period_id'), 'unique' => 1)); + $result = $this->db->buildIndex($indexes, 'items'); + $expected = array('ALTER TABLE items ADD CONSTRAINT client_id UNIQUE([client_id], [period_id]);'); + $this->assertEquals($expected, $result); + } + +/** + * testUpdateAllSyntax method + * + * @return void + */ + public function testUpdateAllSyntax() { + $fields = array('SqlserverTestModel.client_id' => '[SqlserverTestModel].[client_id] + 1'); + $conditions = array('SqlserverTestModel.updated <' => date('2009-01-01 00:00:00')); + $this->db->update($this->model, $fields, null, $conditions); + + $result = $this->db->getLastQuery(); + $this->assertNotRegExp('/SqlserverTestModel/', $result); + $this->assertRegExp('/^UPDATE \[sqlserver_test_models\]/', $result); + $this->assertRegExp('/SET \[client_id\] = \[client_id\] \+ 1/', $result); + } + +/** + * testGetPrimaryKey method + * + * @return void + */ + public function testGetPrimaryKey() { + $schema = $this->model->schema(); + + $this->db->describe = $schema; + $result = $this->db->getPrimaryKey($this->model); + $this->assertEquals('id', $result); + + unset($schema['id']['key']); + $this->db->describe = $schema; + $result = $this->db->getPrimaryKey($this->model); + $this->assertNull($result); + } + +/** + * SQL server < 11 doesn't have proper limit/offset support, test that our hack works. + * + * @return void + */ + public function testLimitOffsetHack() { + $this->loadFixtures('Author', 'Post', 'User'); + $query = array( + 'limit' => 2, + 'page' => 1, + 'order' => 'User.user ASC', + ); + $User = ClassRegistry::init('User'); + $results = $User->find('all', $query); + + $this->assertEquals(2, count($results)); + $this->assertEquals('garrett', $results[0]['User']['user']); + $this->assertEquals('larry', $results[1]['User']['user']); + + $query = array( + 'limit' => 2, + 'page' => 2, + 'order' => 'User.user ASC', + ); + $User = ClassRegistry::init('User'); + $results = $User->find('all', $query); + + $this->assertEquals(2, count($results)); + $this->assertFalse(isset($results[0][0])); + $this->assertEquals('mariano', $results[0]['User']['user']); + $this->assertEquals('nate', $results[1]['User']['user']); + } + +/** + * Test that the return of stored procedures is honoured + * + * @return void + */ + public function testStoredProcedureReturn() { + $sql = <<Dbo->execute($sql); + + $sql = <<Dbo->execute($sql); + $this->Dbo->execute('DROP PROC cake_test_procedure'); + + $result = $query->fetch(); + $this->assertEquals(2, $result['value']); + } + +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Datasource/DboSourceTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Datasource/DboSourceTest.php new file mode 100644 index 0000000..c6cef46 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Datasource/DboSourceTest.php @@ -0,0 +1,1102 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The Open Group Test Suite License + * Redistributions of files must retain the above copyright notice. + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Model.Datasource + * @since CakePHP(tm) v 1.2.0.4206 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ + +App::uses('Model', 'Model'); +App::uses('AppModel', 'Model'); +App::uses('DataSource', 'Model/Datasource'); +App::uses('DboSource', 'Model/Datasource'); +require_once dirname(dirname(__FILE__)) . DS . 'models.php'; + +class MockPDO extends PDO { + + public function __construct() { + } + +} + +class MockDataSource extends DataSource { +} + +class DboTestSource extends DboSource { + + public $nestedSupport = false; + + public function connect($config = array()) { + $this->connected = true; + } + + public function mergeAssociation(&$data, &$merge, $association, $type, $selfJoin = false) { + return parent::_mergeAssociation($data, $merge, $association, $type, $selfJoin); + } + + public function setConfig($config = array()) { + $this->config = $config; + } + + public function setConnection($conn) { + $this->_connection = $conn; + } + + public function nestedTransactionSupported() { + return $this->useNestedTransactions && $this->nestedSupport; + } + +} + +class DboSecondTestSource extends DboSource { + + public $startQuote = '_'; + + public $endQuote = '_'; + + public function connect($config = array()) { + $this->connected = true; + } + + public function mergeAssociation(&$data, &$merge, $association, $type, $selfJoin = false) { + return parent::_mergeAssociation($data, $merge, $association, $type, $selfJoin); + } + + public function setConfig($config = array()) { + $this->config = $config; + } + + public function setConnection($conn) { + $this->_connection = $conn; + } + +} + +/** + * DboSourceTest class + * + * @package Cake.Test.Case.Model.Datasource + */ +class DboSourceTest extends CakeTestCase { + +/** + * autoFixtures property + * + * @var bool false + */ + public $autoFixtures = false; + +/** + * fixtures property + * + * @var array + */ + public $fixtures = array( + 'core.apple', 'core.article', 'core.articles_tag', 'core.attachment', 'core.comment', + 'core.sample', 'core.tag', 'core.user', 'core.post', 'core.author', 'core.data_test' + ); + +/** + * setUp method + * + * @return void + */ + public function setUp() { + parent::setUp(); + $this->__config = $this->db->config; + + $this->testDb = new DboTestSource(); + $this->testDb->cacheSources = false; + $this->testDb->startQuote = '`'; + $this->testDb->endQuote = '`'; + + $this->Model = new TestModel(); + } + +/** + * tearDown method + * + * @return void + */ + public function tearDown() { + parent::tearDown(); + unset($this->Model); + } + +/** + * test that booleans and null make logical condition strings. + * + * @return void + */ + public function testBooleanNullConditionsParsing() { + $result = $this->testDb->conditions(true); + $this->assertEquals(' WHERE 1 = 1', $result, 'true conditions failed %s'); + + $result = $this->testDb->conditions(false); + $this->assertEquals(' WHERE 0 = 1', $result, 'false conditions failed %s'); + + $result = $this->testDb->conditions(null); + $this->assertEquals(' WHERE 1 = 1', $result, 'null conditions failed %s'); + + $result = $this->testDb->conditions(array()); + $this->assertEquals(' WHERE 1 = 1', $result, 'array() conditions failed %s'); + + $result = $this->testDb->conditions(''); + $this->assertEquals(' WHERE 1 = 1', $result, '"" conditions failed %s'); + + $result = $this->testDb->conditions(' ', '" " conditions failed %s'); + $this->assertEquals(' WHERE 1 = 1', $result); + } + +/** + * test that order() will accept objects made from DboSource::expression + * + * @return void + */ + public function testOrderWithExpression() { + $expression = $this->testDb->expression("CASE Sample.id WHEN 1 THEN 'Id One' ELSE 'Other Id' END AS case_col"); + $result = $this->testDb->order($expression); + $expected = " ORDER BY CASE Sample.id WHEN 1 THEN 'Id One' ELSE 'Other Id' END AS case_col"; + $this->assertEquals($expected, $result); + } + +/** + * testMergeAssociations method + * + * @return void + */ + public function testMergeAssociations() { + $data = array('Article2' => array( + 'id' => '1', 'user_id' => '1', 'title' => 'First Article', + 'body' => 'First Article Body', 'published' => 'Y', + 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + )); + $merge = array('Topic' => array(array( + 'id' => '1', 'topic' => 'Topic', 'created' => '2007-03-17 01:16:23', + 'updated' => '2007-03-17 01:18:31' + ))); + $expected = array( + 'Article2' => array( + 'id' => '1', 'user_id' => '1', 'title' => 'First Article', + 'body' => 'First Article Body', 'published' => 'Y', + 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ), + 'Topic' => array( + 'id' => '1', 'topic' => 'Topic', 'created' => '2007-03-17 01:16:23', + 'updated' => '2007-03-17 01:18:31' + ) + ); + $this->testDb->mergeAssociation($data, $merge, 'Topic', 'hasOne'); + $this->assertEquals($expected, $data); + + $data = array('Article2' => array( + 'id' => '1', 'user_id' => '1', 'title' => 'First Article', + 'body' => 'First Article Body', 'published' => 'Y', + 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + )); + $merge = array('User2' => array(array( + 'id' => '1', 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31' + ))); + + $expected = array( + 'Article2' => array( + 'id' => '1', 'user_id' => '1', 'title' => 'First Article', + 'body' => 'First Article Body', 'published' => 'Y', + 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ), + 'User2' => array( + 'id' => '1', 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31' + ) + ); + $this->testDb->mergeAssociation($data, $merge, 'User2', 'belongsTo'); + $this->assertEquals($expected, $data); + + $data = array( + 'Article2' => array( + 'id' => '1', 'user_id' => '1', 'title' => 'First Article', 'body' => 'First Article Body', 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ) + ); + $merge = array(array('Comment' => false)); + $expected = array( + 'Article2' => array( + 'id' => '1', 'user_id' => '1', 'title' => 'First Article', 'body' => 'First Article Body', 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ), + 'Comment' => array() + ); + $this->testDb->mergeAssociation($data, $merge, 'Comment', 'hasMany'); + $this->assertEquals($expected, $data); + + $data = array( + 'Article' => array( + 'id' => '1', 'user_id' => '1', 'title' => 'First Article', 'body' => 'First Article Body', 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ) + ); + $merge = array( + array( + 'Comment' => array( + 'id' => '1', 'comment' => 'Comment 1', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31' + ) + ), + array( + 'Comment' => array( + 'id' => '2', 'comment' => 'Comment 2', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31' + ) + ) + ); + $expected = array( + 'Article' => array( + 'id' => '1', 'user_id' => '1', 'title' => 'First Article', 'body' => 'First Article Body', 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ), + 'Comment' => array( + array( + 'id' => '1', 'comment' => 'Comment 1', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31' + ), + array( + 'id' => '2', 'comment' => 'Comment 2', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31' + ) + ) + ); + $this->testDb->mergeAssociation($data, $merge, 'Comment', 'hasMany'); + $this->assertEquals($expected, $data); + + $data = array( + 'Article' => array( + 'id' => '1', 'user_id' => '1', 'title' => 'First Article', 'body' => 'First Article Body', 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ) + ); + $merge = array( + array( + 'Comment' => array( + 'id' => '1', 'comment' => 'Comment 1', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31' + ), + 'User2' => array( + 'id' => '1', 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31' + ) + ), + array( + 'Comment' => array( + 'id' => '2', 'comment' => 'Comment 2', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31' + ), + 'User2' => array( + 'id' => '1', 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31' + ) + ) + ); + $expected = array( + 'Article' => array( + 'id' => '1', 'user_id' => '1', 'title' => 'First Article', 'body' => 'First Article Body', 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ), + 'Comment' => array( + array( + 'id' => '1', 'comment' => 'Comment 1', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31', + 'User2' => array( + 'id' => '1', 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31' + ) + ), + array( + 'id' => '2', 'comment' => 'Comment 2', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31', + 'User2' => array( + 'id' => '1', 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31' + ) + ) + ) + ); + $this->testDb->mergeAssociation($data, $merge, 'Comment', 'hasMany'); + $this->assertEquals($expected, $data); + + $data = array( + 'Article' => array( + 'id' => '1', 'user_id' => '1', 'title' => 'First Article', 'body' => 'First Article Body', 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ) + ); + $merge = array( + array( + 'Comment' => array( + 'id' => '1', 'comment' => 'Comment 1', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31' + ), + 'User2' => array( + 'id' => '1', 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31' + ), + 'Tag' => array( + array('id' => 1, 'tag' => 'Tag 1'), + array('id' => 2, 'tag' => 'Tag 2') + ) + ), + array( + 'Comment' => array( + 'id' => '2', 'comment' => 'Comment 2', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31' + ), + 'User2' => array( + 'id' => '1', 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31' + ), + 'Tag' => array() + ) + ); + $expected = array( + 'Article' => array( + 'id' => '1', 'user_id' => '1', 'title' => 'First Article', 'body' => 'First Article Body', 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ), + 'Comment' => array( + array( + 'id' => '1', 'comment' => 'Comment 1', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31', + 'User2' => array( + 'id' => '1', 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31' + ), + 'Tag' => array( + array('id' => 1, 'tag' => 'Tag 1'), + array('id' => 2, 'tag' => 'Tag 2') + ) + ), + array( + 'id' => '2', 'comment' => 'Comment 2', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31', + 'User2' => array( + 'id' => '1', 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31' + ), + 'Tag' => array() + ) + ) + ); + $this->testDb->mergeAssociation($data, $merge, 'Comment', 'hasMany'); + $this->assertEquals($expected, $data); + + $data = array( + 'Article' => array( + 'id' => '1', 'user_id' => '1', 'title' => 'First Article', 'body' => 'First Article Body', 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ) + ); + $merge = array( + array( + 'Tag' => array( + 'id' => '1', 'tag' => 'Tag 1', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31' + ) + ), + array( + 'Tag' => array( + 'id' => '2', 'tag' => 'Tag 2', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31' + ) + ), + array( + 'Tag' => array( + 'id' => '3', 'tag' => 'Tag 3', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31' + ) + ) + ); + $expected = array( + 'Article' => array( + 'id' => '1', 'user_id' => '1', 'title' => 'First Article', 'body' => 'First Article Body', 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ), + 'Tag' => array( + array( + 'id' => '1', 'tag' => 'Tag 1', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31' + ), + array( + 'id' => '2', 'tag' => 'Tag 2', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31' + ), + array( + 'id' => '3', 'tag' => 'Tag 3', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31' + ) + ) + ); + $this->testDb->mergeAssociation($data, $merge, 'Tag', 'hasAndBelongsToMany'); + $this->assertEquals($expected, $data); + + $data = array( + 'Article' => array( + 'id' => '1', 'user_id' => '1', 'title' => 'First Article', 'body' => 'First Article Body', 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ) + ); + $merge = array( + array( + 'Tag' => array( + 'id' => '1', 'tag' => 'Tag 1', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31' + ) + ), + array( + 'Tag' => array( + 'id' => '2', 'tag' => 'Tag 2', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31' + ) + ), + array( + 'Tag' => array( + 'id' => '3', 'tag' => 'Tag 3', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31' + ) + ) + ); + $expected = array( + 'Article' => array( + 'id' => '1', 'user_id' => '1', 'title' => 'First Article', 'body' => 'First Article Body', 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31' + ), + 'Tag' => array('id' => '1', 'tag' => 'Tag 1', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31') + ); + $this->testDb->mergeAssociation($data, $merge, 'Tag', 'hasOne'); + $this->assertEquals($expected, $data); + } + +/** + * testMagicMethodQuerying method + * + * @return void + */ + public function testMagicMethodQuerying() { + $result = $this->db->query('findByFieldName', array('value'), $this->Model); + $expected = array('first', array( + 'conditions' => array('TestModel.field_name' => 'value'), + 'fields' => null, 'order' => null, 'recursive' => null + )); + $this->assertEquals($expected, $result); + + $result = $this->db->query('findByFindBy', array('value'), $this->Model); + $expected = array('first', array( + 'conditions' => array('TestModel.find_by' => 'value'), + 'fields' => null, 'order' => null, 'recursive' => null + )); + $this->assertEquals($expected, $result); + + $result = $this->db->query('findAllByFieldName', array('value'), $this->Model); + $expected = array('all', array( + 'conditions' => array('TestModel.field_name' => 'value'), + 'fields' => null, 'order' => null, 'limit' => null, + 'page' => null, 'recursive' => null + )); + $this->assertEquals($expected, $result); + + $result = $this->db->query('findAllById', array('a'), $this->Model); + $expected = array('all', array( + 'conditions' => array('TestModel.id' => 'a'), + 'fields' => null, 'order' => null, 'limit' => null, + 'page' => null, 'recursive' => null + )); + $this->assertEquals($expected, $result); + + $result = $this->db->query('findByFieldName', array(array('value1', 'value2', 'value3')), $this->Model); + $expected = array('first', array( + 'conditions' => array('TestModel.field_name' => array('value1', 'value2', 'value3')), + 'fields' => null, 'order' => null, 'recursive' => null + )); + $this->assertEquals($expected, $result); + + $result = $this->db->query('findByFieldName', array(null), $this->Model); + $expected = array('first', array( + 'conditions' => array('TestModel.field_name' => null), + 'fields' => null, 'order' => null, 'recursive' => null + )); + $this->assertEquals($expected, $result); + + $result = $this->db->query('findByFieldName', array('= a'), $this->Model); + $expected = array('first', array( + 'conditions' => array('TestModel.field_name' => '= a'), + 'fields' => null, 'order' => null, 'recursive' => null + )); + $this->assertEquals($expected, $result); + + $result = $this->db->query('findByFieldName', array(), $this->Model); + $expected = false; + $this->assertEquals($expected, $result); + } + +/** + * + * @expectedException PDOException + * @return void + */ + public function testDirectCallThrowsException() { + $result = $this->db->query('directCall', array(), $this->Model); + } + +/** + * testValue method + * + * @return void + */ + public function testValue() { + if ($this->db instanceof Sqlserver) { + $this->markTestSkipped('Cannot run this test with SqlServer'); + } + $result = $this->db->value('{$__cakeForeignKey__$}'); + $this->assertEquals('{$__cakeForeignKey__$}', $result); + + $result = $this->db->value(array('first', 2, 'third')); + $expected = array('\'first\'', 2, '\'third\''); + $this->assertEquals($expected, $result); + } + +/** + * testReconnect method + * + * @return void + */ + public function testReconnect() { + $this->testDb->reconnect(array('prefix' => 'foo')); + $this->assertTrue($this->testDb->connected); + $this->assertEquals('foo', $this->testDb->config['prefix']); + } + +/** + * testName method + * + * @return void + */ + public function testName() { + $result = $this->testDb->name('name'); + $expected = '`name`'; + $this->assertEquals($expected, $result); + + $result = $this->testDb->name(array('name', 'Model.*')); + $expected = array('`name`', '`Model`.*'); + $this->assertEquals($expected, $result); + + $result = $this->testDb->name('MTD()'); + $expected = 'MTD()'; + $this->assertEquals($expected, $result); + + $result = $this->testDb->name('(sm)'); + $expected = '(sm)'; + $this->assertEquals($expected, $result); + + $result = $this->testDb->name('name AS x'); + $expected = '`name` AS `x`'; + $this->assertEquals($expected, $result); + + $result = $this->testDb->name('Model.name AS x'); + $expected = '`Model`.`name` AS `x`'; + $this->assertEquals($expected, $result); + + $result = $this->testDb->name('Function(Something.foo)'); + $expected = 'Function(`Something`.`foo`)'; + $this->assertEquals($expected, $result); + + $result = $this->testDb->name('Function(SubFunction(Something.foo))'); + $expected = 'Function(SubFunction(`Something`.`foo`))'; + $this->assertEquals($expected, $result); + + $result = $this->testDb->name('Function(Something.foo) AS x'); + $expected = 'Function(`Something`.`foo`) AS `x`'; + $this->assertEquals($expected, $result); + + $result = $this->testDb->name('name-with-minus'); + $expected = '`name-with-minus`'; + $this->assertEquals($expected, $result); + + $result = $this->testDb->name(array('my-name', 'Foo-Model.*')); + $expected = array('`my-name`', '`Foo-Model`.*'); + $this->assertEquals($expected, $result); + + $result = $this->testDb->name(array('Team.P%', 'Team.G/G')); + $expected = array('`Team`.`P%`', '`Team`.`G/G`'); + $this->assertEquals($expected, $result); + + $result = $this->testDb->name('Model.name as y'); + $expected = '`Model`.`name` AS `y`'; + $this->assertEquals($expected, $result); + } + +/** + * test that cacheMethod works as expected + * + * @return void + */ + public function testCacheMethod() { + $this->testDb->cacheMethods = true; + $result = $this->testDb->cacheMethod('name', 'some-key', 'stuff'); + $this->assertEquals('stuff', $result); + + $result = $this->testDb->cacheMethod('name', 'some-key'); + $this->assertEquals('stuff', $result); + + $result = $this->testDb->cacheMethod('conditions', 'some-key'); + $this->assertNull($result); + + $result = $this->testDb->cacheMethod('name', 'other-key'); + $this->assertNull($result); + + $this->testDb->cacheMethods = false; + $result = $this->testDb->cacheMethod('name', 'some-key', 'stuff'); + $this->assertEquals('stuff', $result); + + $result = $this->testDb->cacheMethod('name', 'some-key'); + $this->assertNull($result); + } + +/** + * Test that rare collisions do not happen with method caching + * + * @return void + */ + public function testNameMethodCacheCollisions() { + $this->testDb->cacheMethods = true; + $this->testDb->flushMethodCache(); + $this->testDb->name('Model.fieldlbqndkezcoapfgirmjsh'); + $result = $this->testDb->name('Model.fieldkhdfjmelarbqnzsogcpi'); + $expected = '`Model`.`fieldkhdfjmelarbqnzsogcpi`'; + $this->assertEquals($expected, $result); + } + +/** + * testLog method + * + * @outputBuffering enabled + * @return void + */ + public function testLog() { + $this->testDb->logQuery('Query 1'); + $this->testDb->logQuery('Query 2'); + + $log = $this->testDb->getLog(false, false); + $result = Hash::extract($log['log'], '{n}.query'); + $expected = array('Query 1', 'Query 2'); + $this->assertEquals($expected, $result); + + $oldDebug = Configure::read('debug'); + Configure::write('debug', 2); + ob_start(); + $this->testDb->showLog(); + $contents = ob_get_clean(); + + $this->assertRegExp('/Query 1/s', $contents); + $this->assertRegExp('/Query 2/s', $contents); + + ob_start(); + $this->testDb->showLog(true); + $contents = ob_get_clean(); + + $this->assertRegExp('/Query 1/s', $contents); + $this->assertRegExp('/Query 2/s', $contents); + + Configure::write('debug', $oldDebug); + } + +/** + * test getting the query log as an array. + * + * @return void + */ + public function testGetLog() { + $this->testDb->logQuery('Query 1'); + $this->testDb->logQuery('Query 2'); + + $log = $this->testDb->getLog(); + $expected = array('query' => 'Query 1', 'params' => array(), 'affected' => '', 'numRows' => '', 'took' => ''); + + $this->assertEquals($expected, $log['log'][0]); + $expected = array('query' => 'Query 2', 'params' => array(), 'affected' => '', 'numRows' => '', 'took' => ''); + $this->assertEquals($expected, $log['log'][1]); + $expected = array('query' => 'Error 1', 'affected' => '', 'numRows' => '', 'took' => ''); + } + +/** + * test getting the query log as an array, setting bind params. + * + * @return void + */ + public function testGetLogParams() { + $this->testDb->logQuery('Query 1', array(1,2,'abc')); + $this->testDb->logQuery('Query 2', array('field1' => 1, 'field2' => 'abc')); + + $log = $this->testDb->getLog(); + $expected = array('query' => 'Query 1', 'params' => array(1,2,'abc'), 'affected' => '', 'numRows' => '', 'took' => ''); + $this->assertEquals($expected, $log['log'][0]); + $expected = array('query' => 'Query 2', 'params' => array('field1' => 1, 'field2' => 'abc'), 'affected' => '', 'numRows' => '', 'took' => ''); + $this->assertEquals($expected, $log['log'][1]); + } + +/** + * test that query() returns boolean values from operations like CREATE TABLE + * + * @return void + */ + public function testFetchAllBooleanReturns() { + $name = $this->db->fullTableName('test_query'); + $query = "CREATE TABLE {$name} (name varchar(10));"; + $result = $this->db->query($query); + $this->assertTrue($result, 'Query did not return a boolean'); + + $query = "DROP TABLE {$name};"; + $result = $this->db->query($query); + $this->assertTrue($result, 'Query did not return a boolean'); + } + +/** + * test order to generate query order clause for virtual fields + * + * @return void + */ + public function testVirtualFieldsInOrder() { + $Article = ClassRegistry::init('Article'); + $Article->virtualFields = array( + 'this_moment' => 'NOW()', + 'two' => '1 + 1', + ); + $order = array('two', 'this_moment'); + $result = $this->db->order($order, 'ASC', $Article); + $expected = ' ORDER BY (1 + 1) ASC, (NOW()) ASC'; + $this->assertEquals($expected, $result); + + $order = array('Article.two', 'Article.this_moment'); + $result = $this->db->order($order, 'ASC', $Article); + $expected = ' ORDER BY (1 + 1) ASC, (NOW()) ASC'; + $this->assertEquals($expected, $result); + } + +/** + * test the permutations of fullTableName() + * + * @return void + */ + public function testFullTablePermutations() { + $Article = ClassRegistry::init('Article'); + $result = $this->testDb->fullTableName($Article, false, false); + $this->assertEquals('articles', $result); + + $Article->tablePrefix = 'tbl_'; + $result = $this->testDb->fullTableName($Article, false, false); + $this->assertEquals('tbl_articles', $result); + + $Article->useTable = $Article->table = 'with spaces'; + $Article->tablePrefix = ''; + $result = $this->testDb->fullTableName($Article, true, false); + $this->assertEquals('`with spaces`', $result); + + $this->loadFixtures('Article'); + $Article->useTable = $Article->table = 'articles'; + $Article->setDataSource('test'); + $testdb = $Article->getDataSource(); + $result = $testdb->fullTableName($Article, false, true); + $this->assertEquals($testdb->getSchemaName() . '.articles', $result); + + // tests for empty schemaName + $noschema = ConnectionManager::create('noschema', array( + 'datasource' => 'DboTestSource' + )); + $Article->setDataSource('noschema'); + $Article->schemaName = null; + $result = $noschema->fullTableName($Article, false, true); + $this->assertEquals('articles', $result); + + $this->testDb->config['prefix'] = 't_'; + $result = $this->testDb->fullTableName('post_tag', false, false); + $this->assertEquals('t_post_tag', $result); + } + +/** + * test that read() only calls queryAssociation on db objects when the method is defined. + * + * @return void + */ + public function testReadOnlyCallingQueryAssociationWhenDefined() { + $this->loadFixtures('Article', 'User', 'ArticlesTag', 'Tag'); + ConnectionManager::create('test_no_queryAssociation', array( + 'datasource' => 'MockDataSource' + )); + $Article = ClassRegistry::init('Article'); + $Article->Comment->useDbConfig = 'test_no_queryAssociation'; + $result = $Article->find('all'); + $this->assertTrue(is_array($result)); + } + +/** + * test that queryAssociation() reuse already joined data for 'belongsTo' and 'hasOne' associations + * instead of running unneeded queries for each record + * + * @return void + */ + public function testQueryAssociationUnneededQueries() { + $this->loadFixtures('Article', 'User', 'Comment', 'Attachment', 'Tag', 'ArticlesTag'); + $Comment = new Comment; + + $fullDebug = $this->db->fullDebug; + $this->db->fullDebug = true; + + $Comment->find('all', array('recursive' => 2)); // ensure Model descriptions are saved + $this->db->getLog(); + + // case: Comment belongsTo User and Article + $Comment->unbindModel(array( + 'hasOne' => array('Attachment') + )); + $Comment->Article->unbindModel(array( + 'belongsTo' => array('User'), + 'hasMany' => array('Comment'), + 'hasAndBelongsToMany' => array('Tag') + )); + $Comment->find('all', array('recursive' => 2)); + $log = $this->db->getLog(); + $this->assertEquals(1, count($log['log'])); + + // case: Comment belongsTo Article, Article belongsTo User + $Comment->unbindModel(array( + 'belongsTo' => array('User'), + 'hasOne' => array('Attachment') + )); + $Comment->Article->unbindModel(array( + 'hasMany' => array('Comment'), + 'hasAndBelongsToMany' => array('Tag'), + )); + $Comment->find('all', array('recursive' => 2)); + $log = $this->db->getLog(); + $this->assertEquals(7, count($log['log'])); + + // case: Comment hasOne Attachment + $Comment->unbindModel(array( + 'belongsTo' => array('Article', 'User'), + )); + $Comment->Attachment->unbindModel(array( + 'belongsTo' => array('Comment'), + )); + $Comment->find('all', array('recursive' => 2)); + $log = $this->db->getLog(); + $this->assertEquals(1, count($log['log'])); + + $this->db->fullDebug = $fullDebug; + } + +/** + * test that fields() is using methodCache() + * + * @return void + */ + public function testFieldsUsingMethodCache() { + $this->testDb->cacheMethods = false; + DboTestSource::$methodCache = array(); + + $Article = ClassRegistry::init('Article'); + $this->testDb->fields($Article, null, array('title', 'body', 'published')); + $this->assertTrue(empty(DboTestSource::$methodCache['fields']), 'Cache not empty'); + } + +/** + * test that fields() method cache detects datasource changes + * + * @return void + */ + public function testFieldsCacheKeyWithDatasourceChange() { + ConnectionManager::create('firstschema', array( + 'datasource' => 'DboTestSource' + )); + ConnectionManager::create('secondschema', array( + 'datasource' => 'DboSecondTestSource' + )); + Cache::delete('method_cache', '_cake_core_'); + DboTestSource::$methodCache = array(); + $Article = ClassRegistry::init('Article'); + + $Article->setDataSource('firstschema'); + $ds = $Article->getDataSource(); + $ds->cacheMethods = true; + $first = $ds->fields($Article, null, array('title', 'body', 'published')); + + $Article->setDataSource('secondschema'); + $ds = $Article->getDataSource(); + $ds->cacheMethods = true; + $second = $ds->fields($Article, null, array('title', 'body', 'published')); + + $this->assertNotEquals($first, $second); + $this->assertEquals(2, count(DboTestSource::$methodCache['fields'])); + } + +/** + * Test that group works without a model + * + * @return void + */ + public function testGroupNoModel() { + $result = $this->db->group('created'); + $this->assertEquals(' GROUP BY created', $result); + } + +/** + * Test getting the last error. + */ + public function testLastError() { + $stmt = $this->getMock('PDOStatement'); + $stmt->expects($this->any()) + ->method('errorInfo') + ->will($this->returnValue(array('', 'something', 'bad'))); + + $result = $this->db->lastError($stmt); + $expected = 'something: bad'; + $this->assertEquals($expected, $result); + } + +/** + * Tests that transaction commands are logged + * + * @return void + **/ + public function testTransactionLogging() { + $conn = $this->getMock('MockPDO'); + $db = new DboTestSource; + $db->setConnection($conn); + $conn->expects($this->exactly(2))->method('beginTransaction') + ->will($this->returnValue(true)); + $conn->expects($this->once())->method('commit')->will($this->returnValue(true)); + $conn->expects($this->once())->method('rollback')->will($this->returnValue(true)); + + $db->begin(); + $log = $db->getLog(); + $expected = array('query' => 'BEGIN', 'params' => array(), 'affected' => '', 'numRows' => '', 'took' => ''); + $this->assertEquals($expected, $log['log'][0]); + + $db->commit(); + $expected = array('query' => 'COMMIT', 'params' => array(), 'affected' => '', 'numRows' => '', 'took' => ''); + $log = $db->getLog(); + $this->assertEquals($expected, $log['log'][0]); + + $db->begin(); + $expected = array('query' => 'BEGIN', 'params' => array(), 'affected' => '', 'numRows' => '', 'took' => ''); + $log = $db->getLog(); + $this->assertEquals($expected, $log['log'][0]); + + $db->rollback(); + $expected = array('query' => 'ROLLBACK', 'params' => array(), 'affected' => '', 'numRows' => '', 'took' => ''); + $log = $db->getLog(); + $this->assertEquals($expected, $log['log'][0]); + } + +/** + * Test nested transaction calls + * + * @return void + */ + public function testTransactionNested() { + $conn = $this->getMock('MockPDO'); + $db = new DboTestSource(); + $db->setConnection($conn); + $db->useNestedTransactions = true; + $db->nestedSupport = true; + + $conn->expects($this->at(0))->method('beginTransaction')->will($this->returnValue(true)); + $conn->expects($this->at(1))->method('exec')->with($this->equalTo('SAVEPOINT LEVEL1'))->will($this->returnValue(true)); + $conn->expects($this->at(2))->method('exec')->with($this->equalTo('RELEASE SAVEPOINT LEVEL1'))->will($this->returnValue(true)); + $conn->expects($this->at(3))->method('exec')->with($this->equalTo('SAVEPOINT LEVEL1'))->will($this->returnValue(true)); + $conn->expects($this->at(4))->method('exec')->with($this->equalTo('ROLLBACK TO SAVEPOINT LEVEL1'))->will($this->returnValue(true)); + $conn->expects($this->at(5))->method('commit')->will($this->returnValue(true)); + + $this->_runTransactions($db); + } + +/** + * Test nested transaction calls without support + * + * @return void + */ + public function testTransactionNestedWithoutSupport() { + $conn = $this->getMock('MockPDO'); + $db = new DboTestSource(); + $db->setConnection($conn); + $db->useNestedTransactions = true; + $db->nestedSupport = false; + + $conn->expects($this->once())->method('beginTransaction')->will($this->returnValue(true)); + $conn->expects($this->never())->method('exec'); + $conn->expects($this->once())->method('commit')->will($this->returnValue(true)); + + $this->_runTransactions($db); + } + +/** + * Test nested transaction disabled + * + * @return void + */ + public function testTransactionNestedDisabled() { + $conn = $this->getMock('MockPDO'); + $db = new DboTestSource(); + $db->setConnection($conn); + $db->useNestedTransactions = false; + $db->nestedSupport = true; + + $conn->expects($this->once())->method('beginTransaction')->will($this->returnValue(true)); + $conn->expects($this->never())->method('exec'); + $conn->expects($this->once())->method('commit')->will($this->returnValue(true)); + + $this->_runTransactions($db); + } + +/** + * Nested transaction calls + * + * @param DboTestSource $db + * @return void + */ + protected function _runTransactions($db) { + $db->begin(); + $db->begin(); + $db->commit(); + $db->begin(); + $db->rollback(); + $db->commit(); + } + +/** + * Test build statement with some fields missing + * + * @return void + */ + public function testBuildStatementDefaults() { + $conn = $this->getMock('MockPDO'); + $db = new DboTestSource; + $db->setConnection($conn); + $subQuery = $db->buildStatement( + array( + 'fields' => array('DISTINCT(AssetsTag.asset_id)'), + 'table' => "assets_tags", + 'alias' => "AssetsTag", + 'conditions' => array("Tag.name" => 'foo bar'), + 'limit' => null, + 'group' => "AssetsTag.asset_id" + ), + $this->Model + ); + } + +/** + * data provider for testBuildJoinStatement + * + * @return array + */ + public static function joinStatements($schema) { + return array( + array(array( + 'type' => 'LEFT', + 'alias' => 'PostsTag', + 'table' => 'posts_tags', + 'conditions' => array('PostsTag.post_id = Post.id') + ), 'LEFT JOIN cakephp.posts_tags AS PostsTag ON (PostsTag.post_id = Post.id)'), + array(array( + 'type' => 'LEFT', + 'alias' => 'Stock', + 'table' => '(SELECT Stock.article_id, sum(quantite) quantite FROM stocks AS Stock GROUP BY Stock.article_id)', + 'conditions' => 'Stock.article_id = Article.id' + ), 'LEFT JOIN (SELECT Stock.article_id, sum(quantite) quantite FROM stocks AS Stock GROUP BY Stock.article_id) AS Stock ON (Stock.article_id = Article.id)') + ); + } + +/** + * Test buildJoinStatement() + * ensure that schemaName is not added when table value is a subquery + * + * @dataProvider joinStatements + * @return void + */ + public function testBuildJoinStatement($join, $expected) { + $db = $this->getMock('DboTestSource', array('getSchemaName')); + $db->expects($this->any()) + ->method('getSchemaName') + ->will($this->returnValue('cakephp')); + $result = $db->buildJoinStatement($join); + $this->assertEquals($expected, $result); + } + +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Datasource/Session/CacheSessionTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Datasource/Session/CacheSessionTest.php new file mode 100644 index 0000000..d696d7c --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Datasource/Session/CacheSessionTest.php @@ -0,0 +1,117 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice. + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://cakephp.org CakePHP(tm) Project + * @package Cake.Test.Case.Model.Datasource.Session + * @since CakePHP(tm) v 2.0 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ + +App::uses('CakeSession', 'Model/Datasource'); +App::uses('CacheSession', 'Model/Datasource/Session'); +class_exists('CakeSession'); + +class CacheSessionTest extends CakeTestCase { + + protected static $_sessionBackup; + +/** + * test case startup + * + * @return void + */ + public static function setupBeforeClass() { + Cache::config('session_test', array( + 'engine' => 'File', + 'prefix' => 'session_test_' + )); + self::$_sessionBackup = Configure::read('Session'); + + Configure::write('Session.handler.config', 'session_test'); + } + +/** + * cleanup after test case. + * + * @return void + */ + public static function teardownAfterClass() { + Cache::clear(false, 'session_test'); + Cache::drop('session_test'); + + Configure::write('Session', self::$_sessionBackup); + } + +/** + * setup + * + * @return void + */ + public function setUp() { + parent::setUp(); + $this->storage = new CacheSession(); + } + +/** + * tearDown + * + * @return void + */ + public function tearDown() { + parent::tearDown(); + unset($this->storage); + } + +/** + * test open + * + * @return void + */ + public function testOpen() { + $this->assertTrue($this->storage->open()); + } + +/** + * test write() + * + * @return void + */ + public function testWrite() { + $this->storage->write('abc', 'Some value'); + $this->assertEquals('Some value', Cache::read('abc', 'session_test'), 'Value was not written.'); + $this->assertFalse(Cache::read('abc', 'default'), 'Cache should only write to the given config.'); + } + +/** + * test reading. + * + * @return void + */ + public function testRead() { + $this->storage->write('test_one', 'Some other value'); + $this->assertEquals('Some other value', $this->storage->read('test_one'), 'Incorrect value.'); + } + +/** + * test destroy + * + * @return void + */ + public function testDestroy() { + $this->storage->write('test_one', 'Some other value'); + $this->assertTrue($this->storage->destroy('test_one'), 'Value was not deleted.'); + + $this->assertFalse(Cache::read('test_one', 'session_test'), 'Value stuck around.'); + } + +} \ No newline at end of file diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Datasource/Session/DatabaseSessionTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Datasource/Session/DatabaseSessionTest.php new file mode 100644 index 0000000..3276ae8 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Datasource/Session/DatabaseSessionTest.php @@ -0,0 +1,188 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice. + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://cakephp.org CakePHP(tm) Project + * @package Cake.Test.Case.Model.Datasource.Session + * @since CakePHP(tm) v 2.0 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ + +App::uses('Model', 'Model'); +App::uses('CakeSession', 'Model/Datasource'); +App::uses('DatabaseSession', 'Model/Datasource/Session'); +class_exists('CakeSession'); + +class SessionTestModel extends Model { + + public $name = 'SessionTestModel'; + + public $useTable = 'sessions'; + +} + +/** + * Database session test. + * + * @package Cake.Test.Case.Model.Datasource.Session + */ +class DatabaseSessionTest extends CakeTestCase { + + protected static $_sessionBackup; + +/** + * fixtures + * + * @var string + */ + public $fixtures = array('core.session'); + +/** + * test case startup + * + * @return void + */ + public static function setupBeforeClass() { + self::$_sessionBackup = Configure::read('Session'); + Configure::write('Session.handler', array( + 'model' => 'SessionTestModel', + )); + Configure::write('Session.timeout', 100); + } + +/** + * cleanup after test case. + * + * @return void + */ + public static function teardownAfterClass() { + Configure::write('Session', self::$_sessionBackup); + } + +/** + * setUp + * + * @return void + */ + public function setUp() { + parent::setUp(); + $this->storage = new DatabaseSession(); + } + +/** + * tearDown + * + * @return void + */ + public function tearDown() { + unset($this->storage); + ClassRegistry::flush(); + parent::tearDown(); + } + +/** + * test that constructor sets the right things up. + * + * @return void + */ + public function testConstructionSettings() { + ClassRegistry::flush(); + $storage = new DatabaseSession(); + + $session = ClassRegistry::getObject('session'); + $this->assertInstanceOf('SessionTestModel', $session); + $this->assertEquals('Session', $session->alias); + $this->assertEquals('test', $session->useDbConfig); + $this->assertEquals('sessions', $session->useTable); + } + +/** + * test opening the session + * + * @return void + */ + public function testOpen() { + $this->assertTrue($this->storage->open()); + } + +/** + * test write() + * + * @return void + */ + public function testWrite() { + $result = $this->storage->write('foo', 'Some value'); + $expected = array( + 'Session' => array( + 'id' => 'foo', + 'data' => 'Some value', + 'expires' => time() + (Configure::read('Session.timeout') * 60) + ) + ); + $this->assertEquals($expected, $result); + } + +/** + * testReadAndWriteWithDatabaseStorage method + * + * @return void + */ + public function testWriteEmptySessionId() { + $result = $this->storage->write('', 'This is a Test'); + $this->assertFalse($result); + } + +/** + * test read() + * + * @return void + */ + public function testRead() { + $this->storage->write('foo', 'Some value'); + + $result = $this->storage->read('foo'); + $expected = 'Some value'; + $this->assertEquals($expected, $result); + + $result = $this->storage->read('made up value'); + $this->assertFalse($result); + } + +/** + * test blowing up the session. + * + * @return void + */ + public function testDestroy() { + $this->storage->write('foo', 'Some value'); + + $this->assertTrue($this->storage->destroy('foo'), 'Destroy failed'); + $this->assertFalse($this->storage->read('foo'), 'Value still present.'); + } + +/** + * test the garbage collector + * + * @return void + */ + public function testGc() { + ClassRegistry::flush(); + Configure::write('Session.timeout', 0); + + $storage = new DatabaseSession(); + $storage->write('foo', 'Some value'); + + sleep(1); + $storage->gc(); + $this->assertFalse($storage->read('foo')); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/ModelCrossSchemaHabtmTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/ModelCrossSchemaHabtmTest.php new file mode 100644 index 0000000..57f1bc3 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/ModelCrossSchemaHabtmTest.php @@ -0,0 +1,232 @@ + false on *both* database connections, + * or one connection will step on the other. + * + * PHP 5 + * + * CakePHP(tm) Tests + * Copyright 2005-2012, Cake Software Foundation, Inc. + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Model + * @since CakePHP(tm) v 2.1 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ +require_once dirname(__FILE__) . DS . 'ModelTestBase.php'; + +class ModelCrossSchemaHabtmTest extends BaseModelTest { + +/** + * Fixtures to be used + * + * @var array + */ + public $fixtures = array( + 'core.player', 'core.guild', 'core.guilds_player', + 'core.armor', 'core.armors_player', + ); + +/** + * Don't drop tables if they exist + * + * @var boolean + */ + public $dropTables = false; + +/** + * Don't auto load fixtures + * + * @var boolean + */ + public $autoFixtures = false; + +/** + * setUp method + * + * @return void + */ + public function setUp() { + parent::setUp(); + $this->_checkConfigs(); + } + +/** + * Check if primary and secondary test databases are configured. + * + * @return void + */ + protected function _checkConfigs() { + $config = ConnectionManager::enumConnectionObjects(); + $this->skipIf($this->db instanceof Sqlite, 'This test is not compatible with Sqlite.'); + $this->skipIf( + !isset($config['test']) || !isset($config['test2']), + 'Primary and secondary test databases not configured, ' . + 'skipping cross-database join tests.' . + ' To run these tests, you must define $test and $test2 in your database configuration.' + ); + } + +/** + * testModelDatasources method + * + * @return void + */ + public function testModelDatasources() { + $this->loadFixtures('Player', 'Guild', 'GuildsPlayer'); + + $Player = ClassRegistry::init('Player'); + $this->assertEquals('test', $Player->useDbConfig); + $this->assertEquals('test', $Player->Guild->useDbConfig); + $this->assertEquals('test2', $Player->GuildsPlayer->useDbConfig); + + $this->assertEquals('test', $Player->getDataSource()->configKeyName); + $this->assertEquals('test', $Player->Guild->getDataSource()->configKeyName); + $this->assertEquals('test2', $Player->GuildsPlayer->getDataSource()->configKeyName); + } + +/** + * testHabtmFind method + * + * @return void + */ + public function testHabtmFind() { + $this->loadFixtures('Player', 'Guild', 'GuildsPlayer'); + $Player = ClassRegistry::init('Player'); + + $players = $Player->find('all', array( + 'fields' => array('id', 'name'), + 'contain' => array( + 'Guild' => array( + 'conditions' => array( + 'Guild.name' => 'Wizards', + ), + ), + ), + )); + $this->assertEquals(4, count($players)); + $wizards = Hash::extract($players, '{n}.Guild.{n}[name=Wizards]'); + $this->assertEquals(1, count($wizards)); + + $players = $Player->find('all', array( + 'fields' => array('id', 'name'), + 'conditions' => array( + 'Player.id' => 1, + ), + )); + $this->assertEquals(1, count($players)); + $wizards = Hash::extract($players, '{n}.Guild.{n}'); + $this->assertEquals(2, count($wizards)); + } + +/** + * testHabtmSave method + * + * @return void + */ + public function testHabtmSave() { + $this->loadFixtures('Player', 'Guild', 'GuildsPlayer'); + $Player = ClassRegistry::init('Player'); + $players = $Player->find('count'); + $this->assertEquals(4, $players); + + $player = $Player->create(array( + 'name' => 'rchavik', + )); + + $results = $Player->saveAll($player, array('validate' => 'first')); + $this->assertNotEqual(false, $results); + $count = $Player->find('count'); + $this->assertEquals(5, $count); + + $count = $Player->GuildsPlayer->find('count'); + $this->assertEquals(3, $count); + + $player = $Player->findByName('rchavik'); + $this->assertEmpty($player['Guild']); + + $player['Guild']['Guild'] = array(1, 2, 3); + $Player->save($player); + + $player = $Player->findByName('rchavik'); + $this->assertEquals(3, count($player['Guild'])); + + $players = $Player->find('all', array( + 'contain' => array( + 'conditions' => array( + 'Guild.name' => 'Rangers', + ), + ), + )); + $rangers = Hash::extract($players, '{n}.Guild.{n}[name=Rangers]'); + $this->assertEquals(2, count($rangers)); + } + +/** + * testHabtmWithThreeDatabases method + * + * @return void + */ + public function testHabtmWithThreeDatabases() { + $config = ConnectionManager::enumConnectionObjects(); + $this->skipIf( + !isset($config['test']) || !isset($config['test2']) || !isset($config['test_database_three']), + 'Primary, secondary, and tertiary test databases not configured,' . + ' skipping test. To run these tests, you must define ' . + '$test, $test2, and $test_database_three in your database configuration.' + ); + + $this->loadFixtures('Player', 'Guild', 'GuildsPlayer', 'Armor', 'ArmorsPlayer'); + + $Player = ClassRegistry::init('Player'); + $Player->bindModel(array( + 'hasAndBelongsToMany' => array( + 'Armor' => array( + 'with' => 'ArmorsPlayer', + 'unique' => true, + ), + ), + ), false); + $this->assertEquals('test', $Player->useDbConfig); + $this->assertEquals('test2', $Player->Armor->useDbConfig); + $this->assertEquals('test_database_three', $Player->ArmorsPlayer->useDbConfig); + $players = $Player->find('count'); + $this->assertEquals(4, $players); + + $spongebob = $Player->create(array( + 'id' => 10, + 'name' => 'spongebob', + )); + $spongebob['Armor'] = array('Armor' => array(1, 2, 3, 4)); + $result = $Player->save($spongebob); + + $expected = array( + 'Player' => array( + 'id' => 10, + 'name' => 'spongebob', + ), + 'Armor' => array( + 'Armor' => array( + 1, 2, 3, 4, + 1, 2, 3, 4, + ), + ), + ); + unset($result['Player']['created']); + unset($result['Player']['updated']); + $this->assertEquals($expected, $result); + + $spongebob = $Player->find('all', array( + 'conditions' => array( + 'Player.id' => 10, + ) + )); + $spongeBobsArmors = Hash::extract($spongebob, '{n}.Armor.{n}'); + $this->assertEquals(4, count($spongeBobsArmors)); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/ModelDeleteTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/ModelDeleteTest.php new file mode 100644 index 0000000..329eef3 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/ModelDeleteTest.php @@ -0,0 +1,865 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Model + * @since CakePHP(tm) v 1.2.0.4206 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ +require_once dirname(__FILE__) . DS . 'ModelTestBase.php'; + +/** + * ModelDeleteTest + * + * @package Cake.Test.Case.Model + */ +class ModelDeleteTest extends BaseModelTest { + +/** + * testDeleteHabtmReferenceWithConditions method + * + * @return void + */ + public function testDeleteHabtmReferenceWithConditions() { + $this->loadFixtures('Portfolio', 'Item', 'ItemsPortfolio', 'Syfile', 'Image'); + + $Portfolio = new Portfolio(); + $Portfolio->hasAndBelongsToMany['Item']['conditions'] = array('ItemsPortfolio.item_id >' => 1); + + $result = $Portfolio->find('first', array( + 'conditions' => array('Portfolio.id' => 1) + )); + $expected = array( + array( + 'id' => 3, + 'syfile_id' => 3, + 'published' => false, + 'name' => 'Item 3', + 'ItemsPortfolio' => array( + 'id' => 3, + 'item_id' => 3, + 'portfolio_id' => 1 + )), + array( + 'id' => 4, + 'syfile_id' => 4, + 'published' => false, + 'name' => 'Item 4', + 'ItemsPortfolio' => array( + 'id' => 4, + 'item_id' => 4, + 'portfolio_id' => 1 + )), + array( + 'id' => 5, + 'syfile_id' => 5, + 'published' => false, + 'name' => 'Item 5', + 'ItemsPortfolio' => array( + 'id' => 5, + 'item_id' => 5, + 'portfolio_id' => 1 + ))); + $this->assertEquals($expected, $result['Item']); + + $result = $Portfolio->ItemsPortfolio->find('all', array( + 'conditions' => array('ItemsPortfolio.portfolio_id' => 1) + )); + $expected = array( + array( + 'ItemsPortfolio' => array( + 'id' => 1, + 'item_id' => 1, + 'portfolio_id' => 1 + )), + array( + 'ItemsPortfolio' => array( + 'id' => 3, + 'item_id' => 3, + 'portfolio_id' => 1 + )), + array( + 'ItemsPortfolio' => array( + 'id' => 4, + 'item_id' => 4, + 'portfolio_id' => 1 + )), + array( + 'ItemsPortfolio' => array( + 'id' => 5, + 'item_id' => 5, + 'portfolio_id' => 1 + ))); + $this->assertEquals($expected, $result); + + $Portfolio->delete(1); + + $result = $Portfolio->find('first', array( + 'conditions' => array('Portfolio.id' => 1) + )); + $this->assertFalse($result); + + $result = $Portfolio->ItemsPortfolio->find('all', array( + 'conditions' => array('ItemsPortfolio.portfolio_id' => 1) + )); + $this->assertEquals(array(), $result); + } + +/** + * testDeleteArticleBLinks method + * + * @return void + */ + public function testDeleteArticleBLinks() { + $this->loadFixtures('Article', 'ArticlesTag', 'Tag', 'User'); + $TestModel = new ArticleB(); + + $result = $TestModel->ArticlesTag->find('all'); + $expected = array( + array('ArticlesTag' => array('article_id' => '1', 'tag_id' => '1')), + array('ArticlesTag' => array('article_id' => '1', 'tag_id' => '2')), + array('ArticlesTag' => array('article_id' => '2', 'tag_id' => '1')), + array('ArticlesTag' => array('article_id' => '2', 'tag_id' => '3')) + ); + $this->assertEquals($expected, $result); + + $TestModel->delete(1); + $result = $TestModel->ArticlesTag->find('all'); + + $expected = array( + array('ArticlesTag' => array('article_id' => '2', 'tag_id' => '1')), + array('ArticlesTag' => array('article_id' => '2', 'tag_id' => '3')) + ); + $this->assertEquals($expected, $result); + } + +/** + * testDeleteDependentWithConditions method + * + * @return void + */ + public function testDeleteDependentWithConditions() { + $this->loadFixtures('Cd','Book','OverallFavorite'); + + $Cd = new Cd(); + $Book = new Book(); + $OverallFavorite = new OverallFavorite(); + + $Cd->delete(1); + + $result = $OverallFavorite->find('all', array( + 'fields' => array('model_type', 'model_id', 'priority') + )); + $expected = array( + array( + 'OverallFavorite' => array( + 'model_type' => 'Book', + 'model_id' => 1, + 'priority' => 2 + ))); + + $this->assertTrue(is_array($result)); + $this->assertEquals($expected, $result); + + $Book->delete(1); + + $result = $OverallFavorite->find('all', array( + 'fields' => array('model_type', 'model_id', 'priority') + )); + $expected = array(); + + $this->assertTrue(is_array($result)); + $this->assertEquals($expected, $result); + } + +/** + * testDel method + * + * @return void + */ + public function testDelete() { + $this->loadFixtures('Article', 'Comment', 'Attachment'); + $TestModel = new Article(); + + $result = $TestModel->delete(2); + $this->assertTrue($result); + + $result = $TestModel->read(null, 2); + $this->assertFalse($result); + + $TestModel->recursive = -1; + $result = $TestModel->find('all', array( + 'fields' => array('id', 'title') + )); + $expected = array( + array('Article' => array( + 'id' => 1, + 'title' => 'First Article' + )), + array('Article' => array( + 'id' => 3, + 'title' => 'Third Article' + ))); + $this->assertEquals($expected, $result); + + $result = $TestModel->delete(3); + $this->assertTrue($result); + + $result = $TestModel->read(null, 3); + $this->assertFalse($result); + + $TestModel->recursive = -1; + $result = $TestModel->find('all', array( + 'fields' => array('id', 'title') + )); + $expected = array( + array('Article' => array( + 'id' => 1, + 'title' => 'First Article' + ))); + + $this->assertEquals($expected, $result); + + // make sure deleting a non-existent record doesn't break save() + // ticket #6293 + $this->loadFixtures('Uuid'); + $Uuid = new Uuid(); + $data = array( + 'B607DAB9-88A2-46CF-B57C-842CA9E3B3B3', + '52C8865C-10EE-4302-AE6C-6E7D8E12E2C8', + '8208C7FE-E89C-47C5-B378-DED6C271F9B8'); + foreach ($data as $id) { + $Uuid->save(array('id' => $id)); + } + $Uuid->delete('52C8865C-10EE-4302-AE6C-6E7D8E12E2C8'); + $Uuid->delete('52C8865C-10EE-4302-AE6C-6E7D8E12E2C8'); + foreach ($data as $id) { + $Uuid->save(array('id' => $id)); + } + $result = $Uuid->find('all', array( + 'conditions' => array('id' => $data), + 'fields' => array('id'), + 'order' => 'id')); + $expected = array( + array('Uuid' => array( + 'id' => '52C8865C-10EE-4302-AE6C-6E7D8E12E2C8')), + array('Uuid' => array( + 'id' => '8208C7FE-E89C-47C5-B378-DED6C271F9B8')), + array('Uuid' => array( + 'id' => 'B607DAB9-88A2-46CF-B57C-842CA9E3B3B3'))); + $this->assertEquals($expected, $result); + } + +/** + * test that delete() updates the correct records counterCache() records. + * + * @return void + */ + public function testDeleteUpdatingCounterCacheCorrectly() { + $this->loadFixtures('CounterCacheUser', 'CounterCachePost'); + $User = new CounterCacheUser(); + + $User->Post->delete(3); + $result = $User->read(null, 301); + $this->assertEquals(0, $result['User']['post_count']); + + $result = $User->read(null, 66); + $this->assertEquals(2, $result['User']['post_count']); + } + +/** + * testDeleteAll method + * + * @return void + */ + public function testDeleteAll() { + $this->loadFixtures('Article'); + $TestModel = new Article(); + + $data = array('Article' => array( + 'user_id' => 2, + 'id' => 4, + 'title' => 'Fourth Article', + 'published' => 'N' + )); + $result = $TestModel->set($data) && $TestModel->save(); + $this->assertTrue($result); + + $data = array('Article' => array( + 'user_id' => 2, + 'id' => 5, + 'title' => 'Fifth Article', + 'published' => 'Y' + )); + $result = $TestModel->set($data) && $TestModel->save(); + $this->assertTrue($result); + + $data = array('Article' => array( + 'user_id' => 1, + 'id' => 6, + 'title' => 'Sixth Article', + 'published' => 'N' + )); + $result = $TestModel->set($data) && $TestModel->save(); + $this->assertTrue($result); + + $TestModel->recursive = -1; + $result = $TestModel->find('all', array( + 'fields' => array('id', 'user_id', 'title', 'published'), + 'order' => array('Article.id' => 'ASC') + )); + + $expected = array( + array('Article' => array( + 'id' => 1, + 'user_id' => 1, + 'title' => 'First Article', + 'published' => 'Y' + )), + array('Article' => array( + 'id' => 2, + 'user_id' => 3, + 'title' => 'Second Article', + 'published' => 'Y' + )), + array('Article' => array( + 'id' => 3, + 'user_id' => 1, + 'title' => 'Third Article', + 'published' => 'Y')), + array('Article' => array( + 'id' => 4, + 'user_id' => 2, + 'title' => 'Fourth Article', + 'published' => 'N' + )), + array('Article' => array( + 'id' => 5, + 'user_id' => 2, + 'title' => 'Fifth Article', + 'published' => 'Y' + )), + array('Article' => array( + 'id' => 6, + 'user_id' => 1, + 'title' => 'Sixth Article', + 'published' => 'N' + ))); + + $this->assertEquals($expected, $result); + + $result = $TestModel->deleteAll(array('Article.published' => 'N')); + $this->assertTrue($result); + + $TestModel->recursive = -1; + $result = $TestModel->find('all', array( + 'fields' => array('id', 'user_id', 'title', 'published'), + 'order' => array('Article.id' => 'ASC') + )); + $expected = array( + array('Article' => array( + 'id' => 1, + 'user_id' => 1, + 'title' => 'First Article', + 'published' => 'Y' + )), + array('Article' => array( + 'id' => 2, + 'user_id' => 3, + 'title' => 'Second Article', + 'published' => 'Y' + )), + array('Article' => array( + 'id' => 3, + 'user_id' => 1, + 'title' => 'Third Article', + 'published' => 'Y' + )), + array('Article' => array( + 'id' => 5, + 'user_id' => 2, + 'title' => 'Fifth Article', + 'published' => 'Y' + ))); + $this->assertEquals($expected, $result); + + $data = array('Article.user_id' => array(2, 3)); + $result = $TestModel->deleteAll($data, true, true); + $this->assertTrue($result); + + $TestModel->recursive = -1; + $result = $TestModel->find('all', array( + 'fields' => array('id', 'user_id', 'title', 'published'), + 'order' => array('Article.id' => 'ASC') + )); + $expected = array( + array('Article' => array( + 'id' => 1, + 'user_id' => 1, + 'title' => 'First Article', + 'published' => 'Y' + )), + array('Article' => array( + 'id' => 3, + 'user_id' => 1, + 'title' => 'Third Article', + 'published' => 'Y' + ))); + $this->assertEquals($expected, $result); + + $result = $TestModel->deleteAll(array('Article.user_id' => 999)); + $this->assertTrue($result, 'deleteAll returned false when all no records matched conditions. %s'); + } + +/** + * testDeleteAllUnknownColumn method + * + * @expectedException PDOException + * @return void + */ + public function testDeleteAllUnknownColumn() { + $this->loadFixtures('Article'); + $TestModel = new Article(); + $result = $TestModel->deleteAll(array('Article.non_existent_field' => 999)); + $this->assertFalse($result, 'deleteAll returned true when find query generated sql error. %s'); + } + +/** + * testRecursiveDel method + * + * @return void + */ + public function testRecursiveDel() { + $this->loadFixtures('Article', 'Comment', 'Attachment'); + $TestModel = new Article(); + + $result = $TestModel->delete(2); + $this->assertTrue($result); + + $TestModel->recursive = 2; + $result = $TestModel->read(null, 2); + $this->assertFalse($result); + + $result = $TestModel->Comment->read(null, 5); + $this->assertFalse($result); + + $result = $TestModel->Comment->read(null, 6); + $this->assertFalse($result); + + $result = $TestModel->Comment->Attachment->read(null, 1); + $this->assertFalse($result); + + $result = $TestModel->find('count'); + $this->assertEquals(2, $result); + + $result = $TestModel->Comment->find('count'); + $this->assertEquals(4, $result); + + $result = $TestModel->Comment->Attachment->find('count'); + $this->assertEquals(0, $result); + } + +/** + * testDependentExclusiveDelete method + * + * @return void + */ + public function testDependentExclusiveDelete() { + $this->loadFixtures('Article', 'Comment'); + $TestModel = new Article10(); + + $result = $TestModel->find('all'); + $this->assertEquals(4, count($result[0]['Comment'])); + $this->assertEquals(2, count($result[1]['Comment'])); + $this->assertEquals(6, $TestModel->Comment->find('count')); + + $TestModel->delete(1); + $this->assertEquals(2, $TestModel->Comment->find('count')); + } + +/** + * testDeleteLinks method + * + * @return void + */ + public function testDeleteLinks() { + $this->loadFixtures('Article', 'ArticlesTag', 'Tag'); + $TestModel = new Article(); + + $result = $TestModel->ArticlesTag->find('all'); + $expected = array( + array('ArticlesTag' => array( + 'article_id' => '1', + 'tag_id' => '1' + )), + array('ArticlesTag' => array( + 'article_id' => '1', + 'tag_id' => '2' + )), + array('ArticlesTag' => array( + 'article_id' => '2', + 'tag_id' => '1' + )), + array('ArticlesTag' => array( + 'article_id' => '2', + 'tag_id' => '3' + ))); + $this->assertEquals($expected, $result); + + $TestModel->delete(1); + $result = $TestModel->ArticlesTag->find('all'); + + $expected = array( + array('ArticlesTag' => array( + 'article_id' => '2', + 'tag_id' => '1' + )), + array('ArticlesTag' => array( + 'article_id' => '2', + 'tag_id' => '3' + ))); + $this->assertEquals($expected, $result); + + $result = $TestModel->deleteAll(array('Article.user_id' => 999)); + $this->assertTrue($result, 'deleteAll returned false when all no records matched conditions. %s'); + } + +/** + * test that a plugin model as the 'with' model doesn't have issues + * + * @return void + */ + public function testDeleteLinksWithPLuginJoinModel() { + $this->loadFixtures('Article', 'ArticlesTag', 'Tag'); + $Article = new Article(); + $Article->unbindModel(array('hasAndBelongsToMany' => array('Tag')), false); + unset($Article->Tag, $Article->ArticleTags); + $Article->bindModel(array('hasAndBelongsToMany' => array( + 'Tag' => array('with' => 'TestPlugin.ArticlesTag') + )), false); + + $this->assertTrue($Article->delete(1)); + } + +/** + * testDeleteDependent method + * + * @return void + */ + public function testDeleteDependent() { + $this->loadFixtures('Bidding', 'BiddingMessage', 'Article', + 'ArticlesTag', 'Comment', 'User', 'Attachment' + ); + $Bidding = new Bidding(); + $result = $Bidding->find('all', array('order' => array('Bidding.id' => 'ASC'))); + $expected = array( + array( + 'Bidding' => array('id' => 1, 'bid' => 'One', 'name' => 'Bid 1'), + 'BiddingMessage' => array('bidding' => 'One', 'name' => 'Message 1'), + ), + array( + 'Bidding' => array('id' => 2, 'bid' => 'Two', 'name' => 'Bid 2'), + 'BiddingMessage' => array('bidding' => 'Two', 'name' => 'Message 2'), + ), + array( + 'Bidding' => array('id' => 3, 'bid' => 'Three', 'name' => 'Bid 3'), + 'BiddingMessage' => array('bidding' => 'Three', 'name' => 'Message 3'), + ), + array( + 'Bidding' => array('id' => 4, 'bid' => 'Five', 'name' => 'Bid 5'), + 'BiddingMessage' => array('bidding' => '', 'name' => ''), + ), + ); + $this->assertEquals($expected, $result); + + $Bidding->delete(4, true); + $result = $Bidding->find('all', array('order' => array('Bidding.id' => 'ASC'))); + $expected = array( + array( + 'Bidding' => array('id' => 1, 'bid' => 'One', 'name' => 'Bid 1'), + 'BiddingMessage' => array('bidding' => 'One', 'name' => 'Message 1'), + ), + array( + 'Bidding' => array('id' => 2, 'bid' => 'Two', 'name' => 'Bid 2'), + 'BiddingMessage' => array('bidding' => 'Two', 'name' => 'Message 2'), + ), + array( + 'Bidding' => array('id' => 3, 'bid' => 'Three', 'name' => 'Bid 3'), + 'BiddingMessage' => array('bidding' => 'Three', 'name' => 'Message 3'), + ), + ); + $this->assertEquals($expected, $result); + + $Bidding->delete(2, true); + $result = $Bidding->find('all', array('order' => array('Bidding.id' => 'ASC'))); + $expected = array( + array( + 'Bidding' => array('id' => 1, 'bid' => 'One', 'name' => 'Bid 1'), + 'BiddingMessage' => array('bidding' => 'One', 'name' => 'Message 1'), + ), + array( + 'Bidding' => array('id' => 3, 'bid' => 'Three', 'name' => 'Bid 3'), + 'BiddingMessage' => array('bidding' => 'Three', 'name' => 'Message 3'), + ), + ); + $this->assertEquals($expected, $result); + + $result = $Bidding->BiddingMessage->find('all', array('order' => array('BiddingMessage.name' => 'ASC'))); + $expected = array( + array( + 'BiddingMessage' => array('bidding' => 'One', 'name' => 'Message 1'), + 'Bidding' => array('id' => 1, 'bid' => 'One', 'name' => 'Bid 1'), + ), + array( + 'BiddingMessage' => array('bidding' => 'Three', 'name' => 'Message 3'), + 'Bidding' => array('id' => 3, 'bid' => 'Three', 'name' => 'Bid 3'), + ), + array( + 'BiddingMessage' => array('bidding' => 'Four', 'name' => 'Message 4'), + 'Bidding' => array('id' => '', 'bid' => '', 'name' => ''), + ), + ); + $this->assertEquals($expected, $result); + + $Article = new Article(); + $result = $Article->Comment->find('count', array( + 'conditions' => array('Comment.article_id' => 1) + )); + $this->assertEquals(4, $result); + + $result = $Article->delete(1, true); + $this->assertSame($result, true); + + $result = $Article->Comment->find('count', array( + 'conditions' => array('Comment.article_id' => 1) + )); + $this->assertEquals(0, $result); + } + +/** + * test deleteLinks with Multiple habtm associations + * + * @return void + */ + public function testDeleteLinksWithMultipleHabtmAssociations() { + $this->loadFixtures('JoinA', 'JoinB', 'JoinC', 'JoinAB', 'JoinAC'); + $JoinA = new JoinA(); + + //create two new join records to expose the issue. + $JoinA->JoinAsJoinC->create(array( + 'join_a_id' => 1, + 'join_c_id' => 2, + )); + $JoinA->JoinAsJoinC->save(); + $JoinA->JoinAsJoinB->create(array( + 'join_a_id' => 1, + 'join_b_id' => 2, + )); + $JoinA->JoinAsJoinB->save(); + + $result = $JoinA->delete(1); + $this->assertTrue($result, 'Delete failed %s'); + + $joinedBs = $JoinA->JoinAsJoinB->find('count', array( + 'conditions' => array('JoinAsJoinB.join_a_id' => 1) + )); + $this->assertEquals(0, $joinedBs, 'JoinA/JoinB link records left over. %s'); + + $joinedBs = $JoinA->JoinAsJoinC->find('count', array( + 'conditions' => array('JoinAsJoinC.join_a_id' => 1) + )); + $this->assertEquals(0, $joinedBs, 'JoinA/JoinC link records left over. %s'); + } + +/** + * testHabtmDeleteLinksWhenNoPrimaryKeyInJoinTable method + * + * @return void + */ + public function testHabtmDeleteLinksWhenNoPrimaryKeyInJoinTable() { + $this->loadFixtures('Apple', 'Device', 'ThePaperMonkies'); + $ThePaper = new ThePaper(); + $ThePaper->id = 1; + $ThePaper->save(array('Monkey' => array(2, 3))); + + $result = $ThePaper->findById(1); + $expected = array( + array( + 'id' => '2', + 'device_type_id' => '1', + 'name' => 'Device 2', + 'typ' => '1' + ), + array( + 'id' => '3', + 'device_type_id' => '1', + 'name' => 'Device 3', + 'typ' => '2' + )); + $this->assertEquals($expected, $result['Monkey']); + + $ThePaper = new ThePaper(); + $ThePaper->id = 2; + $ThePaper->save(array('Monkey' => array(2, 3))); + + $result = $ThePaper->findById(2); + $expected = array( + array( + 'id' => '2', + 'device_type_id' => '1', + 'name' => 'Device 2', + 'typ' => '1' + ), + array( + 'id' => '3', + 'device_type_id' => '1', + 'name' => 'Device 3', + 'typ' => '2' + )); + $this->assertEquals($expected, $result['Monkey']); + + $ThePaper->delete(1); + $result = $ThePaper->findById(2); + $expected = array( + array( + 'id' => '2', + 'device_type_id' => '1', + 'name' => 'Device 2', + 'typ' => '1' + ), + array( + 'id' => '3', + 'device_type_id' => '1', + 'name' => 'Device 3', + 'typ' => '2' + )); + $this->assertEquals($expected, $result['Monkey']); + } + +/** + * test that beforeDelete returning false can abort deletion. + * + * @return void + */ + public function testBeforeDeleteDeleteAbortion() { + $this->loadFixtures('Post'); + $Model = new CallbackPostTestModel(); + $Model->beforeDeleteReturn = false; + + $result = $Model->delete(1); + $this->assertFalse($result); + + $exists = $Model->findById(1); + $this->assertTrue(is_array($exists)); + } + +/** + * test for a habtm deletion error that occurs in postgres but should not. + * And should not occur in any dbo. + * + * @return void + */ + public function testDeleteHabtmPostgresFailure() { + $this->loadFixtures('Article', 'Tag', 'ArticlesTag'); + + $Article = ClassRegistry::init('Article'); + $Article->hasAndBelongsToMany['Tag']['unique'] = true; + + $Tag = ClassRegistry::init('Tag'); + $Tag->bindModel(array('hasAndBelongsToMany' => array( + 'Article' => array( + 'className' => 'Article', + 'unique' => true + ) + )), true); + + // Article 1 should have Tag.1 and Tag.2 + $before = $Article->find("all", array( + "conditions" => array("Article.id" => 1), + )); + $this->assertEquals(2, count($before[0]['Tag']), 'Tag count for Article.id = 1 is incorrect, should be 2 %s'); + + // From now on, Tag #1 is only associated with Post #1 + $submittedData = array( + "Tag" => array("id" => 1, 'tag' => 'tag1'), + "Article" => array( + "Article" => array(1) + ) + ); + $Tag->save($submittedData); + + // One more submission (The other way around) to make sure the reverse save looks good. + $submittedData = array( + "Article" => array("id" => 2, 'title' => 'second article'), + "Tag" => array( + "Tag" => array(2, 3) + ) + ); + + // ERROR: + // Postgresql: DELETE FROM "articles_tags" WHERE tag_id IN ('1', '3') + // MySQL: DELETE `ArticlesTag` FROM `articles_tags` AS `ArticlesTag` WHERE `ArticlesTag`.`article_id` = 2 AND `ArticlesTag`.`tag_id` IN (1, 3) + $Article->save($submittedData); + + // Want to make sure Article #1 has Tag #1 and Tag #2 still. + $after = $Article->find("all", array( + "conditions" => array("Article.id" => 1), + )); + + // Removing Article #2 from Tag #1 is all that should have happened. + $this->assertEquals(count($before[0]["Tag"]), count($after[0]["Tag"])); + } + +/** + * test that deleting records inside the beforeDelete doesn't truncate the table. + * + * @return void + */ + public function testBeforeDeleteWipingTable() { + $this->loadFixtures('Comment'); + + $Comment = new BeforeDeleteComment(); + // Delete 3 records. + $Comment->delete(4); + $result = $Comment->find('count'); + + $this->assertTrue($result > 1, 'Comments are all gone.'); + $Comment->create(array( + 'article_id' => 1, + 'user_id' => 2, + 'comment' => 'new record', + 'published' => 'Y' + )); + $Comment->save(); + + $Comment->delete(5); + $result = $Comment->find('count'); + + $this->assertTrue($result > 1, 'Comments are all gone.'); + } + +/** + * test that deleting the same record from the beforeDelete and the delete doesn't truncate the table. + * + * @return void + */ + public function testBeforeDeleteWipingTableWithDuplicateDelete() { + $this->loadFixtures('Comment'); + + $Comment = new BeforeDeleteComment(); + $Comment->delete(1); + + $result = $Comment->find('count'); + $this->assertTrue($result > 1, 'Comments are all gone.'); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/ModelIntegrationTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/ModelIntegrationTest.php new file mode 100644 index 0000000..a7063c0 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/ModelIntegrationTest.php @@ -0,0 +1,2426 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Model + * @since CakePHP(tm) v 1.2.0.4206 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ + +require_once dirname(__FILE__) . DS . 'ModelTestBase.php'; +App::uses('DboSource', 'Model/Datasource'); + +/** + * DboMock class + * A Dbo Source driver to mock a connection and a identity name() method + */ +class DboMock extends DboSource { + +/** + * Returns the $field without modifications + */ + public function name($field) { + return $field; + } + +/** + * Returns true to fake a database connection + */ + public function connect() { + return true; + } + +} + +/** + * ModelIntegrationTest + * + * @package Cake.Test.Case.Model + */ +class ModelIntegrationTest extends BaseModelTest { + +/** + * testAssociationLazyLoading + * + * @group lazyloading + * @return void + */ + public function testAssociationLazyLoading() { + $this->loadFixtures('ArticleFeaturedsTags'); + $Article = new ArticleFeatured(); + $this->assertTrue(isset($Article->belongsTo['User'])); + $this->assertFalse(property_exists($Article, 'User')); + $this->assertInstanceOf('User', $Article->User); + + $this->assertTrue(isset($Article->belongsTo['Category'])); + $this->assertFalse(property_exists($Article, 'Category')); + $this->assertTrue(isset($Article->Category)); + $this->assertInstanceOf('Category', $Article->Category); + + $this->assertTrue(isset($Article->hasMany['Comment'])); + $this->assertFalse(property_exists($Article, 'Comment')); + $this->assertTrue(isset($Article->Comment)); + $this->assertInstanceOf('Comment', $Article->Comment); + + $this->assertTrue(isset($Article->hasAndBelongsToMany['Tag'])); + //There was not enough information to setup the association (joinTable and associationForeignKey) + //so the model was not lazy loaded + $this->assertTrue(property_exists($Article, 'Tag')); + $this->assertTrue(isset($Article->Tag)); + $this->assertInstanceOf('Tag', $Article->Tag); + + $this->assertFalse(property_exists($Article, 'ArticleFeaturedsTag')); + $this->assertInstanceOf('AppModel', $Article->ArticleFeaturedsTag); + $this->assertEquals('article_featureds_tags', $Article->hasAndBelongsToMany['Tag']['joinTable']); + $this->assertEquals('tag_id', $Article->hasAndBelongsToMany['Tag']['associationForeignKey']); + } + +/** + * testAssociationLazyLoadWithHABTM + * + * @group lazyloading + * @return void + */ + public function testAssociationLazyLoadWithHABTM() { + $this->loadFixtures('FruitsUuidTag', 'ArticlesTag'); + $this->db->cacheSources = false; + $Article = new ArticleB(); + $this->assertTrue(isset($Article->hasAndBelongsToMany['TagB'])); + $this->assertFalse(property_exists($Article, 'TagB')); + $this->assertInstanceOf('TagB', $Article->TagB); + + $this->assertFalse(property_exists($Article, 'ArticlesTag')); + $this->assertInstanceOf('AppModel', $Article->ArticlesTag); + + $UuidTag = new UuidTag(); + $this->assertTrue(isset($UuidTag->hasAndBelongsToMany['Fruit'])); + $this->assertFalse(property_exists($UuidTag, 'Fruit')); + $this->assertFalse(property_exists($UuidTag, 'FruitsUuidTag')); + $this->assertTrue(isset($UuidTag->Fruit)); + + $this->assertFalse(property_exists($UuidTag, 'FruitsUuidTag')); + $this->assertTrue(isset($UuidTag->FruitsUuidTag)); + $this->assertInstanceOf('FruitsUuidTag', $UuidTag->FruitsUuidTag); + } + +/** + * testAssociationLazyLoadWithBindModel + * + * @group lazyloading + * @return void + */ + public function testAssociationLazyLoadWithBindModel() { + $this->loadFixtures('Article', 'User'); + $Article = new ArticleB(); + + $this->assertFalse(isset($Article->belongsTo['User'])); + $this->assertFalse(property_exists($Article, 'User')); + + $Article->bindModel(array('belongsTo' => array('User'))); + $this->assertTrue(isset($Article->belongsTo['User'])); + $this->assertFalse(property_exists($Article, 'User')); + $this->assertInstanceOf('User', $Article->User); + } + +/** + * Tests that creating a model with no existent database table associated will throw an exception + * + * @expectedException MissingTableException + * @return void + */ + public function testMissingTable() { + $Article = new ArticleB(false, uniqid()); + $Article->schema(); + } + +/** + * testPkInHAbtmLinkModelArticleB + * + * @return void + */ + public function testPkInHabtmLinkModelArticleB() { + $this->loadFixtures('Article', 'Tag', 'ArticlesTag'); + $TestModel = new ArticleB(); + $this->assertEquals('article_id', $TestModel->ArticlesTag->primaryKey); + } + +/** + * Tests that $cacheSources can only be disabled in the db using model settings, not enabled + * + * @return void + */ + public function testCacheSourcesDisabling() { + $this->loadFixtures('JoinA', 'JoinB', 'JoinAB', 'JoinC', 'JoinAC'); + $this->db->cacheSources = true; + $TestModel = new JoinA(); + $TestModel->cacheSources = false; + $TestModel->setSource('join_as'); + $this->assertFalse($this->db->cacheSources); + + $this->db->cacheSources = false; + $TestModel = new JoinA(); + $TestModel->cacheSources = true; + $TestModel->setSource('join_as'); + $this->assertFalse($this->db->cacheSources); + } + +/** + * testPkInHabtmLinkModel method + * + * @return void + */ + public function testPkInHabtmLinkModel() { + //Test Nonconformant Models + $this->loadFixtures('Content', 'ContentAccount', 'Account', 'JoinC', 'JoinAC', 'ItemsPortfolio'); + $TestModel = new Content(); + $this->assertEquals('iContentAccountsId', $TestModel->ContentAccount->primaryKey); + + //test conformant models with no PK in the join table + $this->loadFixtures('Article', 'Tag'); + $TestModel = new Article(); + $this->assertEquals('article_id', $TestModel->ArticlesTag->primaryKey); + + //test conformant models with PK in join table + $TestModel = new Portfolio(); + $this->assertEquals('id', $TestModel->ItemsPortfolio->primaryKey); + + //test conformant models with PK in join table - join table contains extra field + $this->loadFixtures('JoinA', 'JoinB', 'JoinAB'); + $TestModel = new JoinA(); + $this->assertEquals('id', $TestModel->JoinAsJoinB->primaryKey); + } + +/** + * testDynamicBehaviorAttachment method + * + * @return void + */ + public function testDynamicBehaviorAttachment() { + $this->loadFixtures('Apple', 'Sample', 'Author'); + $TestModel = new Apple(); + $this->assertEquals(array(), $TestModel->Behaviors->attached()); + + $TestModel->Behaviors->attach('Tree', array('left' => 'left_field', 'right' => 'right_field')); + $this->assertTrue(is_object($TestModel->Behaviors->Tree)); + $this->assertEquals(array('Tree'), $TestModel->Behaviors->attached()); + + $expected = array( + 'parent' => 'parent_id', + 'left' => 'left_field', + 'right' => 'right_field', + 'scope' => '1 = 1', + 'type' => 'nested', + '__parentChange' => false, + 'recursive' => -1 + ); + $this->assertEquals($expected, $TestModel->Behaviors->Tree->settings['Apple']); + + $TestModel->Behaviors->attach('Tree', array('enabled' => false)); + $this->assertEquals($expected, $TestModel->Behaviors->Tree->settings['Apple']); + $this->assertEquals(array('Tree'), $TestModel->Behaviors->attached()); + + $TestModel->Behaviors->detach('Tree'); + $this->assertEquals(array(), $TestModel->Behaviors->attached()); + $this->assertFalse(isset($TestModel->Behaviors->Tree)); + } + +/** + * testFindWithJoinsOption method + * + * @access public + * @return void + */ + public function testFindWithJoinsOption() { + $this->loadFixtures('Article', 'User'); + $TestUser = new User(); + + $options = array( + 'fields' => array( + 'user', + 'Article.published', + ), + 'joins' => array( + array( + 'table' => 'articles', + 'alias' => 'Article', + 'type' => 'LEFT', + 'conditions' => array( + 'User.id = Article.user_id', + ), + ), + ), + 'group' => array('User.user', 'Article.published'), + 'recursive' => -1, + 'order' => array('User.user') + ); + $result = $TestUser->find('all', $options); + $expected = array( + array('User' => array('user' => 'garrett'), 'Article' => array('published' => '')), + array('User' => array('user' => 'larry'), 'Article' => array('published' => 'Y')), + array('User' => array('user' => 'mariano'), 'Article' => array('published' => 'Y')), + array('User' => array('user' => 'nate'), 'Article' => array('published' => '')) + ); + $this->assertEquals($expected, $result); + } + +/** + * Tests cross database joins. Requires $test and $test2 to both be set in DATABASE_CONFIG + * NOTE: When testing on MySQL, you must set 'persistent' => false on *both* database connections, + * or one connection will step on the other. + */ + public function testCrossDatabaseJoins() { + $config = ConnectionManager::enumConnectionObjects(); + + $skip = (!isset($config['test']) || !isset($config['test2'])); + if ($skip) { + $this->markTestSkipped('Primary and secondary test databases not configured, skipping cross-database + join tests. To run theses tests defined $test and $test2 in your database configuration.' + ); + } + + $this->loadFixtures('Article', 'Tag', 'ArticlesTag', 'User', 'Comment'); + $TestModel = new Article(); + + $expected = array( + array( + 'Article' => array( + 'id' => '1', + 'user_id' => '1', + 'title' => 'First Article', + 'body' => 'First Article Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:39:23', + 'updated' => '2007-03-18 10:41:31' + ), + 'User' => array( + 'id' => '1', + 'user' => 'mariano', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', + 'updated' => '2007-03-17 01:18:31' + ), + 'Comment' => array( + array( + 'id' => '1', + 'article_id' => '1', + 'user_id' => '2', + 'comment' => 'First Comment for First Article', + 'published' => 'Y', + 'created' => '2007-03-18 10:45:23', + 'updated' => '2007-03-18 10:47:31' + ), + array( + 'id' => '2', + 'article_id' => '1', + 'user_id' => '4', + 'comment' => 'Second Comment for First Article', + 'published' => 'Y', + 'created' => '2007-03-18 10:47:23', + 'updated' => '2007-03-18 10:49:31' + ), + array( + 'id' => '3', + 'article_id' => '1', + 'user_id' => '1', + 'comment' => 'Third Comment for First Article', + 'published' => 'Y', + 'created' => '2007-03-18 10:49:23', + 'updated' => '2007-03-18 10:51:31' + ), + array( + 'id' => '4', + 'article_id' => '1', + 'user_id' => '1', + 'comment' => 'Fourth Comment for First Article', + 'published' => 'N', + 'created' => '2007-03-18 10:51:23', + 'updated' => '2007-03-18 10:53:31' + )), + 'Tag' => array( + array( + 'id' => '1', + 'tag' => 'tag1', + 'created' => '2007-03-18 12:22:23', + 'updated' => '2007-03-18 12:24:31' + ), + array( + 'id' => '2', + 'tag' => 'tag2', + 'created' => '2007-03-18 12:24:23', + 'updated' => '2007-03-18 12:26:31' + ))), + array( + 'Article' => array( + 'id' => '2', + 'user_id' => '3', + 'title' => 'Second Article', + 'body' => 'Second Article Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:41:23', + 'updated' => '2007-03-18 10:43:31' + ), + 'User' => array( + 'id' => '3', + 'user' => 'larry', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:20:23', + 'updated' => '2007-03-17 01:22:31' + ), + 'Comment' => array( + array( + 'id' => '5', + 'article_id' => '2', + 'user_id' => '1', + 'comment' => 'First Comment for Second Article', + 'published' => 'Y', + 'created' => '2007-03-18 10:53:23', + 'updated' => '2007-03-18 10:55:31' + ), + array( + 'id' => '6', + 'article_id' => '2', + 'user_id' => '2', + 'comment' => 'Second Comment for Second Article', + 'published' => 'Y', + 'created' => '2007-03-18 10:55:23', + 'updated' => '2007-03-18 10:57:31' + )), + 'Tag' => array( + array( + 'id' => '1', + 'tag' => 'tag1', + 'created' => '2007-03-18 12:22:23', + 'updated' => '2007-03-18 12:24:31' + ), + array( + 'id' => '3', + 'tag' => 'tag3', + 'created' => '2007-03-18 12:26:23', + 'updated' => '2007-03-18 12:28:31' + ))), + array( + 'Article' => array( + 'id' => '3', + 'user_id' => '1', + 'title' => 'Third Article', + 'body' => 'Third Article Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:43:23', + 'updated' => '2007-03-18 10:45:31' + ), + 'User' => array( + 'id' => '1', + 'user' => 'mariano', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', + 'updated' => '2007-03-17 01:18:31' + ), + 'Comment' => array(), + 'Tag' => array() + )); + $this->assertEquals($expected, $TestModel->find('all')); + + $db2 = ConnectionManager::getDataSource('test2'); + $this->fixtureManager->loadSingle('User', $db2); + $this->fixtureManager->loadSingle('Comment', $db2); + $this->assertEquals(3, $TestModel->find('count')); + + $TestModel->User->setDataSource('test2'); + $TestModel->Comment->setDataSource('test2'); + + foreach ($expected as $key => $value) { + unset($value['Comment'], $value['Tag']); + $expected[$key] = $value; + } + + $TestModel->recursive = 0; + $result = $TestModel->find('all'); + $this->assertEquals($expected, $result); + + foreach ($expected as $key => $value) { + unset($value['Comment'], $value['Tag']); + $expected[$key] = $value; + } + + $TestModel->recursive = 0; + $result = $TestModel->find('all'); + $this->assertEquals($expected, $result); + + $result = Hash::extract($TestModel->User->find('all'), '{n}.User.id'); + $this->assertEquals(array('1', '2', '3', '4'), $result); + $this->assertEquals($expected, $TestModel->find('all')); + + $TestModel->Comment->unbindModel(array('hasOne' => array('Attachment'))); + $expected = array( + array( + 'Comment' => array( + 'id' => '1', + 'article_id' => '1', + 'user_id' => '2', + 'comment' => 'First Comment for First Article', + 'published' => 'Y', + 'created' => '2007-03-18 10:45:23', + 'updated' => '2007-03-18 10:47:31' + ), + 'User' => array( + 'id' => '2', + 'user' => 'nate', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:18:23', + 'updated' => '2007-03-17 01:20:31' + ), + 'Article' => array( + 'id' => '1', + 'user_id' => '1', + 'title' => 'First Article', + 'body' => 'First Article Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:39:23', + 'updated' => '2007-03-18 10:41:31' + )), + array( + 'Comment' => array( + 'id' => '2', + 'article_id' => '1', + 'user_id' => '4', + 'comment' => 'Second Comment for First Article', + 'published' => 'Y', + 'created' => '2007-03-18 10:47:23', + 'updated' => '2007-03-18 10:49:31' + ), + 'User' => array( + 'id' => '4', + 'user' => 'garrett', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:22:23', + 'updated' => '2007-03-17 01:24:31' + ), + 'Article' => array( + 'id' => '1', + 'user_id' => '1', + 'title' => 'First Article', + 'body' => 'First Article Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:39:23', + 'updated' => '2007-03-18 10:41:31' + )), + array( + 'Comment' => array( + 'id' => '3', + 'article_id' => '1', + 'user_id' => '1', + 'comment' => 'Third Comment for First Article', + 'published' => 'Y', + 'created' => '2007-03-18 10:49:23', + 'updated' => '2007-03-18 10:51:31' + ), + 'User' => array( + 'id' => '1', + 'user' => 'mariano', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', + 'updated' => '2007-03-17 01:18:31' + ), + 'Article' => array( + 'id' => '1', + 'user_id' => '1', + 'title' => 'First Article', + 'body' => 'First Article Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:39:23', + 'updated' => '2007-03-18 10:41:31' + )), + array( + 'Comment' => array( + 'id' => '4', + 'article_id' => '1', + 'user_id' => '1', + 'comment' => 'Fourth Comment for First Article', + 'published' => 'N', + 'created' => '2007-03-18 10:51:23', + 'updated' => '2007-03-18 10:53:31' + ), + 'User' => array( + 'id' => '1', + 'user' => 'mariano', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', + 'updated' => '2007-03-17 01:18:31' + ), + 'Article' => array( + 'id' => '1', + 'user_id' => '1', + 'title' => 'First Article', + 'body' => 'First Article Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:39:23', + 'updated' => '2007-03-18 10:41:31' + )), + array( + 'Comment' => array( + 'id' => '5', + 'article_id' => '2', + 'user_id' => '1', + 'comment' => 'First Comment for Second Article', + 'published' => 'Y', + 'created' => '2007-03-18 10:53:23', + 'updated' => '2007-03-18 10:55:31' + ), + 'User' => array( + 'id' => '1', + 'user' => 'mariano', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', + 'updated' => '2007-03-17 01:18:31' + ), + 'Article' => array( + 'id' => '2', + 'user_id' => '3', + 'title' => 'Second Article', + 'body' => 'Second Article Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:41:23', + 'updated' => '2007-03-18 10:43:31' + )), + array( + 'Comment' => array( + 'id' => '6', + 'article_id' => '2', + 'user_id' => '2', + 'comment' => 'Second Comment for Second Article', + 'published' => 'Y', + 'created' => '2007-03-18 10:55:23', + 'updated' => '2007-03-18 10:57:31' + ), + 'User' => array( + 'id' => '2', + 'user' => 'nate', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:18:23', + 'updated' => '2007-03-17 01:20:31' + ), + 'Article' => array( + 'id' => '2', + 'user_id' => '3', + 'title' => 'Second Article', + 'body' => 'Second Article Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:41:23', + 'updated' => '2007-03-18 10:43:31' + ))); + $this->assertEquals($expected, $TestModel->Comment->find('all')); + } + +/** + * test HABM operations without clobbering existing records #275 + * + * @return void + */ + public function testHABTMKeepExisting() { + $this->loadFixtures('Site', 'Domain', 'DomainsSite'); + + $Site = new Site(); + $results = $Site->find('count'); + $expected = 3; + $this->assertEquals($expected, $results); + + $data = $Site->findById(1); + + // include api.cakephp.org + $data['Domain'] = array('Domain' => array(1, 2, 3)); + $Site->save($data); + + $Site->id = 1; + $results = $Site->read(); + $expected = 3; // 3 domains belonging to cakephp + $this->assertEquals($expected, count($results['Domain'])); + + $Site->id = 2; + $results = $Site->read(); + $expected = 2; // 2 domains belonging to markstory + $this->assertEquals($expected, count($results['Domain'])); + + $Site->id = 3; + $results = $Site->read(); + $expected = 2; + $this->assertEquals($expected, count($results['Domain'])); + $results['Domain'] = array('Domain' => array(7)); + $Site->save($results); // remove association from domain 6 + $results = $Site->read(); + $expected = 1; // only 1 domain left belonging to rchavik + $this->assertEquals($expected, count($results['Domain'])); + + // add deleted domain back + $results['Domain'] = array('Domain' => array(6, 7)); + $Site->save($results); + $results = $Site->read(); + $expected = 2; // 2 domains belonging to rchavik + $this->assertEquals($expected, count($results['Domain'])); + + $Site->DomainsSite->id = $results['Domain'][0]['DomainsSite']['id']; + $Site->DomainsSite->saveField('active', true); + + $results = $Site->Domain->DomainsSite->find('count', array( + 'conditions' => array( + 'DomainsSite.active' => true, + ), + )); + $expected = 5; + $this->assertEquals($expected, $results); + + // activate api.cakephp.org + $activated = $Site->DomainsSite->findByDomainId(3); + $activated['DomainsSite']['active'] = true; + $Site->DomainsSite->save($activated); + + $results = $Site->DomainsSite->find('count', array( + 'conditions' => array( + 'DomainsSite.active' => true, + ), + )); + $expected = 6; + $this->assertEquals($expected, $results); + + // remove 2 previously active domains, and leave $activated alone + $data = array( + 'Site' => array('id' => 1, 'name' => 'cakephp (modified)'), + 'Domain' => array( + 'Domain' => array(3), + ) + ); + $Site->create($data); + $Site->save($data); + + // tests that record is still identical prior to removal + $Site->id = 1; + $results = $Site->read(); + unset($results['Domain'][0]['DomainsSite']['updated']); + unset($activated['DomainsSite']['updated']); + $this->assertEquals($activated['DomainsSite'], $results['Domain'][0]['DomainsSite']); + } + +/** + * testHABTMKeepExistingAlternateDataFormat + * + * @return void + */ + public function testHABTMKeepExistingAlternateDataFormat() { + $this->loadFixtures('Site', 'Domain', 'DomainsSite'); + + $Site = new Site(); + + $expected = array( + array( + 'DomainsSite' => array( + 'id' => 1, + 'site_id' => 1, + 'domain_id' => 1, + 'active' => true, + 'created' => '2007-03-17 01:16:23' + ) + ), + array( + 'DomainsSite' => array( + 'id' => 2, + 'site_id' => 1, + 'domain_id' => 2, + 'active' => true, + 'created' => '2007-03-17 01:16:23' + ) + ) + ); + $result = $Site->DomainsSite->find('all', array( + 'conditions' => array('DomainsSite.site_id' => 1), + 'fields' => array( + 'DomainsSite.id', + 'DomainsSite.site_id', + 'DomainsSite.domain_id', + 'DomainsSite.active', + 'DomainsSite.created' + ), + 'order' => 'DomainsSite.id' + )); + $this->assertEquals($expected, $result); + + $time = date('Y-m-d H:i:s'); + $data = array( + 'Site' => array( + 'id' => 1 + ), + 'Domain' => array( + array( + 'site_id' => 1, + 'domain_id' => 3, + 'created' => $time, + ), + array( + 'id' => 2, + 'site_id' => 1, + 'domain_id' => 2 + ), + ) + ); + $Site->save($data); + $expected = array( + array( + 'DomainsSite' => array( + 'id' => 2, + 'site_id' => 1, + 'domain_id' => 2, + 'active' => true, + 'created' => '2007-03-17 01:16:23' + ) + ), + array( + 'DomainsSite' => array( + 'id' => 7, + 'site_id' => 1, + 'domain_id' => 3, + 'active' => false, + 'created' => $time + ) + ) + ); + $result = $Site->DomainsSite->find('all', array( + 'conditions' => array('DomainsSite.site_id' => 1), + 'fields' => array( + 'DomainsSite.id', + 'DomainsSite.site_id', + 'DomainsSite.domain_id', + 'DomainsSite.active', + 'DomainsSite.created' + ), + 'order' => 'DomainsSite.id' + )); + $this->assertEquals($expected, $result); + } + +/** + * test HABM operations without clobbering existing records #275 + * + * @return void + */ + public function testHABTMKeepExistingWithThreeDbs() { + $config = ConnectionManager::enumConnectionObjects(); + $this->skipIf($this->db instanceof Sqlite, 'This test is not compatible with Sqlite.'); + $this->skipIf( + !isset($config['test']) || !isset($config['test2']) || !isset($config['test_database_three']), + 'Primary, secondary, and tertiary test databases not configured, skipping test. To run this test define $test, $test2, and $test_database_three in your database configuration.' + ); + + $this->loadFixtures('Player', 'Guild', 'GuildsPlayer', 'Armor', 'ArmorsPlayer'); + $Player = ClassRegistry::init('Player'); + $Player->bindModel(array( + 'hasAndBelongsToMany' => array( + 'Armor' => array( + 'with' => 'ArmorsPlayer', + 'unique' => 'keepExisting', + ), + ), + ), false); + $this->assertEquals('test', $Player->useDbConfig); + $this->assertEquals('test', $Player->Guild->useDbConfig); + $this->assertEquals('test2', $Player->Guild->GuildsPlayer->useDbConfig); + $this->assertEquals('test2', $Player->Armor->useDbConfig); + $this->assertEquals('test_database_three', $Player->ArmorsPlayer->useDbConfig); + + $players = $Player->find('all'); + $this->assertEquals(4 , count($players)); + $playersGuilds = Hash::extract($players, '{n}.Guild.{n}.GuildsPlayer'); + $this->assertEquals(3 , count($playersGuilds)); + $playersArmors = Hash::extract($players, '{n}.Armor.{n}.ArmorsPlayer'); + $this->assertEquals(3 , count($playersArmors)); + unset($players); + + $larry = $Player->findByName('larry'); + $larrysArmor = Hash::extract($larry, 'Armor.{n}.ArmorsPlayer'); + $this->assertEquals(1 , count($larrysArmor)); + + $larry['Guild']['Guild'] = array(1, 3); // larry joins another guild + $larry['Armor']['Armor'] = array(2, 3); // purchases chainmail + $Player->save($larry); + unset($larry); + + $larry = $Player->findByName('larry'); + $larrysGuild = Hash::extract($larry, 'Guild.{n}.GuildsPlayer'); + $this->assertEquals(2 , count($larrysGuild)); + $larrysArmor = Hash::extract($larry, 'Armor.{n}.ArmorsPlayer'); + $this->assertEquals(2 , count($larrysArmor)); + + $larrysArmorsPlayersIds = Hash::extract($larry, 'Armor.{n}.ArmorsPlayer.id'); + + $Player->ArmorsPlayer->id = 3; + $Player->ArmorsPlayer->saveField('broken', true); // larry's cloak broke + + $larry = $Player->findByName('larry'); + $larrysCloak = Hash::extract($larry, 'Armor.{n}.ArmorsPlayer[armor_id=3]', $larry); + $this->assertNotEmpty($larrysCloak); + $this->assertTrue($larrysCloak[0]['broken']); // still broken + } + +/** + * testDisplayField method + * + * @return void + */ + public function testDisplayField() { + $this->loadFixtures('Post', 'Comment', 'Person', 'User'); + $Post = new Post(); + $Comment = new Comment(); + $Person = new Person(); + + $this->assertEquals('title', $Post->displayField); + $this->assertEquals('name', $Person->displayField); + $this->assertEquals('id', $Comment->displayField); + } + +/** + * testSchema method + * + * @return void + */ + public function testSchema() { + $Post = new Post(); + + $result = $Post->schema(); + $columns = array('id', 'author_id', 'title', 'body', 'published', 'created', 'updated'); + $this->assertEquals($columns, array_keys($result)); + + $types = array('integer', 'integer', 'string', 'text', 'string', 'datetime', 'datetime'); + $this->assertEquals(Hash::extract(array_values($result), '{n}.type'), $types); + + $result = $Post->schema('body'); + $this->assertEquals('text', $result['type']); + $this->assertNull($Post->schema('foo')); + + $this->assertEquals($Post->getColumnTypes(), array_combine($columns, $types)); + } + +/** + * data provider for time tests. + * + * @return array + */ + public static function timeProvider() { + $db = ConnectionManager::getDataSource('test'); + $now = $db->expression('NOW()'); + return array( + // blank + array( + array('hour' => '', 'min' => '', 'meridian' => ''), + '' + ), + // missing hour + array( + array('hour' => '', 'min' => '00', 'meridian' => 'pm'), + '' + ), + // all blank + array( + array('hour' => '', 'min' => '', 'sec' => ''), + '' + ), + // set and empty merdian + array( + array('hour' => '1', 'min' => '00', 'meridian' => ''), + '' + ), + // midnight + array( + array('hour' => '12', 'min' => '0', 'meridian' => 'am'), + '00:00:00' + ), + array( + array('hour' => '00', 'min' => '00'), + '00:00:00' + ), + // 3am + array( + array('hour' => '03', 'min' => '04', 'sec' => '04'), + '03:04:04' + ), + array( + array('hour' => '3', 'min' => '4', 'sec' => '4'), + '03:04:04' + ), + array( + array('hour' => '03', 'min' => '4', 'sec' => '4'), + '03:04:04' + ), + array( + $now, + $now + ) + ); + } + +/** + * test deconstruct with time fields. + * + * @dataProvider timeProvider + * @return void + */ + public function testDeconstructFieldsTime($input, $result) { + $this->skipIf($this->db instanceof Sqlserver, 'This test is not compatible with SQL Server.'); + + $this->loadFixtures('Apple'); + $TestModel = new Apple(); + + $data = array( + 'Apple' => array( + 'mytime' => $input + ) + ); + + $TestModel->data = null; + $TestModel->set($data); + $expected = array('Apple' => array('mytime' => $result)); + $this->assertEquals($expected, $TestModel->data); + } + +/** + * testDeconstructFields with datetime, timestamp, and date fields + * + * @return void + */ + public function testDeconstructFieldsDateTime() { + $this->skipIf($this->db instanceof Sqlserver, 'This test is not compatible with SQL Server.'); + + $this->loadFixtures('Apple'); + $TestModel = new Apple(); + + //test null/empty values first + $data['Apple']['created']['year'] = ''; + $data['Apple']['created']['month'] = ''; + $data['Apple']['created']['day'] = ''; + $data['Apple']['created']['hour'] = ''; + $data['Apple']['created']['min'] = ''; + $data['Apple']['created']['sec'] = ''; + + $TestModel->data = null; + $TestModel->set($data); + $expected = array('Apple' => array('created' => '')); + $this->assertEquals($expected, $TestModel->data); + + $data = array(); + $data['Apple']['date']['year'] = ''; + $data['Apple']['date']['month'] = ''; + $data['Apple']['date']['day'] = ''; + + $TestModel->data = null; + $TestModel->set($data); + $expected = array('Apple' => array('date' => '')); + $this->assertEquals($expected, $TestModel->data); + + $data = array(); + $data['Apple']['created']['year'] = '2007'; + $data['Apple']['created']['month'] = '08'; + $data['Apple']['created']['day'] = '20'; + $data['Apple']['created']['hour'] = ''; + $data['Apple']['created']['min'] = ''; + $data['Apple']['created']['sec'] = ''; + + $TestModel->data = null; + $TestModel->set($data); + $expected = array('Apple' => array('created' => '2007-08-20 00:00:00')); + $this->assertEquals($expected, $TestModel->data); + + $data = array(); + $data['Apple']['created']['year'] = '2007'; + $data['Apple']['created']['month'] = '08'; + $data['Apple']['created']['day'] = '20'; + $data['Apple']['created']['hour'] = '10'; + $data['Apple']['created']['min'] = '12'; + $data['Apple']['created']['sec'] = ''; + + $TestModel->data = null; + $TestModel->set($data); + $expected = array('Apple' => array('created' => '2007-08-20 10:12:00')); + $this->assertEquals($expected, $TestModel->data); + + $data = array(); + $data['Apple']['created']['year'] = '2007'; + $data['Apple']['created']['month'] = ''; + $data['Apple']['created']['day'] = '12'; + $data['Apple']['created']['hour'] = '20'; + $data['Apple']['created']['min'] = ''; + $data['Apple']['created']['sec'] = ''; + + $TestModel->data = null; + $TestModel->set($data); + $expected = array('Apple' => array('created' => '')); + $this->assertEquals($expected, $TestModel->data); + + $data = array(); + $data['Apple']['created']['hour'] = '20'; + $data['Apple']['created']['min'] = '33'; + + $TestModel->data = null; + $TestModel->set($data); + $expected = array('Apple' => array('created' => '')); + $this->assertEquals($expected, $TestModel->data); + + $data = array(); + $data['Apple']['created']['hour'] = '20'; + $data['Apple']['created']['min'] = '33'; + $data['Apple']['created']['sec'] = '33'; + + $TestModel->data = null; + $TestModel->set($data); + $expected = array('Apple' => array('created' => '')); + $this->assertEquals($expected, $TestModel->data); + + $data = array(); + $data['Apple']['created']['hour'] = '13'; + $data['Apple']['created']['min'] = '00'; + $data['Apple']['date']['year'] = '2006'; + $data['Apple']['date']['month'] = '12'; + $data['Apple']['date']['day'] = '25'; + + $TestModel->data = null; + $TestModel->set($data); + $expected = array( + 'Apple' => array( + 'created' => '', + 'date' => '2006-12-25' + )); + $this->assertEquals($expected, $TestModel->data); + + $data = array(); + $data['Apple']['created']['year'] = '2007'; + $data['Apple']['created']['month'] = '08'; + $data['Apple']['created']['day'] = '20'; + $data['Apple']['created']['hour'] = '10'; + $data['Apple']['created']['min'] = '12'; + $data['Apple']['created']['sec'] = '09'; + $data['Apple']['date']['year'] = '2006'; + $data['Apple']['date']['month'] = '12'; + $data['Apple']['date']['day'] = '25'; + + $TestModel->data = null; + $TestModel->set($data); + $expected = array( + 'Apple' => array( + 'created' => '2007-08-20 10:12:09', + 'date' => '2006-12-25' + )); + $this->assertEquals($expected, $TestModel->data); + + $data = array(); + $data['Apple']['created']['year'] = '--'; + $data['Apple']['created']['month'] = '--'; + $data['Apple']['created']['day'] = '--'; + $data['Apple']['created']['hour'] = '--'; + $data['Apple']['created']['min'] = '--'; + $data['Apple']['created']['sec'] = '--'; + $data['Apple']['date']['year'] = '--'; + $data['Apple']['date']['month'] = '--'; + $data['Apple']['date']['day'] = '--'; + + $TestModel->data = null; + $TestModel->set($data); + $expected = array('Apple' => array('created' => '', 'date' => '')); + $this->assertEquals($expected, $TestModel->data); + + $data = array(); + $data['Apple']['created']['year'] = '2007'; + $data['Apple']['created']['month'] = '--'; + $data['Apple']['created']['day'] = '20'; + $data['Apple']['created']['hour'] = '10'; + $data['Apple']['created']['min'] = '12'; + $data['Apple']['created']['sec'] = '09'; + $data['Apple']['date']['year'] = '2006'; + $data['Apple']['date']['month'] = '12'; + $data['Apple']['date']['day'] = '25'; + + $TestModel->data = null; + $TestModel->set($data); + $expected = array('Apple' => array('created' => '', 'date' => '2006-12-25')); + $this->assertEquals($expected, $TestModel->data); + + $data = array(); + $data['Apple']['date']['year'] = '2006'; + $data['Apple']['date']['month'] = '12'; + $data['Apple']['date']['day'] = '25'; + + $TestModel->data = null; + $TestModel->set($data); + $expected = array('Apple' => array('date' => '2006-12-25')); + $this->assertEquals($expected, $TestModel->data); + + $db = ConnectionManager::getDataSource('test'); + $data = array(); + $data['Apple']['modified'] = $db->expression('NOW()'); + $TestModel->data = null; + $TestModel->set($data); + $this->assertEquals($TestModel->data, $data); + } + +/** + * testTablePrefixSwitching method + * + * @return void + */ + public function testTablePrefixSwitching() { + ConnectionManager::create('database1', + array_merge($this->db->config, array('prefix' => 'aaa_') + )); + ConnectionManager::create('database2', + array_merge($this->db->config, array('prefix' => 'bbb_') + )); + + $db1 = ConnectionManager::getDataSource('database1'); + $db2 = ConnectionManager::getDataSource('database2'); + + $TestModel = new Apple(); + $TestModel->setDataSource('database1'); + $this->assertContains('aaa_apples', $this->db->fullTableName($TestModel)); + $this->assertContains('aaa_apples', $db1->fullTableName($TestModel)); + $this->assertContains('aaa_apples', $db2->fullTableName($TestModel)); + + $TestModel->setDataSource('database2'); + $this->assertContains('bbb_apples', $this->db->fullTableName($TestModel)); + $this->assertContains('bbb_apples', $db1->fullTableName($TestModel)); + $this->assertContains('bbb_apples', $db2->fullTableName($TestModel)); + + $TestModel = new Apple(); + $TestModel->tablePrefix = 'custom_'; + $this->assertContains('custom_apples', $this->db->fullTableName($TestModel)); + $TestModel->setDataSource('database1'); + $this->assertContains('custom_apples', $this->db->fullTableName($TestModel)); + $this->assertContains('custom_apples', $db1->fullTableName($TestModel)); + + $TestModel = new Apple(); + $TestModel->setDataSource('database1'); + $this->assertContains('aaa_apples', $this->db->fullTableName($TestModel)); + $TestModel->tablePrefix = ''; + $TestModel->setDataSource('database2'); + $this->assertContains('apples', $db2->fullTableName($TestModel)); + $this->assertContains('apples', $db1->fullTableName($TestModel)); + + $TestModel->tablePrefix = null; + $TestModel->setDataSource('database1'); + $this->assertContains('aaa_apples', $db2->fullTableName($TestModel)); + $this->assertContains('aaa_apples', $db1->fullTableName($TestModel)); + + $TestModel->tablePrefix = false; + $TestModel->setDataSource('database2'); + $this->assertContains('apples', $db2->fullTableName($TestModel)); + $this->assertContains('apples', $db1->fullTableName($TestModel)); + } + +/** + * Tests validation parameter order in custom validation methods + * + * @return void + */ + public function testInvalidAssociation() { + $TestModel = new ValidationTest1(); + $this->assertNull($TestModel->getAssociated('Foo')); + } + +/** + * testLoadModelSecondIteration method + * + * @return void + */ + public function testLoadModelSecondIteration() { + $this->loadFixtures('Apple', 'Message', 'Thread', 'Bid'); + $model = new ModelA(); + $this->assertInstanceOf('ModelA', $model); + + $this->assertInstanceOf('ModelB', $model->ModelB); + $this->assertInstanceOf('ModelD', $model->ModelB->ModelD); + + $this->assertInstanceOf('ModelC', $model->ModelC); + $this->assertInstanceOf('ModelD', $model->ModelC->ModelD); + } + +/** + * ensure that exists() does not persist between method calls reset on create + * + * @return void + */ + public function testResetOfExistsOnCreate() { + $this->loadFixtures('Article'); + $Article = new Article(); + $Article->id = 1; + $Article->saveField('title', 'Reset me'); + $Article->delete(); + $Article->id = 1; + $this->assertFalse($Article->exists()); + + $Article->create(); + $this->assertFalse($Article->exists()); + $Article->id = 2; + $Article->saveField('title', 'Staying alive'); + $result = $Article->read(null, 2); + $this->assertEquals('Staying alive', $result['Article']['title']); + } + +/** + * testUseTableFalseExistsCheck method + * + * @return void + */ + public function testUseTableFalseExistsCheck() { + $this->loadFixtures('Article'); + $Article = new Article(); + $Article->id = 1337; + $result = $Article->exists(); + $this->assertFalse($result); + + $Article->useTable = false; + $Article->id = null; + $result = $Article->exists(); + $this->assertFalse($result); + + // An article with primary key of '1' has been loaded by the fixtures. + $Article->useTable = false; + $Article->id = 1; + $result = $Article->exists(); + $this->assertTrue($result); + } + +/** + * testPluginAssociations method + * + * @return void + */ + public function testPluginAssociations() { + $this->loadFixtures('TestPluginArticle', 'User', 'TestPluginComment'); + $TestModel = new TestPluginArticle(); + + $result = $TestModel->find('all'); + $expected = array( + array( + 'TestPluginArticle' => array( + 'id' => 1, + 'user_id' => 1, + 'title' => 'First Plugin Article', + 'body' => 'First Plugin Article Body', + 'published' => 'Y', + 'created' => '2008-09-24 10:39:23', + 'updated' => '2008-09-24 10:41:31' + ), + 'User' => array( + 'id' => 1, + 'user' => 'mariano', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', + 'updated' => '2007-03-17 01:18:31' + ), + 'TestPluginComment' => array( + array( + 'id' => 1, + 'article_id' => 1, + 'user_id' => 2, + 'comment' => 'First Comment for First Plugin Article', + 'published' => 'Y', + 'created' => '2008-09-24 10:45:23', + 'updated' => '2008-09-24 10:47:31' + ), + array( + 'id' => 2, + 'article_id' => 1, + 'user_id' => 4, + 'comment' => 'Second Comment for First Plugin Article', + 'published' => 'Y', + 'created' => '2008-09-24 10:47:23', + 'updated' => '2008-09-24 10:49:31' + ), + array( + 'id' => 3, + 'article_id' => 1, + 'user_id' => 1, + 'comment' => 'Third Comment for First Plugin Article', + 'published' => 'Y', + 'created' => '2008-09-24 10:49:23', + 'updated' => '2008-09-24 10:51:31' + ), + array( + 'id' => 4, + 'article_id' => 1, + 'user_id' => 1, + 'comment' => 'Fourth Comment for First Plugin Article', + 'published' => 'N', + 'created' => '2008-09-24 10:51:23', + 'updated' => '2008-09-24 10:53:31' + ))), + array( + 'TestPluginArticle' => array( + 'id' => 2, + 'user_id' => 3, + 'title' => 'Second Plugin Article', + 'body' => 'Second Plugin Article Body', + 'published' => 'Y', + 'created' => '2008-09-24 10:41:23', + 'updated' => '2008-09-24 10:43:31' + ), + 'User' => array( + 'id' => 3, + 'user' => 'larry', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:20:23', + 'updated' => '2007-03-17 01:22:31' + ), + 'TestPluginComment' => array( + array( + 'id' => 5, + 'article_id' => 2, + 'user_id' => 1, + 'comment' => 'First Comment for Second Plugin Article', + 'published' => 'Y', + 'created' => '2008-09-24 10:53:23', + 'updated' => '2008-09-24 10:55:31' + ), + array( + 'id' => 6, + 'article_id' => 2, + 'user_id' => 2, + 'comment' => 'Second Comment for Second Plugin Article', + 'published' => 'Y', + 'created' => '2008-09-24 10:55:23', + 'updated' => '2008-09-24 10:57:31' + ))), + array( + 'TestPluginArticle' => array( + 'id' => 3, + 'user_id' => 1, + 'title' => 'Third Plugin Article', + 'body' => 'Third Plugin Article Body', + 'published' => 'Y', + 'created' => '2008-09-24 10:43:23', + 'updated' => '2008-09-24 10:45:31' + ), + 'User' => array( + 'id' => 1, + 'user' => 'mariano', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', + 'updated' => '2007-03-17 01:18:31' + ), + 'TestPluginComment' => array() + )); + + $this->assertEquals($expected, $result); + } + +/** + * Tests getAssociated method + * + * @return void + */ + public function testGetAssociated() { + $this->loadFixtures('Article', 'Tag'); + $Article = ClassRegistry::init('Article'); + + $assocTypes = array('hasMany', 'hasOne', 'belongsTo', 'hasAndBelongsToMany'); + foreach ($assocTypes as $type) { + $this->assertEquals($Article->getAssociated($type), array_keys($Article->{$type})); + } + + $Article->bindModel(array('hasMany' => array('Category'))); + $this->assertEquals(array('Comment', 'Category'), $Article->getAssociated('hasMany')); + + $results = $Article->getAssociated(); + $results = array_keys($results); + sort($results); + $this->assertEquals(array('Category', 'Comment', 'Tag', 'User'), $results); + + $Article->unbindModel(array('hasAndBelongsToMany' => array('Tag'))); + $this->assertEquals(array(), $Article->getAssociated('hasAndBelongsToMany')); + + $result = $Article->getAssociated('Category'); + $expected = array( + 'className' => 'Category', + 'foreignKey' => 'article_id', + 'conditions' => '', + 'fields' => '', + 'order' => '', + 'limit' => '', + 'offset' => '', + 'dependent' => '', + 'exclusive' => '', + 'finderQuery' => '', + 'counterQuery' => '', + 'association' => 'hasMany', + ); + $this->assertEquals($expected, $result); + } + +/** + * testAutoConstructAssociations method + * + * @return void + */ + public function testAutoConstructAssociations() { + $this->loadFixtures('User', 'ArticleFeatured', 'Featured', 'ArticleFeaturedsTags'); + $TestModel = new AssociationTest1(); + + $result = $TestModel->hasAndBelongsToMany; + $expected = array('AssociationTest2' => array( + 'unique' => false, + 'joinTable' => 'join_as_join_bs', + 'foreignKey' => false, + 'className' => 'AssociationTest2', + 'with' => 'JoinAsJoinB', + 'dynamicWith' => true, + 'associationForeignKey' => 'join_b_id', + 'conditions' => '', 'fields' => '', 'order' => '', 'limit' => '', 'offset' => '', + 'finderQuery' => '', 'deleteQuery' => '', 'insertQuery' => '' + )); + $this->assertEquals($expected, $result); + + $TestModel = new ArticleFeatured(); + $TestFakeModel = new ArticleFeatured(array('table' => false)); + + $expected = array( + 'User' => array( + 'className' => 'User', 'foreignKey' => 'user_id', + 'conditions' => '', 'fields' => '', 'order' => '', 'counterCache' => '' + ), + 'Category' => array( + 'className' => 'Category', 'foreignKey' => 'category_id', + 'conditions' => '', 'fields' => '', 'order' => '', 'counterCache' => '' + ) + ); + $this->assertSame($TestModel->belongsTo, $expected); + $this->assertSame($TestFakeModel->belongsTo, $expected); + + $this->assertEquals('User', $TestModel->User->name); + $this->assertEquals('User', $TestFakeModel->User->name); + $this->assertEquals('Category', $TestModel->Category->name); + $this->assertEquals('Category', $TestFakeModel->Category->name); + + $expected = array( + 'Featured' => array( + 'className' => 'Featured', + 'foreignKey' => 'article_featured_id', + 'conditions' => '', + 'fields' => '', + 'order' => '', + 'dependent' => '' + )); + + $this->assertSame($TestModel->hasOne, $expected); + $this->assertSame($TestFakeModel->hasOne, $expected); + + $this->assertEquals('Featured', $TestModel->Featured->name); + $this->assertEquals('Featured', $TestFakeModel->Featured->name); + + $expected = array( + 'Comment' => array( + 'className' => 'Comment', + 'dependent' => true, + 'foreignKey' => 'article_featured_id', + 'conditions' => '', + 'fields' => '', + 'order' => '', + 'limit' => '', + 'offset' => '', + 'exclusive' => '', + 'finderQuery' => '', + 'counterQuery' => '' + )); + + $this->assertSame($TestModel->hasMany, $expected); + $this->assertSame($TestFakeModel->hasMany, $expected); + + $this->assertEquals('Comment', $TestModel->Comment->name); + $this->assertEquals('Comment', $TestFakeModel->Comment->name); + + $expected = array( + 'Tag' => array( + 'className' => 'Tag', + 'joinTable' => 'article_featureds_tags', + 'with' => 'ArticleFeaturedsTag', + 'dynamicWith' => true, + 'foreignKey' => 'article_featured_id', + 'associationForeignKey' => 'tag_id', + 'conditions' => '', + 'fields' => '', + 'order' => '', + 'limit' => '', + 'offset' => '', + 'unique' => true, + 'finderQuery' => '', + 'deleteQuery' => '', + 'insertQuery' => '' + )); + + $this->assertSame($TestModel->hasAndBelongsToMany, $expected); + $this->assertSame($TestFakeModel->hasAndBelongsToMany, $expected); + + $this->assertEquals('Tag', $TestModel->Tag->name); + $this->assertEquals('Tag', $TestFakeModel->Tag->name); + } + +/** + * test creating associations with plugins. Ensure a double alias isn't created + * + * @return void + */ + public function testAutoConstructPluginAssociations() { + $Comment = ClassRegistry::init('TestPluginComment'); + + $this->assertEquals(2, count($Comment->belongsTo), 'Too many associations'); + $this->assertFalse(isset($Comment->belongsTo['TestPlugin.User'])); + $this->assertTrue(isset($Comment->belongsTo['User']), 'Missing association'); + $this->assertTrue(isset($Comment->belongsTo['TestPluginArticle']), 'Missing association'); + } + +/** + * test Model::__construct + * + * ensure that $actsAS and $findMethods are merged. + * + * @return void + */ + public function testConstruct() { + $this->loadFixtures('Post'); + + $TestModel = ClassRegistry::init('MergeVarPluginPost'); + $this->assertEquals(array('Containable' => null, 'Tree' => null), $TestModel->actsAs); + $this->assertTrue(isset($TestModel->Behaviors->Containable)); + $this->assertTrue(isset($TestModel->Behaviors->Tree)); + + $TestModel = ClassRegistry::init('MergeVarPluginComment'); + $expected = array('Containable' => array('some_settings')); + $this->assertEquals($expected, $TestModel->actsAs); + $this->assertTrue(isset($TestModel->Behaviors->Containable)); + } + +/** + * test Model::__construct + * + * ensure that $actsAS and $findMethods are merged. + * + * @return void + */ + public function testConstructWithAlternateDataSource() { + $TestModel = ClassRegistry::init(array( + 'class' => 'DoesntMatter', 'ds' => 'test', 'table' => false + )); + $this->assertEquals('test', $TestModel->useDbConfig); + + //deprecated but test it anyway + $NewVoid = new TheVoid(null, false, 'other'); + $this->assertEquals('other', $NewVoid->useDbConfig); + } + +/** + * testColumnTypeFetching method + * + * @return void + */ + public function testColumnTypeFetching() { + $model = new Test(); + $this->assertEquals('integer', $model->getColumnType('id')); + $this->assertEquals('text', $model->getColumnType('notes')); + $this->assertEquals('datetime', $model->getColumnType('updated')); + $this->assertEquals(null, $model->getColumnType('unknown')); + + $model = new Article(); + $this->assertEquals('datetime', $model->getColumnType('User.created')); + $this->assertEquals('integer', $model->getColumnType('Tag.id')); + $this->assertEquals('integer', $model->getColumnType('Article.id')); + } + +/** + * testHabtmUniqueKey method + * + * @return void + */ + public function testHabtmUniqueKey() { + $model = new Item(); + $this->assertFalse($model->hasAndBelongsToMany['Portfolio']['unique']); + } + +/** + * testIdentity method + * + * @return void + */ + public function testIdentity() { + $TestModel = new Test(); + $result = $TestModel->alias; + $expected = 'Test'; + $this->assertEquals($expected, $result); + + $TestModel = new TestAlias(); + $result = $TestModel->alias; + $expected = 'TestAlias'; + $this->assertEquals($expected, $result); + + $TestModel = new Test(array('alias' => 'AnotherTest')); + $result = $TestModel->alias; + $expected = 'AnotherTest'; + $this->assertEquals($expected, $result); + } + +/** + * testWithAssociation method + * + * @return void + */ + public function testWithAssociation() { + $this->loadFixtures('Something', 'SomethingElse', 'JoinThing'); + $TestModel = new Something(); + $result = $TestModel->SomethingElse->find('all'); + + $expected = array( + array( + 'SomethingElse' => array( + 'id' => '1', + 'title' => 'First Post', + 'body' => 'First Post Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:39:23', + 'updated' => '2007-03-18 10:41:31' + ), + 'Something' => array( + array( + 'id' => '3', + 'title' => 'Third Post', + 'body' => 'Third Post Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:43:23', + 'updated' => '2007-03-18 10:45:31', + 'JoinThing' => array( + 'id' => '3', + 'something_id' => '3', + 'something_else_id' => '1', + 'doomed' => true, + 'created' => '2007-03-18 10:43:23', + 'updated' => '2007-03-18 10:45:31' + )))), + array( + 'SomethingElse' => array( + 'id' => '2', + 'title' => 'Second Post', + 'body' => 'Second Post Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:41:23', + 'updated' => '2007-03-18 10:43:31' + ), + 'Something' => array( + array( + 'id' => '1', + 'title' => 'First Post', + 'body' => 'First Post Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:39:23', + 'updated' => '2007-03-18 10:41:31', + 'JoinThing' => array( + 'id' => '1', + 'something_id' => '1', + 'something_else_id' => '2', + 'doomed' => true, + 'created' => '2007-03-18 10:39:23', + 'updated' => '2007-03-18 10:41:31' + )))), + array( + 'SomethingElse' => array( + 'id' => '3', + 'title' => 'Third Post', + 'body' => 'Third Post Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:43:23', + 'updated' => '2007-03-18 10:45:31' + ), + 'Something' => array( + array( + 'id' => '2', + 'title' => 'Second Post', + 'body' => 'Second Post Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:41:23', + 'updated' => '2007-03-18 10:43:31', + 'JoinThing' => array( + 'id' => '2', + 'something_id' => '2', + 'something_else_id' => '3', + 'doomed' => false, + 'created' => '2007-03-18 10:41:23', + 'updated' => '2007-03-18 10:43:31' + ))))); + $this->assertEquals($expected, $result); + + $result = $TestModel->find('all'); + $expected = array( + array( + 'Something' => array( + 'id' => '1', + 'title' => 'First Post', + 'body' => 'First Post Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:39:23', + 'updated' => '2007-03-18 10:41:31' + ), + 'SomethingElse' => array( + array( + 'id' => '2', + 'title' => 'Second Post', + 'body' => 'Second Post Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:41:23', + 'updated' => '2007-03-18 10:43:31', + 'JoinThing' => array( + 'doomed' => true, + 'something_id' => '1', + 'something_else_id' => '2' + )))), + array( + 'Something' => array( + 'id' => '2', + 'title' => 'Second Post', + 'body' => 'Second Post Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:41:23', + 'updated' => '2007-03-18 10:43:31' + ), + 'SomethingElse' => array( + array( + 'id' => '3', + 'title' => 'Third Post', + 'body' => 'Third Post Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:43:23', + 'updated' => '2007-03-18 10:45:31', + 'JoinThing' => array( + 'doomed' => false, + 'something_id' => '2', + 'something_else_id' => '3' + )))), + array( + 'Something' => array( + 'id' => '3', + 'title' => 'Third Post', + 'body' => 'Third Post Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:43:23', + 'updated' => '2007-03-18 10:45:31' + ), + 'SomethingElse' => array( + array( + 'id' => '1', + 'title' => 'First Post', + 'body' => 'First Post Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:39:23', + 'updated' => '2007-03-18 10:41:31', + 'JoinThing' => array( + 'doomed' => true, + 'something_id' => '3', + 'something_else_id' => '1' + ))))); + $this->assertEquals($expected, $result); + + $result = $TestModel->findById(1); + $expected = array( + 'Something' => array( + 'id' => '1', + 'title' => 'First Post', + 'body' => 'First Post Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:39:23', + 'updated' => '2007-03-18 10:41:31' + ), + 'SomethingElse' => array( + array( + 'id' => '2', + 'title' => 'Second Post', + 'body' => 'Second Post Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:41:23', + 'updated' => '2007-03-18 10:43:31', + 'JoinThing' => array( + 'doomed' => true, + 'something_id' => '1', + 'something_else_id' => '2' + )))); + $this->assertEquals($expected, $result); + + $expected = $TestModel->findById(1); + $TestModel->set($expected); + $TestModel->save(); + $result = $TestModel->findById(1); + $this->assertEquals($expected, $result); + + $TestModel->hasAndBelongsToMany['SomethingElse']['unique'] = false; + $TestModel->create(array( + 'Something' => array('id' => 1), + 'SomethingElse' => array(3, array( + 'something_else_id' => 1, + 'doomed' => true + )))); + + $TestModel->save(); + + $TestModel->hasAndBelongsToMany['SomethingElse']['order'] = 'SomethingElse.id ASC'; + $result = $TestModel->findById(1); + $expected = array( + 'Something' => array( + 'id' => '1', + 'title' => 'First Post', + 'body' => 'First Post Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:39:23' + ), + 'SomethingElse' => array( + array( + 'id' => '1', + 'title' => 'First Post', + 'body' => 'First Post Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:39:23', + 'updated' => '2007-03-18 10:41:31', + 'JoinThing' => array( + 'doomed' => true, + 'something_id' => '1', + 'something_else_id' => '1' + ) + ), + array( + 'id' => '2', + 'title' => 'Second Post', + 'body' => 'Second Post Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:41:23', + 'updated' => '2007-03-18 10:43:31', + 'JoinThing' => array( + 'doomed' => true, + 'something_id' => '1', + 'something_else_id' => '2' + ) + ), + array( + 'id' => '3', + 'title' => 'Third Post', + 'body' => 'Third Post Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:43:23', + 'updated' => '2007-03-18 10:45:31', + 'JoinThing' => array( + 'doomed' => false, + 'something_id' => '1', + 'something_else_id' => '3') + ) + ) + ); + $this->assertEquals(self::date(), $result['Something']['updated']); + unset($result['Something']['updated']); + $this->assertEquals($expected, $result); + } + +/** + * testFindSelfAssociations method + * + * @return void + */ + public function testFindSelfAssociations() { + $this->loadFixtures('Person'); + + $TestModel = new Person(); + $TestModel->recursive = 2; + $result = $TestModel->read(null, 1); + $expected = array( + 'Person' => array( + 'id' => 1, + 'name' => 'person', + 'mother_id' => 2, + 'father_id' => 3 + ), + 'Mother' => array( + 'id' => 2, + 'name' => 'mother', + 'mother_id' => 4, + 'father_id' => 5, + 'Mother' => array( + 'id' => 4, + 'name' => 'mother - grand mother', + 'mother_id' => 0, + 'father_id' => 0 + ), + 'Father' => array( + 'id' => 5, + 'name' => 'mother - grand father', + 'mother_id' => 0, + 'father_id' => 0 + )), + 'Father' => array( + 'id' => 3, + 'name' => 'father', + 'mother_id' => 6, + 'father_id' => 7, + 'Father' => array( + 'id' => 7, + 'name' => 'father - grand father', + 'mother_id' => 0, + 'father_id' => 0 + ), + 'Mother' => array( + 'id' => 6, + 'name' => 'father - grand mother', + 'mother_id' => 0, + 'father_id' => 0 + ))); + + $this->assertEquals($expected, $result); + + $TestModel->recursive = 3; + $result = $TestModel->read(null, 1); + $expected = array( + 'Person' => array( + 'id' => 1, + 'name' => 'person', + 'mother_id' => 2, + 'father_id' => 3 + ), + 'Mother' => array( + 'id' => 2, + 'name' => 'mother', + 'mother_id' => 4, + 'father_id' => 5, + 'Mother' => array( + 'id' => 4, + 'name' => 'mother - grand mother', + 'mother_id' => 0, + 'father_id' => 0, + 'Mother' => array(), + 'Father' => array()), + 'Father' => array( + 'id' => 5, + 'name' => 'mother - grand father', + 'mother_id' => 0, + 'father_id' => 0, + 'Father' => array(), + 'Mother' => array() + )), + 'Father' => array( + 'id' => 3, + 'name' => 'father', + 'mother_id' => 6, + 'father_id' => 7, + 'Father' => array( + 'id' => 7, + 'name' => 'father - grand father', + 'mother_id' => 0, + 'father_id' => 0, + 'Father' => array(), + 'Mother' => array() + ), + 'Mother' => array( + 'id' => 6, + 'name' => 'father - grand mother', + 'mother_id' => 0, + 'father_id' => 0, + 'Mother' => array(), + 'Father' => array() + ))); + + $this->assertEquals($expected, $result); + } + +/** + * testDynamicAssociations method + * + * @return void + */ + public function testDynamicAssociations() { + $this->loadFixtures('Article', 'Comment'); + $TestModel = new Article(); + + $TestModel->belongsTo = $TestModel->hasAndBelongsToMany = $TestModel->hasOne = array(); + $TestModel->hasMany['Comment'] = array_merge($TestModel->hasMany['Comment'], array( + 'foreignKey' => false, + 'conditions' => array('Comment.user_id =' => '2') + )); + $result = $TestModel->find('all'); + $expected = array( + array( + 'Article' => array( + 'id' => '1', + 'user_id' => '1', + 'title' => 'First Article', + 'body' => 'First Article Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:39:23', + 'updated' => '2007-03-18 10:41:31' + ), + 'Comment' => array( + array( + 'id' => '1', + 'article_id' => '1', + 'user_id' => '2', + 'comment' => 'First Comment for First Article', + 'published' => 'Y', + 'created' => '2007-03-18 10:45:23', + 'updated' => '2007-03-18 10:47:31' + ), + array( + 'id' => '6', + 'article_id' => '2', + 'user_id' => '2', + 'comment' => 'Second Comment for Second Article', + 'published' => 'Y', + 'created' => '2007-03-18 10:55:23', + 'updated' => '2007-03-18 10:57:31' + ))), + array( + 'Article' => array( + 'id' => '2', + 'user_id' => '3', + 'title' => 'Second Article', + 'body' => 'Second Article Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:41:23', + 'updated' => '2007-03-18 10:43:31' + ), + 'Comment' => array( + array( + 'id' => '1', + 'article_id' => '1', + 'user_id' => '2', + 'comment' => 'First Comment for First Article', + 'published' => 'Y', + 'created' => '2007-03-18 10:45:23', + 'updated' => '2007-03-18 10:47:31' + ), + array( + 'id' => '6', + 'article_id' => '2', + 'user_id' => '2', + 'comment' => 'Second Comment for Second Article', + 'published' => 'Y', + 'created' => '2007-03-18 10:55:23', + 'updated' => '2007-03-18 10:57:31' + ))), + array( + 'Article' => array( + 'id' => '3', + 'user_id' => '1', + 'title' => 'Third Article', + 'body' => 'Third Article Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:43:23', + 'updated' => '2007-03-18 10:45:31' + ), + 'Comment' => array( + array( + 'id' => '1', + 'article_id' => '1', + 'user_id' => '2', + 'comment' => 'First Comment for First Article', + 'published' => 'Y', + 'created' => '2007-03-18 10:45:23', + 'updated' => '2007-03-18 10:47:31' + ), + array( + 'id' => '6', + 'article_id' => '2', + 'user_id' => '2', + 'comment' => 'Second Comment for Second Article', + 'published' => 'Y', + 'created' => '2007-03-18 10:55:23', + 'updated' => '2007-03-18 10:57:31' + )))); + + $this->assertEquals($expected, $result); + } + +/** + * testCreation method + * + * @return void + */ + public function testCreation() { + $this->loadFixtures('Article', 'ArticleFeaturedsTags', 'User', 'Featured'); + $TestModel = new Test(); + $result = $TestModel->create(); + $expected = array('Test' => array('notes' => 'write some notes here')); + $this->assertEquals($expected, $result); + $TestModel = new User(); + $result = $TestModel->schema(); + + if (isset($this->db->columns['primary_key']['length'])) { + $intLength = $this->db->columns['primary_key']['length']; + } elseif (isset($this->db->columns['integer']['length'])) { + $intLength = $this->db->columns['integer']['length']; + } else { + $intLength = 11; + } + foreach (array('collate', 'charset', 'comment') as $type) { + foreach ($result as $i => $r) { + unset($result[$i][$type]); + } + } + + $expected = array( + 'id' => array( + 'type' => 'integer', + 'null' => false, + 'default' => null, + 'length' => $intLength, + 'key' => 'primary' + ), + 'user' => array( + 'type' => 'string', + 'null' => true, + 'default' => '', + 'length' => 255 + ), + 'password' => array( + 'type' => 'string', + 'null' => true, + 'default' => '', + 'length' => 255 + ), + 'created' => array( + 'type' => 'datetime', + 'null' => true, + 'default' => null, + 'length' => null + ), + 'updated' => array( + 'type' => 'datetime', + 'null' => true, + 'default' => null, + 'length' => null + )); + + $this->assertEquals($expected, $result); + + $TestModel = new Article(); + $result = $TestModel->create(); + $expected = array('Article' => array('published' => 'N')); + $this->assertEquals($expected, $result); + + $FeaturedModel = new Featured(); + $data = array( + 'article_featured_id' => 1, + 'category_id' => 1, + 'published_date' => array( + 'year' => 2008, + 'month' => 06, + 'day' => 11 + ), + 'end_date' => array( + 'year' => 2008, + 'month' => 06, + 'day' => 20 + )); + + $expected = array( + 'Featured' => array( + 'article_featured_id' => 1, + 'category_id' => 1, + 'published_date' => '2008-06-11 00:00:00', + 'end_date' => '2008-06-20 00:00:00' + )); + + $this->assertEquals($expected, $FeaturedModel->create($data)); + + $data = array( + 'published_date' => array( + 'year' => 2008, + 'month' => 06, + 'day' => 11 + ), + 'end_date' => array( + 'year' => 2008, + 'month' => 06, + 'day' => 20 + ), + 'article_featured_id' => 1, + 'category_id' => 1 + ); + + $expected = array( + 'Featured' => array( + 'published_date' => '2008-06-11 00:00:00', + 'end_date' => '2008-06-20 00:00:00', + 'article_featured_id' => 1, + 'category_id' => 1 + )); + + $this->assertEquals($expected, $FeaturedModel->create($data)); + } + +/** + * testEscapeField to prove it escapes the field well even when it has part of the alias on it + * + * @return void + */ + public function testEscapeField() { + $TestModel = new Test(); + $db = $TestModel->getDataSource(); + + $result = $TestModel->escapeField('test_field'); + $expected = $db->name('Test.test_field'); + $this->assertEquals($expected, $result); + + $result = $TestModel->escapeField('TestField'); + $expected = $db->name('Test.TestField'); + $this->assertEquals($expected, $result); + + $result = $TestModel->escapeField('DomainHandle', 'Domain'); + $expected = $db->name('Domain.DomainHandle'); + $this->assertEquals($expected, $result); + + ConnectionManager::create('mock', array('datasource' => 'DboMock')); + $TestModel->setDataSource('mock'); + $db = $TestModel->getDataSource(); + + $result = $TestModel->escapeField('DomainHandle', 'Domain'); + $expected = $db->name('Domain.DomainHandle'); + $this->assertEquals($expected, $result); + ConnectionManager::drop('mock'); + } + +/** + * testGetID + * + * @return void + */ + public function testGetID() { + $TestModel = new Test(); + + $result = $TestModel->getID(); + $this->assertFalse($result); + + $TestModel->id = 9; + $result = $TestModel->getID(); + $this->assertEquals(9, $result); + + $TestModel->id = array(10, 9, 8, 7); + $result = $TestModel->getID(2); + $this->assertEquals(8, $result); + + $TestModel->id = array(array(), 1, 2, 3); + $result = $TestModel->getID(); + $this->assertFalse($result); + } + +/** + * test that model->hasMethod checks self and behaviors. + * + * @return void + */ + public function testHasMethod() { + $Article = new Article(); + $Article->Behaviors = $this->getMock('BehaviorCollection'); + + $Article->Behaviors->expects($this->at(0)) + ->method('hasMethod') + ->will($this->returnValue(true)); + + $Article->Behaviors->expects($this->at(1)) + ->method('hasMethod') + ->will($this->returnValue(false)); + + $this->assertTrue($Article->hasMethod('find')); + + $this->assertTrue($Article->hasMethod('pass')); + $this->assertFalse($Article->hasMethod('fail')); + } + +/** + * testMultischemaFixture + * + * @return void + */ + public function testMultischemaFixture() { + $config = ConnectionManager::enumConnectionObjects(); + $this->skipIf($this->db instanceof Sqlite, 'This test is not compatible with Sqlite.'); + $this->skipIf(!isset($config['test']) || !isset($config['test2']), + 'Primary and secondary test databases not configured, skipping cross-database join tests. To run these tests define $test and $test2 in your database configuration.' + ); + + $this->loadFixtures('Player', 'Guild', 'GuildsPlayer'); + + $Player = ClassRegistry::init('Player'); + $this->assertEquals('test', $Player->useDbConfig); + $this->assertEquals('test', $Player->Guild->useDbConfig); + $this->assertEquals('test2', $Player->Guild->GuildsPlayer->useDbConfig); + $this->assertEquals('test2', $Player->GuildsPlayer->useDbConfig); + + $players = $Player->find('all', array('recursive' => -1)); + $guilds = $Player->Guild->find('all', array('recursive' => -1)); + $guildsPlayers = $Player->GuildsPlayer->find('all', array('recursive' => -1)); + + $this->assertEquals(true, count($players) > 1); + $this->assertEquals(true, count($guilds) > 1); + $this->assertEquals(true, count($guildsPlayers) > 1); + } + +/** + * testMultischemaFixtureWithThreeDatabases, three databases + * + * @return void + */ + public function testMultischemaFixtureWithThreeDatabases() { + $config = ConnectionManager::enumConnectionObjects(); + $this->skipIf($this->db instanceof Sqlite, 'This test is not compatible with Sqlite.'); + $this->skipIf( + !isset($config['test']) || !isset($config['test2']) || !isset($config['test_database_three']), + 'Primary, secondary, and tertiary test databases not configured, skipping test. To run this test define $test, $test2, and $test_database_three in your database configuration.' + ); + + $this->loadFixtures('Player', 'Guild', 'GuildsPlayer', 'Armor', 'ArmorsPlayer'); + + $Player = ClassRegistry::init('Player'); + $Player->bindModel(array( + 'hasAndBelongsToMany' => array( + 'Armor' => array( + 'with' => 'ArmorsPlayer', + ), + ), + ), false); + $this->assertEquals('test', $Player->useDbConfig); + $this->assertEquals('test', $Player->Guild->useDbConfig); + $this->assertEquals('test2', $Player->Guild->GuildsPlayer->useDbConfig); + $this->assertEquals('test2', $Player->GuildsPlayer->useDbConfig); + $this->assertEquals('test2', $Player->Armor->useDbConfig); + $this->assertEquals('test_database_three', $Player->Armor->ArmorsPlayer->useDbConfig); + $this->assertEquals('test', $Player->getDataSource()->configKeyName); + $this->assertEquals('test', $Player->Guild->getDataSource()->configKeyName); + $this->assertEquals('test2', $Player->GuildsPlayer->getDataSource()->configKeyName); + $this->assertEquals('test2', $Player->Armor->getDataSource()->configKeyName); + $this->assertEquals('test_database_three', $Player->Armor->ArmorsPlayer->getDataSource()->configKeyName); + + $players = $Player->find('all', array('recursive' => -1)); + $guilds = $Player->Guild->find('all', array('recursive' => -1)); + $guildsPlayers = $Player->GuildsPlayer->find('all', array('recursive' => -1)); + $armorsPlayers = $Player->ArmorsPlayer->find('all', array('recursive' => -1)); + + $this->assertEquals(true, count($players) > 1); + $this->assertEquals(true, count($guilds) > 1); + $this->assertEquals(true, count($guildsPlayers) > 1); + $this->assertEquals(true, count($armorsPlayers) > 1); + } + +/** + * Tests that calling schema() on a model that is not supposed to use a table + * does not trigger any calls on any datasource + * + * @return void + **/ + public function testSchemaNoDB() { + $model = $this->getMock('Article', array('getDataSource')); + $model->useTable = false; + $model->expects($this->never())->method('getDataSource'); + $this->assertEmpty($model->schema()); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/ModelReadTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/ModelReadTest.php new file mode 100644 index 0000000..58a2ff4 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/ModelReadTest.php @@ -0,0 +1,7881 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Model + * @since CakePHP(tm) v 1.2.0.4206 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ +require_once dirname(__FILE__) . DS . 'ModelTestBase.php'; +/** + * ModelReadTest + * + * @package Cake.Test.Case.Model + */ +class ModelReadTest extends BaseModelTest { + +/** + * testExists function + * @retun void + */ + public function testExists() { + $this->loadFixtures('User'); + $TestModel = new User(); + + $this->assertTrue($TestModel->exists(1)); + + $TestModel->id = 2; + $this->assertTrue($TestModel->exists()); + + $TestModel->delete(); + $this->assertFalse($TestModel->exists()); + + $this->assertFalse($TestModel->exists(2)); + } + +/** + * testFetchingNonUniqueFKJoinTableRecords() + * + * Tests if the results are properly returned in the case there are non-unique FK's + * in the join table but another fields value is different. For example: + * something_id | something_else_id | doomed = 1 + * something_id | something_else_id | doomed = 0 + * Should return both records and not just one. + * + * @return void + */ + public function testFetchingNonUniqueFKJoinTableRecords() { + $this->loadFixtures('Something', 'SomethingElse', 'JoinThing'); + $Something = new Something(); + + $joinThingData = array( + 'JoinThing' => array( + 'something_id' => 1, + 'something_else_id' => 2, + 'doomed' => '0', + 'created' => '2007-03-18 10:39:23', + 'updated' => '2007-03-18 10:41:31' + ) + ); + + $Something->JoinThing->create($joinThingData); + $Something->JoinThing->save(); + + $result = $Something->JoinThing->find('all', array('conditions' => array('something_else_id' => 2))); + + $this->assertEquals(true, $result[0]['JoinThing']['doomed']); + $this->assertEquals(false, $result[1]['JoinThing']['doomed']); + + $result = $Something->find('first'); + + $this->assertEquals(2, count($result['SomethingElse'])); + + $doomed = Hash::extract($result['SomethingElse'], '{n}.JoinThing.doomed'); + $this->assertTrue(in_array(true, $doomed)); + $this->assertTrue(in_array(false, $doomed)); + } + +/** + * testGroupBy method + * + * These tests will never pass with Postgres or Oracle as all fields in a select must be + * part of an aggregate function or in the GROUP BY statement. + * + * @return void + */ + public function testGroupBy() { + $isStrictGroupBy = $this->db instanceof Postgres || $this->db instanceof Sqlite || $this->db instanceof Oracle || $this->db instanceof Sqlserver; + $message = 'Postgres, Oracle, SQLite and SQL Server have strict GROUP BY and are incompatible with this test.'; + + $this->skipIf($isStrictGroupBy, $message); + + $this->loadFixtures('Project', 'Product', 'Thread', 'Message', 'Bid'); + $Thread = new Thread(); + $Product = new Product(); + + $result = $Thread->find('all', array( + 'group' => 'Thread.project_id', + 'order' => 'Thread.id ASC' + )); + + $expected = array( + array( + 'Thread' => array( + 'id' => 1, + 'project_id' => 1, + 'name' => 'Project 1, Thread 1' + ), + 'Project' => array( + 'id' => 1, + 'name' => 'Project 1' + ), + 'Message' => array( + array( + 'id' => 1, + 'thread_id' => 1, + 'name' => 'Thread 1, Message 1' + ))), + array( + 'Thread' => array( + 'id' => 3, + 'project_id' => 2, + 'name' => 'Project 2, Thread 1' + ), + 'Project' => array( + 'id' => 2, + 'name' => 'Project 2' + ), + 'Message' => array( + array( + 'id' => 3, + 'thread_id' => 3, + 'name' => 'Thread 3, Message 1' + )))); + $this->assertEquals($expected, $result); + + $rows = $Thread->find('all', array( + 'group' => 'Thread.project_id', + 'fields' => array('Thread.project_id', 'COUNT(*) AS total') + )); + $result = array(); + foreach ($rows as $row) { + $result[$row['Thread']['project_id']] = $row[0]['total']; + } + $expected = array( + 1 => 2, + 2 => 1 + ); + $this->assertEquals($expected, $result); + + $rows = $Thread->find('all', array( + 'group' => 'Thread.project_id', + 'fields' => array('Thread.project_id', 'COUNT(*) AS total'), + 'order' => 'Thread.project_id' + )); + $result = array(); + foreach ($rows as $row) { + $result[$row['Thread']['project_id']] = $row[0]['total']; + } + $expected = array( + 1 => 2, + 2 => 1 + ); + $this->assertEquals($expected, $result); + + $result = $Thread->find('all', array( + 'conditions' => array('Thread.project_id' => 1), + 'group' => 'Thread.project_id' + )); + $expected = array( + array( + 'Thread' => array( + 'id' => 1, + 'project_id' => 1, + 'name' => 'Project 1, Thread 1' + ), + 'Project' => array( + 'id' => 1, + 'name' => 'Project 1' + ), + 'Message' => array( + array( + 'id' => 1, + 'thread_id' => 1, + 'name' => 'Thread 1, Message 1' + )))); + $this->assertEquals($expected, $result); + + $result = $Thread->find('all', array( + 'conditions' => array('Thread.project_id' => 1), + 'group' => 'Thread.project_id, Project.id' + )); + $this->assertEquals($expected, $result); + + $result = $Thread->find('all', array( + 'conditions' => array('Thread.project_id' => 1), + 'group' => 'project_id' + )); + $this->assertEquals($expected, $result); + + $result = $Thread->find('all', array( + 'conditions' => array('Thread.project_id' => 1), + 'group' => array('project_id') + )); + $this->assertEquals($expected, $result); + + $result = $Thread->find('all', array( + 'conditions' => array('Thread.project_id' => 1), + 'group' => array('project_id', 'Project.id') + )); + $this->assertEquals($expected, $result); + + $result = $Thread->find('all', array( + 'conditions' => array('Thread.project_id' => 1), + 'group' => array('Thread.project_id', 'Project.id') + )); + $this->assertEquals($expected, $result); + + $expected = array( + array('Product' => array('type' => 'Clothing'), array('price' => 32)), + array('Product' => array('type' => 'Food'), array('price' => 9)), + array('Product' => array('type' => 'Music'), array('price' => 4)), + array('Product' => array('type' => 'Toy'), array('price' => 3)) + ); + $result = $Product->find('all',array( + 'fields' => array('Product.type', 'MIN(Product.price) as price'), + 'group' => 'Product.type', + 'order' => 'Product.type ASC' + )); + $this->assertEquals($expected, $result); + + $result = $Product->find('all', array( + 'fields' => array('Product.type', 'MIN(Product.price) as price'), + 'group' => array('Product.type'), + 'order' => 'Product.type ASC')); + $this->assertEquals($expected, $result); + } + +/** + * testOldQuery method + * + * @return void + */ + public function testOldQuery() { + $this->loadFixtures('Article', 'User', 'Tag', 'ArticlesTag', 'Comment', 'Attachment'); + $Article = new Article(); + + $query = 'SELECT title FROM '; + $query .= $this->db->fullTableName('articles'); + $query .= ' WHERE ' . $this->db->fullTableName('articles') . '.id IN (1,2)'; + + $results = $Article->query($query); + $this->assertTrue(is_array($results)); + $this->assertEquals(2, count($results)); + + $query = 'SELECT title, body FROM '; + $query .= $this->db->fullTableName('articles'); + $query .= ' WHERE ' . $this->db->fullTableName('articles') . '.id = 1'; + + $results = $Article->query($query, false); + $this->assertFalse($this->db->getQueryCache($query)); + $this->assertTrue(is_array($results)); + + $query = 'SELECT title, id FROM '; + $query .= $this->db->fullTableName('articles'); + $query .= ' WHERE ' . $this->db->fullTableName('articles'); + $query .= '.published = ' . $this->db->value('Y'); + + $results = $Article->query($query, true); + $result = $this->db->getQueryCache($query); + $this->assertFalse(empty($result)); + $this->assertTrue(is_array($results)); + } + +/** + * testPreparedQuery method + * + * @return void + */ + public function testPreparedQuery() { + $this->loadFixtures('Article', 'User', 'Tag', 'ArticlesTag'); + $Article = new Article(); + + $query = 'SELECT title, published FROM '; + $query .= $this->db->fullTableName('articles'); + $query .= ' WHERE ' . $this->db->fullTableName('articles'); + $query .= '.id = ? AND ' . $this->db->fullTableName('articles') . '.published = ?'; + + $params = array(1, 'Y'); + $result = $Article->query($query, $params); + $expected = array( + '0' => array( + $this->db->fullTableName('articles', false, false) => array( + 'title' => 'First Article', 'published' => 'Y') + )); + + if (isset($result[0][0])) { + $expected[0][0] = $expected[0][$this->db->fullTableName('articles', false, false)]; + unset($expected[0][$this->db->fullTableName('articles', false, false)]); + } + + $this->assertEquals($expected, $result); + $result = $this->db->getQueryCache($query, $params); + $this->assertFalse(empty($result)); + + $query = 'SELECT id, created FROM '; + $query .= $this->db->fullTableName('articles'); + $query .= ' WHERE ' . $this->db->fullTableName('articles') . '.title = ?'; + + $params = array('First Article'); + $result = $Article->query($query, $params, false); + $this->assertTrue(is_array($result)); + $this->assertTrue( + isset($result[0][$this->db->fullTableName('articles', false, false)]) || + isset($result[0][0]) + ); + $result = $this->db->getQueryCache($query, $params); + $this->assertTrue(empty($result)); + + $query = 'SELECT title FROM '; + $query .= $this->db->fullTableName('articles'); + $query .= ' WHERE ' . $this->db->fullTableName('articles') . '.title LIKE ?'; + + $params = array('%First%'); + $result = $Article->query($query, $params); + $this->assertTrue(is_array($result)); + $this->assertTrue( + isset($result[0][$this->db->fullTableName('articles', false, false)]['title']) || + isset($result[0][0]['title']) + ); + + //related to ticket #5035 + $query = 'SELECT title FROM '; + $query .= $this->db->fullTableName('articles') . ' WHERE title = ? AND published = ?'; + $params = array('First? Article', 'Y'); + $Article->query($query, $params); + + $result = $this->db->getQueryCache($query, $params); + $this->assertFalse($result === false); + } + +/** + * testParameterMismatch method + * + * @expectedException PDOException + * @return void + */ + public function testParameterMismatch() { + $this->skipIf($this->db instanceof Sqlite, 'Sqlite does not accept real prepared statements, no way to check this'); + $this->loadFixtures('Article', 'User', 'Tag', 'ArticlesTag'); + $Article = new Article(); + + $query = 'SELECT * FROM ' . $this->db->fullTableName('articles'); + $query .= ' WHERE ' . $this->db->fullTableName('articles'); + $query .= '.published = ? AND ' . $this->db->fullTableName('articles') . '.user_id = ?'; + $params = array('Y'); + + $result = $Article->query($query, $params); + } + +/** + * testVeryStrangeUseCase method + * + * @expectedException PDOException + * @return void + */ + public function testVeryStrangeUseCase() { + $this->loadFixtures('Article', 'User', 'Tag', 'ArticlesTag'); + $Article = new Article(); + + $query = 'SELECT * FROM ? WHERE ? = ? AND ? = ?'; + $param = array( + $this->db->fullTableName('articles'), + $this->db->fullTableName('articles') . '.user_id', '3', + $this->db->fullTableName('articles') . '.published', 'Y' + ); + + $result = $Article->query($query, $param); + } + +/** + * testRecursiveUnbind method + * + * @return void + */ + public function testRecursiveUnbind() { + $this->skipIf($this->db instanceof Sqlserver, 'The test of testRecursiveUnbind test is not compatible with SQL Server, because it check for time columns.'); + + $this->loadFixtures('Apple', 'Sample'); + $TestModel = new Apple(); + $TestModel->recursive = 2; + + $result = $TestModel->find('all'); + $expected = array( + array( + 'Apple' => array( + 'id' => 1, + 'apple_id' => 2, + 'color' => 'Red 1', + 'name' => 'Red Apple 1', + 'created' => '2006-11-22 10:38:58', + 'date' => '1951-01-04', + 'modified' => '2006-12-01 13:31:26', + 'mytime' => '22:57:17' + ), + 'Parent' => array( + 'id' => 2, + 'apple_id' => 1, + 'color' => 'Bright Red 1', + 'name' => 'Bright Red Apple', + 'created' => '2006-11-22 10:43:13', + 'date' => '2014-01-01', + 'modified' => '2006-11-30 18:38:10', + 'mytime' => '22:57:17', + 'Parent' => array( + 'id' => 1, + 'apple_id' => 2, + 'color' => 'Red 1', + 'name' => 'Red Apple 1', + 'created' => '2006-11-22 10:38:58', + 'date' => '1951-01-04', + 'modified' => '2006-12-01 13:31:26', + 'mytime' => '22:57:17' + ), + 'Sample' => array( + 'id' => 2, + 'apple_id' => 2, + 'name' => 'sample2' + ), + 'Child' => array( + array( + 'id' => 1, + 'apple_id' => 2, + 'color' => 'Red 1', + 'name' => 'Red Apple 1', + 'created' => '2006-11-22 10:38:58', + 'date' => '1951-01-04', + 'modified' => '2006-12-01 13:31:26', + 'mytime' => '22:57:17' + ), + array( + 'id' => 3, + 'apple_id' => 2, + 'color' => 'blue green', + 'name' => 'green blue', + 'created' => '2006-12-25 05:13:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:24', + 'mytime' => '22:57:17' + ), + array( + 'id' => 4, + 'apple_id' => 2, + 'color' => 'Blue Green', + 'name' => 'Test Name', + 'created' => '2006-12-25 05:23:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:36', + 'mytime' => '22:57:17' + ))), + 'Sample' => array( + 'id' => '', + 'apple_id' => '', + 'name' => '' + ), + 'Child' => array( + array( + 'id' => 2, + 'apple_id' => 1, + 'color' => 'Bright Red 1', + 'name' => 'Bright Red Apple', + 'created' => '2006-11-22 10:43:13', + 'date' => '2014-01-01', + 'modified' => '2006-11-30 18:38:10', + 'mytime' => '22:57:17', + 'Parent' => array( + 'id' => 1, + 'apple_id' => 2, + 'color' => 'Red 1', + 'name' => 'Red Apple 1', + 'created' => '2006-11-22 10:38:58', + 'date' => '1951-01-04', + 'modified' => '2006-12-01 13:31:26', + 'mytime' => '22:57:17' + ), + 'Sample' => array( + 'id' => 2, + 'apple_id' => 2, + 'name' => 'sample2' + ), + 'Child' => array( + array( + 'id' => 1, + 'apple_id' => 2, + 'color' => 'Red 1', + 'name' => 'Red Apple 1', + 'created' => '2006-11-22 10:38:58', + 'date' => '1951-01-04', + 'modified' => '2006-12-01 13:31:26', + 'mytime' => '22:57:17' + ), + array( + 'id' => 3, + 'apple_id' => 2, + 'color' => 'blue green', + 'name' => 'green blue', + 'created' => '2006-12-25 05:13:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:24', + 'mytime' => '22:57:17' + ), + array( + 'id' => 4, + 'apple_id' => 2, + 'color' => 'Blue Green', + 'name' => 'Test Name', + 'created' => '2006-12-25 05:23:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:36', + 'mytime' => '22:57:17' + ))))), + array( + 'Apple' => array( + 'id' => 2, + 'apple_id' => 1, + 'color' => 'Bright Red 1', + 'name' => 'Bright Red Apple', + 'created' => '2006-11-22 10:43:13', + 'date' => '2014-01-01', + 'modified' => '2006-11-30 18:38:10', + 'mytime' => '22:57:17' + ), + 'Parent' => array( + 'id' => 1, + 'apple_id' => 2, + 'color' => 'Red 1', + 'name' => 'Red Apple 1', + 'created' => '2006-11-22 10:38:58', + 'date' => '1951-01-04', + 'modified' => '2006-12-01 13:31:26', + 'mytime' => '22:57:17', + 'Parent' => array( + 'id' => 2, + 'apple_id' => 1, + 'color' => 'Bright Red 1', + 'name' => 'Bright Red Apple', + 'created' => '2006-11-22 10:43:13', + 'date' => '2014-01-01', + 'modified' => '2006-11-30 18:38:10', + 'mytime' => '22:57:17' + ), + 'Sample' => array(), + 'Child' => array( + array( + 'id' => 2, + 'apple_id' => 1, + 'color' => 'Bright Red 1', + 'name' => 'Bright Red Apple', + 'created' => '2006-11-22 10:43:13', + 'date' => '2014-01-01', + 'modified' => '2006-11-30 18:38:10', + 'mytime' => '22:57:17' + ))), + 'Sample' => array( + 'id' => 2, + 'apple_id' => 2, + 'name' => 'sample2', + 'Apple' => array( + 'id' => 2, + 'apple_id' => 1, + 'color' => 'Bright Red 1', + 'name' => 'Bright Red Apple', + 'created' => '2006-11-22 10:43:13', + 'date' => '2014-01-01', + 'modified' => '2006-11-30 18:38:10', + 'mytime' => '22:57:17' + )), + 'Child' => array( + array( + 'id' => 1, + 'apple_id' => 2, + 'color' => 'Red 1', + 'name' => 'Red Apple 1', + 'created' => '2006-11-22 10:38:58', + 'date' => '1951-01-04', + 'modified' => '2006-12-01 13:31:26', + 'mytime' => '22:57:17', + 'Parent' => array( + 'id' => 2, + 'apple_id' => 1, + 'color' => 'Bright Red 1', + 'name' => 'Bright Red Apple', + 'created' => '2006-11-22 10:43:13', + 'date' => '2014-01-01', + 'modified' => '2006-11-30 18:38:10', + 'mytime' => '22:57:17' + ), + 'Sample' => array(), + 'Child' => array( + array( + 'id' => 2, + 'apple_id' => 1, + 'color' => 'Bright Red 1', + 'name' => 'Bright Red Apple', + 'created' => '2006-11-22 10:43:13', + 'date' => '2014-01-01', + 'modified' => '2006-11-30 18:38:10', + 'mytime' => '22:57:17' + ))), + array( + 'id' => 3, + 'apple_id' => 2, + 'color' => 'blue green', + 'name' => 'green blue', + 'created' => '2006-12-25 05:13:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:24', + 'mytime' => '22:57:17', + 'Parent' => array( + 'id' => 2, + 'apple_id' => 1, + 'color' => 'Bright Red 1', + 'name' => 'Bright Red Apple', + 'created' => '2006-11-22 10:43:13', + 'date' => '2014-01-01', + 'modified' => '2006-11-30 18:38:10', + 'mytime' => '22:57:17' + ), + 'Sample' => array( + 'id' => 1, + 'apple_id' => 3, + 'name' => 'sample1' + )), + array( + 'id' => 4, + 'apple_id' => 2, + 'color' => 'Blue Green', + 'name' => 'Test Name', + 'created' => '2006-12-25 05:23:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:36', + 'mytime' => '22:57:17', + 'Parent' => array( + 'id' => 2, + 'apple_id' => 1, + 'color' => 'Bright Red 1', + 'name' => 'Bright Red Apple', + 'created' => '2006-11-22 10:43:13', + 'date' => '2014-01-01', + 'modified' => '2006-11-30 18:38:10', + 'mytime' => '22:57:17' + ), + 'Sample' => array( + 'id' => 3, + 'apple_id' => 4, + 'name' => 'sample3' + ), + 'Child' => array( + array( + 'id' => 6, + 'apple_id' => 4, + 'color' => 'My new appleOrange', + 'name' => 'My new apple', + 'created' => '2006-12-25 05:29:39', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:29:39', + 'mytime' => '22:57:17' + ))))), + array( + 'Apple' => array( + 'id' => 3, + 'apple_id' => 2, + 'color' => 'blue green', + 'name' => 'green blue', + 'created' => '2006-12-25 05:13:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:24', + 'mytime' => '22:57:17' + ), + 'Parent' => array( + 'id' => 2, + 'apple_id' => 1, + 'color' => 'Bright Red 1', + 'name' => 'Bright Red Apple', + 'created' => '2006-11-22 10:43:13', + 'date' => '2014-01-01', + 'modified' => '2006-11-30 18:38:10', + 'mytime' => '22:57:17', + 'Parent' => array( + 'id' => 1, + 'apple_id' => 2, + 'color' => 'Red 1', + 'name' => 'Red Apple 1', + 'created' => '2006-11-22 10:38:58', + 'date' => '1951-01-04', + 'modified' => '2006-12-01 13:31:26', + 'mytime' => '22:57:17' + ), + 'Sample' => array( + 'id' => 2, + 'apple_id' => 2, + 'name' => 'sample2' + ), + 'Child' => array( + array( + 'id' => 1, + 'apple_id' => 2, + 'color' => 'Red 1', + 'name' => 'Red Apple 1', + 'created' => '2006-11-22 10:38:58', + 'date' => '1951-01-04', + 'modified' => '2006-12-01 13:31:26', + 'mytime' => '22:57:17' + ), + array( + 'id' => 3, + 'apple_id' => 2, + 'color' => 'blue green', + 'name' => 'green blue', + 'created' => '2006-12-25 05:13:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:24', + 'mytime' => '22:57:17' + ), + array( + 'id' => 4, + 'apple_id' => 2, + 'color' => 'Blue Green', + 'name' => 'Test Name', + 'created' => '2006-12-25 05:23:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:36', + 'mytime' => '22:57:17' + ))), + 'Sample' => array( + 'id' => 1, + 'apple_id' => 3, + 'name' => 'sample1', + 'Apple' => array( + 'id' => 3, + 'apple_id' => 2, + 'color' => 'blue green', + 'name' => 'green blue', + 'created' => '2006-12-25 05:13:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:24', + 'mytime' => '22:57:17' + )), + 'Child' => array() + ), + array( + 'Apple' => array( + 'id' => 4, + 'apple_id' => 2, + 'color' => 'Blue Green', + 'name' => 'Test Name', + 'created' => '2006-12-25 05:23:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:36', + 'mytime' => '22:57:17' + ), + 'Parent' => array( + 'id' => 2, + 'apple_id' => 1, + 'color' => 'Bright Red 1', + 'name' => 'Bright Red Apple', + 'created' => '2006-11-22 10:43:13', + 'date' => '2014-01-01', + 'modified' => '2006-11-30 18:38:10', + 'mytime' => '22:57:17', + 'Parent' => array( + 'id' => 1, + 'apple_id' => 2, + 'color' => 'Red 1', + 'name' => 'Red Apple 1', + 'created' => '2006-11-22 10:38:58', + 'date' => '1951-01-04', + 'modified' => '2006-12-01 13:31:26', 'mytime' => '22:57:17'), + 'Sample' => array('id' => 2, 'apple_id' => 2, 'name' => 'sample2'), + 'Child' => array( + array( + 'id' => 1, + 'apple_id' => 2, + 'color' => 'Red 1', + 'name' => 'Red Apple 1', + 'created' => '2006-11-22 10:38:58', + 'date' => '1951-01-04', + 'modified' => '2006-12-01 13:31:26', + 'mytime' => '22:57:17' + ), + array( + 'id' => 3, + 'apple_id' => 2, + 'color' => 'blue green', + 'name' => 'green blue', + 'created' => '2006-12-25 05:13:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:24', + 'mytime' => '22:57:17' + ), + array( + 'id' => 4, + 'apple_id' => 2, + 'color' => 'Blue Green', + 'name' => 'Test Name', + 'created' => '2006-12-25 05:23:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:36', + 'mytime' => '22:57:17' + ))), + 'Sample' => array( + 'id' => 3, + 'apple_id' => 4, + 'name' => 'sample3', + 'Apple' => array( + 'id' => 4, + 'apple_id' => 2, + 'color' => 'Blue Green', + 'name' => 'Test Name', + 'created' => '2006-12-25 05:23:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:36', + 'mytime' => '22:57:17' + )), + 'Child' => array( + array( + 'id' => 6, + 'apple_id' => 4, + 'color' => 'My new appleOrange', + 'name' => 'My new apple', + 'created' => '2006-12-25 05:29:39', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:29:39', + 'mytime' => '22:57:17', + 'Parent' => array( + 'id' => 4, + 'apple_id' => 2, + 'color' => 'Blue Green', + 'name' => 'Test Name', + 'created' => '2006-12-25 05:23:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:36', + 'mytime' => '22:57:17' + ), + 'Sample' => array(), + 'Child' => array( + array( + 'id' => 7, + 'apple_id' => 6, + 'color' => 'Some wierd color', + 'name' => 'Some odd color', + 'created' => '2006-12-25 05:34:21', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:34:21', + 'mytime' => '22:57:17' + ))))), + array( + 'Apple' => array( + 'id' => 5, + 'apple_id' => 5, + 'color' => 'Green', + 'name' => 'Blue Green', + 'created' => '2006-12-25 05:24:06', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:29:16', + 'mytime' => '22:57:17' + ), + 'Parent' => array( + 'id' => 5, + 'apple_id' => 5, + 'color' => 'Green', + 'name' => 'Blue Green', + 'created' => '2006-12-25 05:24:06', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:29:16', + 'mytime' => '22:57:17', + 'Parent' => array( + 'id' => 5, + 'apple_id' => 5, + 'color' => 'Green', + 'name' => 'Blue Green', + 'created' => '2006-12-25 05:24:06', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:29:16', + 'mytime' => '22:57:17' + ), + 'Sample' => array( + 'id' => 4, + 'apple_id' => 5, + 'name' => 'sample4' + ), + 'Child' => array( + array( + 'id' => 5, + 'apple_id' => 5, + 'color' => 'Green', + 'name' => 'Blue Green', + 'created' => '2006-12-25 05:24:06', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:29:16', + 'mytime' => '22:57:17' + ))), + 'Sample' => array( + 'id' => 4, + 'apple_id' => 5, + 'name' => 'sample4', + 'Apple' => array( + 'id' => 5, + 'apple_id' => 5, + 'color' => 'Green', + 'name' => 'Blue Green', + 'created' => '2006-12-25 05:24:06', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:29:16', + 'mytime' => '22:57:17' + )), + 'Child' => array( + array( + 'id' => 5, + 'apple_id' => 5, + 'color' => 'Green', + 'name' => 'Blue Green', + 'created' => '2006-12-25 05:24:06', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:29:16', + 'mytime' => '22:57:17', + 'Parent' => array( + 'id' => 5, + 'apple_id' => 5, + 'color' => 'Green', + 'name' => 'Blue Green', + 'created' => '2006-12-25 05:24:06', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:29:16', + 'mytime' => '22:57:17' + ), + 'Sample' => array( + 'id' => 4, + 'apple_id' => 5, + 'name' => 'sample4' + ), + 'Child' => array( + array( + 'id' => 5, + 'apple_id' => 5, + 'color' => 'Green', + 'name' => 'Blue Green', + 'created' => '2006-12-25 05:24:06', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:29:16', + 'mytime' => '22:57:17' + ))))), + array( + 'Apple' => array( + 'id' => 6, + 'apple_id' => 4, + 'color' => 'My new appleOrange', + 'name' => 'My new apple', + 'created' => '2006-12-25 05:29:39', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:29:39', + 'mytime' => '22:57:17' + ), + 'Parent' => array( + 'id' => 4, + 'apple_id' => 2, + 'color' => 'Blue Green', + 'name' => 'Test Name', + 'created' => '2006-12-25 05:23:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:36', + 'mytime' => '22:57:17', + 'Parent' => array( + 'id' => 2, + 'apple_id' => 1, + 'color' => 'Bright Red 1', + 'name' => 'Bright Red Apple', + 'created' => '2006-11-22 10:43:13', + 'date' => '2014-01-01', + 'modified' => '2006-11-30 18:38:10', + 'mytime' => '22:57:17' + ), + 'Sample' => array( + 'id' => 3, + 'apple_id' => 4, + 'name' => 'sample3' + ), + 'Child' => array( + array( + 'id' => 6, + 'apple_id' => 4, + 'color' => 'My new appleOrange', + 'name' => 'My new apple', + 'created' => '2006-12-25 05:29:39', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:29:39', + 'mytime' => '22:57:17' + ))), + 'Sample' => array( + 'id' => '', + 'apple_id' => '', + 'name' => '' + ), + 'Child' => array( + array( + 'id' => 7, + 'apple_id' => 6, + 'color' => 'Some wierd color', + 'name' => 'Some odd color', + 'created' => '2006-12-25 05:34:21', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:34:21', + 'mytime' => '22:57:17', + 'Parent' => array( + 'id' => 6, + 'apple_id' => 4, + 'color' => 'My new appleOrange', + 'name' => 'My new apple', + 'created' => '2006-12-25 05:29:39', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:29:39', + 'mytime' => '22:57:17' + ), + 'Sample' => array() + ))), + array( + 'Apple' => array( + 'id' => 7, + 'apple_id' => 6, + 'color' => + 'Some wierd color', + 'name' => 'Some odd color', + 'created' => '2006-12-25 05:34:21', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:34:21', + 'mytime' => '22:57:17' + ), + 'Parent' => array( + 'id' => 6, + 'apple_id' => 4, + 'color' => 'My new appleOrange', + 'name' => 'My new apple', + 'created' => '2006-12-25 05:29:39', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:29:39', + 'mytime' => '22:57:17', + 'Parent' => array( + 'id' => 4, + 'apple_id' => 2, + 'color' => 'Blue Green', + 'name' => 'Test Name', + 'created' => '2006-12-25 05:23:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:36', + 'mytime' => '22:57:17' + ), + 'Sample' => array(), + 'Child' => array( + array( + 'id' => 7, + 'apple_id' => 6, + 'color' => 'Some wierd color', + 'name' => 'Some odd color', + 'created' => '2006-12-25 05:34:21', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:34:21', + 'mytime' => '22:57:17' + ))), + 'Sample' => array( + 'id' => '', + 'apple_id' => '', + 'name' => '' + ), + 'Child' => array())); + $this->assertEquals($expected, $result); + + $result = $TestModel->Parent->unbindModel(array('hasOne' => array('Sample'))); + $this->assertTrue($result); + + $result = $TestModel->find('all'); + $expected = array( + array( + 'Apple' => array( + 'id' => 1, + 'apple_id' => 2, + 'color' => 'Red 1', + 'name' => 'Red Apple 1', + 'created' => '2006-11-22 10:38:58', + 'date' => '1951-01-04', + 'modified' => '2006-12-01 13:31:26', + 'mytime' => '22:57:17'), + 'Parent' => array( + 'id' => 2, + 'apple_id' => 1, + 'color' => 'Bright Red 1', + 'name' => 'Bright Red Apple', + 'created' => '2006-11-22 10:43:13', + 'date' => '2014-01-01', + 'modified' => '2006-11-30 18:38:10', + 'mytime' => '22:57:17', + 'Parent' => array( + 'id' => 1, + 'apple_id' => 2, + 'color' => 'Red 1', + 'name' => 'Red Apple 1', + 'created' => '2006-11-22 10:38:58', + 'date' => '1951-01-04', + 'modified' => '2006-12-01 13:31:26', + 'mytime' => '22:57:17' + ), + 'Child' => array( + array( + 'id' => 1, + 'apple_id' => 2, + 'color' => 'Red 1', + 'name' => 'Red Apple 1', + 'created' => '2006-11-22 10:38:58', + 'date' => '1951-01-04', + 'modified' => '2006-12-01 13:31:26', + 'mytime' => '22:57:17' + ), + array( + 'id' => 3, + 'apple_id' => 2, + 'color' => 'blue green', + 'name' => 'green blue', + 'created' => '2006-12-25 05:13:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:24', + 'mytime' => '22:57:17' + ), + array( + 'id' => 4, + 'apple_id' => 2, + 'color' => 'Blue Green', + 'name' => 'Test Name', + 'created' => '2006-12-25 05:23:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:36', + 'mytime' => '22:57:17' + ))), + 'Sample' => array( + 'id' => '', + 'apple_id' => '', + 'name' => '' + ), + 'Child' => array( + array( + 'id' => 2, + 'apple_id' => 1, + 'color' => 'Bright Red 1', + 'name' => 'Bright Red Apple', + 'created' => '2006-11-22 10:43:13', + 'date' => '2014-01-01', + 'modified' => '2006-11-30 18:38:10', + 'mytime' => '22:57:17', + 'Parent' => array( + 'id' => 1, + 'apple_id' => 2, + 'color' => 'Red 1', + 'name' => 'Red Apple 1', + 'created' => '2006-11-22 10:38:58', + 'date' => '1951-01-04', + 'modified' => '2006-12-01 13:31:26', + 'mytime' => '22:57:17' + ), + 'Sample' => array( + 'id' => 2, + 'apple_id' => 2, + 'name' => 'sample2' + ), + 'Child' => array( + array( + 'id' => 1, + 'apple_id' => 2, + 'color' => 'Red 1', + 'name' => 'Red Apple 1', + 'created' => '2006-11-22 10:38:58', + 'date' => '1951-01-04', + 'modified' => '2006-12-01 13:31:26', + 'mytime' => '22:57:17' + ), + array( + 'id' => 3, + 'apple_id' => 2, + 'color' => 'blue green', + 'name' => 'green blue', + 'created' => '2006-12-25 05:13:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:24', + 'mytime' => '22:57:17' + ), + array( + 'id' => 4, + 'apple_id' => 2, + 'color' => 'Blue Green', + 'name' => 'Test Name', + 'created' => '2006-12-25 05:23:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:36', + 'mytime' => '22:57:17' + ))))), + array( + 'Apple' => array( + 'id' => 2, + 'apple_id' => 1, + 'color' => 'Bright Red 1', + 'name' => 'Bright Red Apple', + 'created' => '2006-11-22 10:43:13', + 'date' => '2014-01-01', + 'modified' => '2006-11-30 18:38:10', + 'mytime' => '22:57:17' + ), + 'Parent' => array( + 'id' => 1, + 'apple_id' => 2, + 'color' => 'Red 1', + 'name' => 'Red Apple 1', + 'created' => '2006-11-22 10:38:58', + 'date' => '1951-01-04', + 'modified' => '2006-12-01 13:31:26', + 'mytime' => '22:57:17', + 'Parent' => array( + 'id' => 2, + 'apple_id' => 1, + 'color' => 'Bright Red 1', + 'name' => 'Bright Red Apple', + 'created' => '2006-11-22 10:43:13', + 'date' => '2014-01-01', + 'modified' => '2006-11-30 18:38:10', + 'mytime' => '22:57:17' + ), + 'Child' => array( + array( + 'id' => 2, + 'apple_id' => 1, + 'color' => 'Bright Red 1', + 'name' => 'Bright Red Apple', + 'created' => '2006-11-22 10:43:13', + 'date' => '2014-01-01', + 'modified' => '2006-11-30 18:38:10', + 'mytime' => '22:57:17' + ))), + 'Sample' => array( + 'id' => 2, + 'apple_id' => 2, + 'name' => 'sample2', + 'Apple' => array( + 'id' => 2, + 'apple_id' => 1, + 'color' => 'Bright Red 1', + 'name' => 'Bright Red Apple', + 'created' => '2006-11-22 10:43:13', + 'date' => '2014-01-01', + 'modified' => '2006-11-30 18:38:10', + 'mytime' => '22:57:17' + )), + 'Child' => array( + array( + 'id' => 1, + 'apple_id' => 2, + 'color' => 'Red 1', + 'name' => 'Red Apple 1', + 'created' => '2006-11-22 10:38:58', + 'date' => '1951-01-04', + 'modified' => '2006-12-01 13:31:26', + 'mytime' => '22:57:17', + 'Parent' => array( + 'id' => 2, + 'apple_id' => 1, + 'color' => 'Bright Red 1', + 'name' => 'Bright Red Apple', + 'created' => '2006-11-22 10:43:13', + 'date' => '2014-01-01', + 'modified' => '2006-11-30 18:38:10', + 'mytime' => '22:57:17' + ), + 'Sample' => array(), + 'Child' => array( + array( + 'id' => 2, + 'apple_id' => 1, + 'color' => 'Bright Red 1', + 'name' => 'Bright Red Apple', + 'created' => '2006-11-22 10:43:13', + 'date' => '2014-01-01', 'modified' => + '2006-11-30 18:38:10', + 'mytime' => '22:57:17' + ))), + array( + 'id' => 3, + 'apple_id' => 2, + 'color' => 'blue green', + 'name' => 'green blue', + 'created' => '2006-12-25 05:13:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:24', + 'mytime' => '22:57:17', + 'Parent' => array( + 'id' => 2, + 'apple_id' => 1, + 'color' => 'Bright Red 1', + 'name' => 'Bright Red Apple', + 'created' => '2006-11-22 10:43:13', + 'date' => '2014-01-01', + 'modified' => '2006-11-30 18:38:10', + 'mytime' => '22:57:17' + ), + 'Sample' => array( + 'id' => 1, + 'apple_id' => 3, + 'name' => 'sample1' + )), + array( + 'id' => 4, + 'apple_id' => 2, + 'color' => 'Blue Green', + 'name' => 'Test Name', + 'created' => '2006-12-25 05:23:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:36', + 'mytime' => '22:57:17', + 'Parent' => array( + 'id' => 2, + 'apple_id' => 1, + 'color' => 'Bright Red 1', + 'name' => 'Bright Red Apple', + 'created' => '2006-11-22 10:43:13', + 'date' => '2014-01-01', + 'modified' => '2006-11-30 18:38:10', + 'mytime' => '22:57:17' + ), + 'Sample' => array( + 'id' => 3, + 'apple_id' => 4, + 'name' => 'sample3' + ), + 'Child' => array( + array( + 'id' => 6, + 'apple_id' => 4, + 'color' => 'My new appleOrange', + 'name' => 'My new apple', + 'created' => '2006-12-25 05:29:39', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:29:39', + 'mytime' => '22:57:17' + ))))), + array( + 'Apple' => array( + 'id' => 3, + 'apple_id' => 2, + 'color' => 'blue green', + 'name' => 'green blue', + 'created' => '2006-12-25 05:13:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:24', + 'mytime' => '22:57:17' + ), + 'Parent' => array( + 'id' => 2, + 'apple_id' => 1, + 'color' => 'Bright Red 1', + 'name' => 'Bright Red Apple', + 'created' => '2006-11-22 10:43:13', + 'date' => '2014-01-01', + 'modified' => '2006-11-30 18:38:10', + 'mytime' => '22:57:17', + 'Parent' => array( + 'id' => 1, + 'apple_id' => 2, + 'color' => 'Red 1', + 'name' => 'Red Apple 1', + 'created' => '2006-11-22 10:38:58', + 'date' => '1951-01-04', + 'modified' => '2006-12-01 13:31:26', + 'mytime' => '22:57:17' + ), + 'Child' => array( + array( + 'id' => 1, + 'apple_id' => 2, + 'color' => 'Red 1', + 'name' => 'Red Apple 1', + 'created' => '2006-11-22 10:38:58', + 'date' => '1951-01-04', + 'modified' => '2006-12-01 13:31:26', + 'mytime' => '22:57:17' + ), + array( + 'id' => 3, + 'apple_id' => 2, + 'color' => 'blue green', + 'name' => 'green blue', + 'created' => '2006-12-25 05:13:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:24', + 'mytime' => '22:57:17' + ), + array( + 'id' => 4, + 'apple_id' => 2, + 'color' => 'Blue Green', + 'name' => 'Test Name', + 'created' => '2006-12-25 05:23:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:36', + 'mytime' => '22:57:17' + ))), + 'Sample' => array( + 'id' => 1, + 'apple_id' => 3, + 'name' => 'sample1', + 'Apple' => array( + 'id' => 3, + 'apple_id' => 2, + 'color' => 'blue green', + 'name' => 'green blue', + 'created' => '2006-12-25 05:13:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:24', + 'mytime' => '22:57:17' + )), + 'Child' => array() + ), + array( + 'Apple' => array( + 'id' => 4, + 'apple_id' => 2, + 'color' => 'Blue Green', + 'name' => 'Test Name', + 'created' => '2006-12-25 05:23:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:36', + 'mytime' => '22:57:17' + ), + 'Parent' => array( + 'id' => 2, + 'apple_id' => 1, + 'color' => 'Bright Red 1', + 'name' => 'Bright Red Apple', + 'created' => '2006-11-22 10:43:13', + 'date' => '2014-01-01', + 'modified' => '2006-11-30 18:38:10', + 'mytime' => '22:57:17', + 'Parent' => array( + 'id' => 1, + 'apple_id' => 2, + 'color' => 'Red 1', + 'name' => 'Red Apple 1', + 'created' => '2006-11-22 10:38:58', + 'date' => '1951-01-04', + 'modified' => '2006-12-01 13:31:26', + 'mytime' => '22:57:17' + ), + 'Child' => array( + array( + 'id' => 1, + 'apple_id' => 2, + 'color' => 'Red 1', + 'name' => 'Red Apple 1', + 'created' => '2006-11-22 10:38:58', + 'date' => '1951-01-04', + 'modified' => '2006-12-01 13:31:26', + 'mytime' => '22:57:17' + ), + array( + 'id' => 3, + 'apple_id' => 2, + 'color' => 'blue green', + 'name' => 'green blue', + 'created' => '2006-12-25 05:13:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:24', + 'mytime' => '22:57:17' + ), + array( + 'id' => 4, + 'apple_id' => 2, + 'color' => 'Blue Green', + 'name' => 'Test Name', + 'created' => '2006-12-25 05:23:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:36', + 'mytime' => '22:57:17' + ))), + 'Sample' => array( + 'id' => 3, + 'apple_id' => 4, + 'name' => 'sample3', + 'Apple' => array( + 'id' => 4, + 'apple_id' => 2, + 'color' => 'Blue Green', + 'name' => 'Test Name', + 'created' => '2006-12-25 05:23:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:36', + 'mytime' => '22:57:17' + )), + 'Child' => array( + array( + 'id' => 6, + 'apple_id' => 4, + 'color' => 'My new appleOrange', + 'name' => 'My new apple', + 'created' => '2006-12-25 05:29:39', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:29:39', + 'mytime' => '22:57:17', + 'Parent' => array( + 'id' => 4, + 'apple_id' => 2, + 'color' => 'Blue Green', + 'name' => 'Test Name', + 'created' => '2006-12-25 05:23:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:36', + 'mytime' => '22:57:17' + ), + 'Sample' => array(), + 'Child' => array( + array( + 'id' => 7, + 'apple_id' => 6, + 'color' => 'Some wierd color', + 'name' => 'Some odd color', + 'created' => '2006-12-25 05:34:21', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:34:21', + 'mytime' => '22:57:17' + ))))), + array( + 'Apple' => array( + 'id' => 5, + 'apple_id' => 5, + 'color' => 'Green', + 'name' => 'Blue Green', + 'created' => '2006-12-25 05:24:06', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:29:16', + 'mytime' => '22:57:17' + ), + 'Parent' => array( + 'id' => 5, + 'apple_id' => 5, + 'color' => 'Green', + 'name' => 'Blue Green', + 'created' => '2006-12-25 05:24:06', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:29:16', + 'mytime' => '22:57:17', + 'Parent' => array( + 'id' => 5, + 'apple_id' => 5, + 'color' => 'Green', + 'name' => 'Blue Green', + 'created' => '2006-12-25 05:24:06', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:29:16', + 'mytime' => '22:57:17' + ), + 'Child' => array( + array( + 'id' => 5, + 'apple_id' => 5, + 'color' => 'Green', + 'name' => 'Blue Green', + 'created' => '2006-12-25 05:24:06', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:29:16', + 'mytime' => '22:57:17' + ))), + 'Sample' => array( + 'id' => 4, + 'apple_id' => 5, + 'name' => 'sample4', + 'Apple' => array( + 'id' => 5, + 'apple_id' => 5, + 'color' => 'Green', + 'name' => 'Blue Green', + 'created' => '2006-12-25 05:24:06', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:29:16', + 'mytime' => '22:57:17' + )), + 'Child' => array( + array( + 'id' => 5, + 'apple_id' => 5, + 'color' => 'Green', + 'name' => 'Blue Green', + 'created' => '2006-12-25 05:24:06', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:29:16', + 'mytime' => '22:57:17', + 'Parent' => array( + 'id' => 5, + 'apple_id' => 5, + 'color' => 'Green', + 'name' => 'Blue Green', + 'created' => '2006-12-25 05:24:06', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:29:16', + 'mytime' => '22:57:17' + ), + 'Sample' => array( + 'id' => 4, + 'apple_id' => 5, + 'name' => 'sample4' + ), + 'Child' => array( + array( + 'id' => 5, + 'apple_id' => 5, + 'color' => 'Green', + 'name' => 'Blue Green', + 'created' => '2006-12-25 05:24:06', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:29:16', + 'mytime' => '22:57:17' + ))))), + array( + 'Apple' => array( + 'id' => 6, + 'apple_id' => 4, + 'color' => 'My new appleOrange', + 'name' => 'My new apple', + 'created' => '2006-12-25 05:29:39', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:29:39', + 'mytime' => '22:57:17' + ), + 'Parent' => array( + 'id' => 4, + 'apple_id' => 2, + 'color' => 'Blue Green', + 'name' => 'Test Name', + 'created' => '2006-12-25 05:23:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:36', + 'mytime' => '22:57:17', + 'Parent' => array( + 'id' => 2, + 'apple_id' => 1, + 'color' => 'Bright Red 1', + 'name' => 'Bright Red Apple', + 'created' => '2006-11-22 10:43:13', + 'date' => '2014-01-01', + 'modified' => '2006-11-30 18:38:10', + 'mytime' => '22:57:17' + ), + 'Child' => array( + array( + 'id' => 6, + 'apple_id' => 4, + 'color' => 'My new appleOrange', + 'name' => 'My new apple', + 'created' => '2006-12-25 05:29:39', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:29:39', + 'mytime' => '22:57:17' + ))), + 'Sample' => array( + 'id' => '', + 'apple_id' => '', + 'name' => '' + ), + 'Child' => array( + array( + 'id' => 7, + 'apple_id' => 6, + 'color' => 'Some wierd color', + 'name' => 'Some odd color', + 'created' => '2006-12-25 05:34:21', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:34:21', + 'mytime' => '22:57:17', + 'Parent' => array( + 'id' => 6, + 'apple_id' => 4, + 'color' => 'My new appleOrange', + 'name' => 'My new apple', + 'created' => '2006-12-25 05:29:39', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:29:39', + 'mytime' => '22:57:17' + ), + 'Sample' => array() + ))), + array( + 'Apple' => array( + 'id' => 7, + 'apple_id' => 6, + 'color' => 'Some wierd color', + 'name' => 'Some odd color', + 'created' => '2006-12-25 05:34:21', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:34:21', + 'mytime' => '22:57:17' + ), + 'Parent' => array( + 'id' => 6, + 'apple_id' => 4, + 'color' => 'My new appleOrange', + 'name' => 'My new apple', + 'created' => '2006-12-25 05:29:39', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:29:39', + 'mytime' => '22:57:17', + 'Parent' => array( + 'id' => 4, + 'apple_id' => 2, + 'color' => 'Blue Green', + 'name' => 'Test Name', + 'created' => '2006-12-25 05:23:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:36', + 'mytime' => '22:57:17' + ), + 'Child' => array( + array( + 'id' => 7, + 'apple_id' => 6, + 'color' => 'Some wierd color', + 'name' => 'Some odd color', + 'created' => '2006-12-25 05:34:21', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:34:21', + 'mytime' => '22:57:17' + ))), + 'Sample' => array( + 'id' => '', + 'apple_id' => '', + 'name' => '' + ), + 'Child' => array() + )); + + $this->assertEquals($expected, $result); + + $result = $TestModel->Parent->unbindModel(array('hasOne' => array('Sample'))); + $this->assertTrue($result); + + $result = $TestModel->unbindModel(array('hasMany' => array('Child'))); + $this->assertTrue($result); + + $result = $TestModel->find('all'); + $expected = array( + array( + 'Apple' => array( + 'id' => 1, + 'apple_id' => 2, + 'color' => 'Red 1', + 'name' => 'Red Apple 1', + 'created' => '2006-11-22 10:38:58', + 'date' => '1951-01-04', + 'modified' => '2006-12-01 13:31:26', + 'mytime' => '22:57:17' + ), + 'Parent' => array( + 'id' => 2, + 'apple_id' => 1, + 'color' => 'Bright Red 1', + 'name' => 'Bright Red Apple', + 'created' => '2006-11-22 10:43:13', + 'date' => '2014-01-01', + 'modified' => '2006-11-30 18:38:10', + 'mytime' => '22:57:17', + 'Parent' => array( + 'id' => 1, + 'apple_id' => 2, + 'color' => 'Red 1', + 'name' => 'Red Apple 1', + 'created' => '2006-11-22 10:38:58', + 'date' => '1951-01-04', + 'modified' => '2006-12-01 13:31:26', + 'mytime' => '22:57:17' + ), + 'Child' => array( + array( + 'id' => 1, + 'apple_id' => 2, + 'color' => 'Red 1', + 'name' => 'Red Apple 1', + 'created' => '2006-11-22 10:38:58', + 'date' => '1951-01-04', + 'modified' => '2006-12-01 13:31:26', + 'mytime' => '22:57:17' + ), + array( + 'id' => 3, + 'apple_id' => 2, + 'color' => 'blue green', + 'name' => 'green blue', + 'created' => '2006-12-25 05:13:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:24', + 'mytime' => '22:57:17' + ), + array( + 'id' => 4, + 'apple_id' => 2, + 'color' => 'Blue Green', + 'name' => 'Test Name', + 'created' => '2006-12-25 05:23:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:36', + 'mytime' => '22:57:17' + ))), + 'Sample' => array( + 'id' => '', + 'apple_id' => '', + 'name' => '' + )), + array( + 'Apple' => array( + 'id' => 2, + 'apple_id' => 1, + 'color' => 'Bright Red 1', + 'name' => 'Bright Red Apple', + 'created' => '2006-11-22 10:43:13', + 'date' => '2014-01-01', + 'modified' => '2006-11-30 18:38:10', + 'mytime' => '22:57:17' + ), + 'Parent' => array( + 'id' => 1, + 'apple_id' => 2, + 'color' => 'Red 1', + 'name' => 'Red Apple 1', + 'created' => '2006-11-22 10:38:58', + 'date' => '1951-01-04', + 'modified' => '2006-12-01 13:31:26', + 'mytime' => '22:57:17', + 'Parent' => array( + 'id' => 2, + 'apple_id' => 1, + 'color' => 'Bright Red 1', + 'name' => 'Bright Red Apple', + 'created' => '2006-11-22 10:43:13', + 'date' => '2014-01-01', + 'modified' => '2006-11-30 18:38:10', + 'mytime' => '22:57:17' + ), + 'Child' => array( + array( + 'id' => 2, + 'apple_id' => 1, + 'color' => 'Bright Red 1', + 'name' => 'Bright Red Apple', + 'created' => '2006-11-22 10:43:13', + 'date' => '2014-01-01', + 'modified' => '2006-11-30 18:38:10', + 'mytime' => '22:57:17' + ))), + 'Sample' => array( + 'id' => 2, + 'apple_id' => 2, + 'name' => 'sample2', + 'Apple' => array( + 'id' => 2, + 'apple_id' => 1, + 'color' => 'Bright Red 1', + 'name' => 'Bright Red Apple', + 'created' => '2006-11-22 10:43:13', + 'date' => '2014-01-01', + 'modified' => '2006-11-30 18:38:10', + 'mytime' => '22:57:17' + ))), + array( + 'Apple' => array( + 'id' => 3, + 'apple_id' => 2, + 'color' => 'blue green', + 'name' => 'green blue', + 'created' => '2006-12-25 05:13:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:24', + 'mytime' => '22:57:17' + ), + 'Parent' => array( + 'id' => 2, + 'apple_id' => 1, + 'color' => 'Bright Red 1', + 'name' => 'Bright Red Apple', + 'created' => '2006-11-22 10:43:13', + 'date' => '2014-01-01', + 'modified' => '2006-11-30 18:38:10', + 'mytime' => '22:57:17', + 'Parent' => array( + 'id' => 1, + 'apple_id' => 2, + 'color' => 'Red 1', + 'name' => 'Red Apple 1', + 'created' => '2006-11-22 10:38:58', + 'date' => '1951-01-04', + 'modified' => '2006-12-01 13:31:26', + 'mytime' => '22:57:17' + ), + 'Child' => array( + array( + 'id' => 1, + 'apple_id' => 2, + 'color' => 'Red 1', + 'name' => 'Red Apple 1', + 'created' => '2006-11-22 10:38:58', + 'date' => '1951-01-04', + 'modified' => '2006-12-01 13:31:26', + 'mytime' => '22:57:17' + ), + array( + 'id' => 3, + 'apple_id' => 2, + 'color' => 'blue green', + 'name' => 'green blue', + 'created' => '2006-12-25 05:13:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:24', + 'mytime' => '22:57:17' + ), + array( + 'id' => 4, + 'apple_id' => 2, + 'color' => 'Blue Green', + 'name' => 'Test Name', + 'created' => '2006-12-25 05:23:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:36', + 'mytime' => '22:57:17' + ))), + 'Sample' => array( + 'id' => 1, + 'apple_id' => 3, + 'name' => 'sample1', + 'Apple' => array( + 'id' => 3, + 'apple_id' => 2, + 'color' => 'blue green', + 'name' => 'green blue', + 'created' => '2006-12-25 05:13:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:24', + 'mytime' => '22:57:17' + ))), + array( + 'Apple' => array( + 'id' => 4, + 'apple_id' => 2, + 'color' => 'Blue Green', + 'name' => 'Test Name', + 'created' => '2006-12-25 05:23:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:36', + 'mytime' => '22:57:17' + ), + 'Parent' => array( + 'id' => 2, + 'apple_id' => 1, + 'color' => 'Bright Red 1', + 'name' => 'Bright Red Apple', + 'created' => '2006-11-22 10:43:13', + 'date' => '2014-01-01', + 'modified' => '2006-11-30 18:38:10', + 'mytime' => '22:57:17', + 'Parent' => array( + 'id' => 1, + 'apple_id' => 2, + 'color' => 'Red 1', + 'name' => 'Red Apple 1', + 'created' => '2006-11-22 10:38:58', + 'date' => '1951-01-04', + 'modified' => '2006-12-01 13:31:26', + 'mytime' => '22:57:17' + ), + 'Child' => array( + array( + 'id' => 1, + 'apple_id' => 2, + 'color' => 'Red 1', + 'name' => 'Red Apple 1', + 'created' => '2006-11-22 10:38:58', + 'date' => '1951-01-04', + 'modified' => '2006-12-01 13:31:26', + 'mytime' => '22:57:17' + ), + array( + 'id' => 3, + 'apple_id' => 2, + 'color' => 'blue green', + 'name' => 'green blue', + 'created' => '2006-12-25 05:13:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:24', + 'mytime' => '22:57:17' + ), + array( + 'id' => 4, + 'apple_id' => 2, + 'color' => 'Blue Green', + 'name' => 'Test Name', + 'created' => '2006-12-25 05:23:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:36', + 'mytime' => '22:57:17' + ))), + 'Sample' => array( + 'id' => 3, + 'apple_id' => 4, + 'name' => 'sample3', + 'Apple' => array( + 'id' => 4, + 'apple_id' => 2, + 'color' => 'Blue Green', + 'name' => 'Test Name', + 'created' => '2006-12-25 05:23:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:36', + 'mytime' => '22:57:17' + ))), + array( + 'Apple' => array( + 'id' => 5, + 'apple_id' => 5, + 'color' => 'Green', + 'name' => 'Blue Green', + 'created' => '2006-12-25 05:24:06', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:29:16', + 'mytime' => '22:57:17' + ), + 'Parent' => array( + 'id' => 5, + 'apple_id' => 5, + 'color' => 'Green', + 'name' => 'Blue Green', + 'created' => '2006-12-25 05:24:06', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:29:16', + 'mytime' => '22:57:17', + 'Parent' => array( + 'id' => 5, + 'apple_id' => 5, + 'color' => 'Green', + 'name' => 'Blue Green', + 'created' => '2006-12-25 05:24:06', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:29:16', + 'mytime' => '22:57:17' + ), + 'Child' => array( + array( + 'id' => 5, + 'apple_id' => 5, + 'color' => 'Green', + 'name' => 'Blue Green', + 'created' => '2006-12-25 05:24:06', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:29:16', + 'mytime' => '22:57:17' + ))), + 'Sample' => array( + 'id' => 4, + 'apple_id' => 5, + 'name' => 'sample4', + 'Apple' => array( + 'id' => 5, + 'apple_id' => 5, + 'color' => 'Green', + 'name' => 'Blue Green', + 'created' => '2006-12-25 05:24:06', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:29:16', + 'mytime' => '22:57:17' + ))), + array( + 'Apple' => array( + 'id' => 6, + 'apple_id' => 4, + 'color' => 'My new appleOrange', + 'name' => 'My new apple', + 'created' => '2006-12-25 05:29:39', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:29:39', + 'mytime' => '22:57:17' + ), + 'Parent' => array( + 'id' => 4, + 'apple_id' => 2, + 'color' => 'Blue Green', + 'name' => 'Test Name', + 'created' => '2006-12-25 05:23:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:36', + 'mytime' => '22:57:17', + 'Parent' => array( + 'id' => 2, + 'apple_id' => 1, + 'color' => 'Bright Red 1', + 'name' => 'Bright Red Apple', + 'created' => '2006-11-22 10:43:13', + 'date' => '2014-01-01', + 'modified' => '2006-11-30 18:38:10', + 'mytime' => '22:57:17' + ), + 'Child' => array( + array( + 'id' => 6, + 'apple_id' => 4, + 'color' => 'My new appleOrange', + 'name' => 'My new apple', + 'created' => '2006-12-25 05:29:39', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:29:39', + 'mytime' => '22:57:17' + ))), + 'Sample' => array( + 'id' => '', + 'apple_id' => '', + 'name' => '' + )), + array( + 'Apple' => array( + 'id' => 7, + 'apple_id' => 6, + 'color' => 'Some wierd color', + 'name' => 'Some odd color', + 'created' => '2006-12-25 05:34:21', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:34:21', + 'mytime' => '22:57:17' + ), + 'Parent' => array( + 'id' => 6, + 'apple_id' => 4, + 'color' => 'My new appleOrange', + 'name' => 'My new apple', + 'created' => '2006-12-25 05:29:39', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:29:39', + 'mytime' => '22:57:17', + 'Parent' => array( + 'id' => 4, + 'apple_id' => 2, + 'color' => 'Blue Green', + 'name' => 'Test Name', + 'created' => '2006-12-25 05:23:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:36', + 'mytime' => '22:57:17' + ), + 'Child' => array( + array( + 'id' => 7, + 'apple_id' => 6, + 'color' => 'Some wierd color', + 'name' => 'Some odd color', + 'created' => '2006-12-25 05:34:21', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:34:21', + 'mytime' => '22:57:17' + ))), + 'Sample' => array( + 'id' => '', + 'apple_id' => '', + 'name' => '' + ))); + + $this->assertEquals($expected, $result); + + $result = $TestModel->unbindModel(array('hasMany' => array('Child'))); + $this->assertTrue($result); + + $result = $TestModel->Sample->unbindModel(array('belongsTo' => array('Apple'))); + $this->assertTrue($result); + + $result = $TestModel->find('all'); + $expected = array( + array( + 'Apple' => array( + 'id' => 1, + 'apple_id' => 2, + 'color' => 'Red 1', + 'name' => 'Red Apple 1', + 'created' => '2006-11-22 10:38:58', + 'date' => '1951-01-04', + 'modified' => '2006-12-01 13:31:26', + 'mytime' => '22:57:17' + ), + 'Parent' => array( + 'id' => 2, + 'apple_id' => 1, + 'color' => 'Bright Red 1', + 'name' => 'Bright Red Apple', + 'created' => '2006-11-22 10:43:13', + 'date' => '2014-01-01', + 'modified' => '2006-11-30 18:38:10', + 'mytime' => '22:57:17', + 'Parent' => array( + 'id' => 1, + 'apple_id' => 2, + 'color' => 'Red 1', + 'name' => 'Red Apple 1', + 'created' => '2006-11-22 10:38:58', + 'date' => '1951-01-04', + 'modified' => '2006-12-01 13:31:26', + 'mytime' => '22:57:17' + ), + 'Sample' => array( + 'id' => 2, + 'apple_id' => 2, + 'name' => 'sample2' + ), + 'Child' => array( + array( + 'id' => 1, + 'apple_id' => 2, + 'color' => 'Red 1', + 'name' => 'Red Apple 1', + 'created' => '2006-11-22 10:38:58', + 'date' => '1951-01-04', + 'modified' => '2006-12-01 13:31:26', + 'mytime' => '22:57:17' + ), + array( + 'id' => 3, + 'apple_id' => 2, + 'color' => 'blue green', + 'name' => 'green blue', + 'created' => '2006-12-25 05:13:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:24', + 'mytime' => '22:57:17' + ), + array( + 'id' => 4, + 'apple_id' => 2, + 'color' => 'Blue Green', + 'name' => 'Test Name', + 'created' => '2006-12-25 05:23:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:36', + 'mytime' => '22:57:17' + ))), + 'Sample' => array( + 'id' => '', + 'apple_id' => '', + 'name' => '' + )), + array( + 'Apple' => array( + 'id' => 2, + 'apple_id' => 1, + 'color' => 'Bright Red 1', + 'name' => 'Bright Red Apple', + 'created' => '2006-11-22 10:43:13', + 'date' => '2014-01-01', + 'modified' => '2006-11-30 18:38:10', + 'mytime' => '22:57:17' + ), + 'Parent' => array( + 'id' => 1, + 'apple_id' => 2, + 'color' => 'Red 1', + 'name' => 'Red Apple 1', + 'created' => '2006-11-22 10:38:58', + 'date' => '1951-01-04', + 'modified' => '2006-12-01 13:31:26', + 'mytime' => '22:57:17', + 'Parent' => array( + 'id' => 2, + 'apple_id' => 1, + 'color' => 'Bright Red 1', + 'name' => 'Bright Red Apple', + 'created' => '2006-11-22 10:43:13', + 'date' => '2014-01-01', + 'modified' => '2006-11-30 18:38:10', + 'mytime' => '22:57:17' + ), + 'Sample' => array(), + 'Child' => array( + array( + 'id' => 2, + 'apple_id' => 1, + 'color' => 'Bright Red 1', + 'name' => 'Bright Red Apple', + 'created' => '2006-11-22 10:43:13', + 'date' => '2014-01-01', + 'modified' => '2006-11-30 18:38:10', + 'mytime' => '22:57:17' + ))), + 'Sample' => array( + 'id' => 2, + 'apple_id' => 2, + 'name' => 'sample2' + )), + array( + 'Apple' => array( + 'id' => 3, + 'apple_id' => 2, + 'color' => 'blue green', + 'name' => 'green blue', + 'created' => '2006-12-25 05:13:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:24', + 'mytime' => '22:57:17' + ), + 'Parent' => array( + 'id' => 2, + 'apple_id' => 1, + 'color' => 'Bright Red 1', + 'name' => 'Bright Red Apple', + 'created' => '2006-11-22 10:43:13', + 'date' => '2014-01-01', + 'modified' => '2006-11-30 18:38:10', + 'mytime' => '22:57:17', + 'Parent' => array( + 'id' => 1, + 'apple_id' => 2, + 'color' => 'Red 1', + 'name' => 'Red Apple 1', + 'created' => '2006-11-22 10:38:58', + 'date' => '1951-01-04', + 'modified' => '2006-12-01 13:31:26', + 'mytime' => '22:57:17' + ), + 'Sample' => array( + 'id' => 2, + 'apple_id' => 2, + 'name' => 'sample2' + ), + 'Child' => array( + array( + 'id' => 1, + 'apple_id' => 2, + 'color' => 'Red 1', + 'name' => 'Red Apple 1', + 'created' => '2006-11-22 10:38:58', + 'date' => '1951-01-04', + 'modified' => '2006-12-01 13:31:26', + 'mytime' => '22:57:17' + ), + array( + 'id' => 3, + 'apple_id' => 2, + 'color' => 'blue green', + 'name' => 'green blue', + 'created' => '2006-12-25 05:13:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:24', + 'mytime' => '22:57:17' + ), + array( + 'id' => 4, + 'apple_id' => 2, + 'color' => 'Blue Green', + 'name' => 'Test Name', + 'created' => '2006-12-25 05:23:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:36', + 'mytime' => '22:57:17' + ))), + 'Sample' => array( + 'id' => 1, + 'apple_id' => 3, + 'name' => 'sample1' + )), + array( + 'Apple' => array( + 'id' => 4, + 'apple_id' => 2, + 'color' => 'Blue Green', + 'name' => 'Test Name', + 'created' => '2006-12-25 05:23:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:36', + 'mytime' => '22:57:17' + ), + 'Parent' => array( + 'id' => 2, + 'apple_id' => 1, + 'color' => 'Bright Red 1', + 'name' => 'Bright Red Apple', + 'created' => '2006-11-22 10:43:13', + 'date' => '2014-01-01', + 'modified' => '2006-11-30 18:38:10', + 'mytime' => '22:57:17', + 'Parent' => array( + 'id' => 1, + 'apple_id' => 2, + 'color' => 'Red 1', + 'name' => 'Red Apple 1', + 'created' => '2006-11-22 10:38:58', + 'date' => '1951-01-04', + 'modified' => '2006-12-01 13:31:26', + 'mytime' => '22:57:17' + ), + 'Sample' => array( + 'id' => 2, + 'apple_id' => 2, + 'name' => 'sample2' + ), + 'Child' => array( + array( + 'id' => 1, + 'apple_id' => 2, + 'color' => 'Red 1', + 'name' => 'Red Apple 1', + 'created' => '2006-11-22 10:38:58', + 'date' => '1951-01-04', + 'modified' => '2006-12-01 13:31:26', + 'mytime' => '22:57:17' + ), + array( + 'id' => 3, + 'apple_id' => 2, + 'color' => 'blue green', + 'name' => 'green blue', + 'created' => '2006-12-25 05:13:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:24', + 'mytime' => '22:57:17' + ), + array( + 'id' => 4, + 'apple_id' => 2, + 'color' => 'Blue Green', + 'name' => 'Test Name', + 'created' => '2006-12-25 05:23:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:36', + 'mytime' => '22:57:17' + ))), + 'Sample' => array( + 'id' => 3, + 'apple_id' => 4, + 'name' => 'sample3' + )), + array( + 'Apple' => array( + 'id' => 5, + 'apple_id' => 5, + 'color' => 'Green', + 'name' => 'Blue Green', + 'created' => '2006-12-25 05:24:06', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:29:16', + 'mytime' => '22:57:17' + ), + 'Parent' => array( + 'id' => 5, + 'apple_id' => 5, + 'color' => 'Green', + 'name' => 'Blue Green', + 'created' => '2006-12-25 05:24:06', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:29:16', + 'mytime' => '22:57:17', + 'Parent' => array( + 'id' => 5, + 'apple_id' => 5, + 'color' => 'Green', + 'name' => 'Blue Green', + 'created' => '2006-12-25 05:24:06', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:29:16', + 'mytime' => '22:57:17' + ), + 'Sample' => array( + 'id' => 4, + 'apple_id' => 5, + 'name' => 'sample4' + ), + 'Child' => array( + array( + 'id' => 5, + 'apple_id' => 5, + 'color' => 'Green', + 'name' => 'Blue Green', + 'created' => '2006-12-25 05:24:06', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:29:16', + 'mytime' => '22:57:17' + ))), + 'Sample' => array( + 'id' => 4, + 'apple_id' => 5, + 'name' => 'sample4' + )), + array( + 'Apple' => array( + 'id' => 6, + 'apple_id' => 4, + 'color' => 'My new appleOrange', + 'name' => 'My new apple', + 'created' => '2006-12-25 05:29:39', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:29:39', + 'mytime' => '22:57:17' + ), + 'Parent' => array( + 'id' => 4, + 'apple_id' => 2, + 'color' => 'Blue Green', + 'name' => 'Test Name', + 'created' => '2006-12-25 05:23:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:36', + 'mytime' => '22:57:17', + 'Parent' => array( + 'id' => 2, + 'apple_id' => 1, + 'color' => 'Bright Red 1', + 'name' => 'Bright Red Apple', + 'created' => '2006-11-22 10:43:13', + 'date' => '2014-01-01', + 'modified' => '2006-11-30 18:38:10', + 'mytime' => '22:57:17' + ), + 'Sample' => array( + 'id' => 3, + 'apple_id' => 4, + 'name' => 'sample3' + ), + 'Child' => array( + array( + 'id' => 6, + 'apple_id' => 4, + 'color' => 'My new appleOrange', + 'name' => 'My new apple', + 'created' => '2006-12-25 05:29:39', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:29:39', + 'mytime' => '22:57:17' + ))), + 'Sample' => array( + 'id' => '', + 'apple_id' => '', + 'name' => '' + )), + array( + 'Apple' => array( + 'id' => 7, + 'apple_id' => 6, + 'color' => 'Some wierd color', + 'name' => 'Some odd color', + 'created' => '2006-12-25 05:34:21', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:34:21', + 'mytime' => '22:57:17' + ), + 'Parent' => array( + 'id' => 6, + 'apple_id' => 4, + 'color' => 'My new appleOrange', + 'name' => 'My new apple', + 'created' => '2006-12-25 05:29:39', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:29:39', + 'mytime' => '22:57:17', + 'Parent' => array( + 'id' => 4, + 'apple_id' => 2, + 'color' => 'Blue Green', + 'name' => 'Test Name', + 'created' => '2006-12-25 05:23:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:36', + 'mytime' => '22:57:17' + ), + 'Sample' => array(), + 'Child' => array( + array( + 'id' => 7, + 'apple_id' => 6, + 'color' => 'Some wierd color', + 'name' => 'Some odd color', + 'created' => '2006-12-25 05:34:21', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:34:21', + 'mytime' => '22:57:17' + ))), + 'Sample' => array( + 'id' => '', + 'apple_id' => '', + 'name' => '' + ))); + $this->assertEquals($expected, $result); + + $result = $TestModel->Parent->unbindModel(array('belongsTo' => array('Parent'))); + $this->assertTrue($result); + + $result = $TestModel->unbindModel(array('hasMany' => array('Child'))); + $this->assertTrue($result); + + $result = $TestModel->find('all'); + $expected = array( + array( + 'Apple' => array( + 'id' => 1, + 'apple_id' => 2, + 'color' => 'Red 1', + 'name' => 'Red Apple 1', + 'created' => '2006-11-22 10:38:58', + 'date' => '1951-01-04', + 'modified' => '2006-12-01 13:31:26', + 'mytime' => '22:57:17' + ), + 'Parent' => array( + 'id' => 2, + 'apple_id' => 1, + 'color' => 'Bright Red 1', + 'name' => 'Bright Red Apple', + 'created' => '2006-11-22 10:43:13', + 'date' => '2014-01-01', + 'modified' => '2006-11-30 18:38:10', + 'mytime' => '22:57:17', + 'Sample' => array( + 'id' => 2, + 'apple_id' => 2, + 'name' => 'sample2' + ), + 'Child' => array( + array( + 'id' => 1, + 'apple_id' => 2, + 'color' => 'Red 1', + 'name' => 'Red Apple 1', + 'created' => '2006-11-22 10:38:58', + 'date' => '1951-01-04', + 'modified' => '2006-12-01 13:31:26', + 'mytime' => '22:57:17' + ), + array( + 'id' => 3, + 'apple_id' => 2, + 'color' => 'blue green', + 'name' => 'green blue', + 'created' => '2006-12-25 05:13:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:24', + 'mytime' => '22:57:17' + ), + array( + 'id' => 4, + 'apple_id' => 2, + 'color' => 'Blue Green', + 'name' => 'Test Name', + 'created' => '2006-12-25 05:23:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:36', + 'mytime' => '22:57:17' + ))), + 'Sample' => array( + 'id' => '', + 'apple_id' => '', + 'name' => '' + )), + array( + 'Apple' => array( + 'id' => 2, + 'apple_id' => 1, + 'color' => 'Bright Red 1', + 'name' => 'Bright Red Apple', + 'created' => '2006-11-22 10:43:13', + 'date' => '2014-01-01', + 'modified' => '2006-11-30 18:38:10', + 'mytime' => '22:57:17' + ), + 'Parent' => array( + 'id' => 1, + 'apple_id' => 2, + 'color' => 'Red 1', + 'name' => 'Red Apple 1', + 'created' => '2006-11-22 10:38:58', + 'date' => '1951-01-04', + 'modified' => '2006-12-01 13:31:26', + 'mytime' => '22:57:17', + 'Sample' => array(), + 'Child' => array( + array( + 'id' => 2, + 'apple_id' => 1, + 'color' => 'Bright Red 1', + 'name' => 'Bright Red Apple', + 'created' => '2006-11-22 10:43:13', + 'date' => '2014-01-01', + 'modified' => '2006-11-30 18:38:10', + 'mytime' => '22:57:17' + ))), + 'Sample' => array( + 'id' => 2, + 'apple_id' => 2, + 'name' => 'sample2', + 'Apple' => array( + 'id' => 2, + 'apple_id' => 1, + 'color' => 'Bright Red 1', + 'name' => 'Bright Red Apple', + 'created' => '2006-11-22 10:43:13', + 'date' => '2014-01-01', + 'modified' => '2006-11-30 18:38:10', + 'mytime' => '22:57:17' + ))), + array( + 'Apple' => array( + 'id' => 3, + 'apple_id' => 2, + 'color' => 'blue green', + 'name' => 'green blue', + 'created' => '2006-12-25 05:13:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:24', + 'mytime' => '22:57:17' + ), + 'Parent' => array( + 'id' => 2, + 'apple_id' => 1, + 'color' => 'Bright Red 1', + 'name' => 'Bright Red Apple', + 'created' => '2006-11-22 10:43:13', + 'date' => '2014-01-01', + 'modified' => '2006-11-30 18:38:10', + 'mytime' => '22:57:17', + 'Sample' => array( + 'id' => 2, + 'apple_id' => 2, + 'name' => 'sample2' + ), + 'Child' => array( + array( + 'id' => 1, + 'apple_id' => 2, + 'color' => 'Red 1', + 'name' => 'Red Apple 1', + 'created' => '2006-11-22 10:38:58', + 'date' => '1951-01-04', + 'modified' => '2006-12-01 13:31:26', + 'mytime' => '22:57:17' + ), + array( + 'id' => 3, + 'apple_id' => 2, + 'color' => 'blue green', + 'name' => 'green blue', + 'created' => '2006-12-25 05:13:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:24', + 'mytime' => '22:57:17' + ), + array( + 'id' => 4, + 'apple_id' => 2, + 'color' => 'Blue Green', + 'name' => 'Test Name', + 'created' => '2006-12-25 05:23:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:36', + 'mytime' => '22:57:17' + ))), + 'Sample' => array( + 'id' => 1, + 'apple_id' => 3, + 'name' => 'sample1', + 'Apple' => array( + 'id' => 3, + 'apple_id' => 2, + 'color' => 'blue green', + 'name' => 'green blue', + 'created' => '2006-12-25 05:13:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:24', + 'mytime' => '22:57:17' + ))), + array( + 'Apple' => array( + 'id' => 4, + 'apple_id' => 2, + 'color' => 'Blue Green', + 'name' => 'Test Name', + 'created' => '2006-12-25 05:23:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:36', + 'mytime' => '22:57:17' + ), + 'Parent' => array( + 'id' => 2, + 'apple_id' => 1, + 'color' => 'Bright Red 1', + 'name' => 'Bright Red Apple', + 'created' => '2006-11-22 10:43:13', + 'date' => '2014-01-01', + 'modified' => '2006-11-30 18:38:10', + 'mytime' => '22:57:17', + 'Sample' => array( + 'id' => 2, + 'apple_id' => 2, + 'name' => 'sample2' + ), + 'Child' => array( + array( + 'id' => 1, + 'apple_id' => 2, + 'color' => 'Red 1', + 'name' => 'Red Apple 1', + 'created' => '2006-11-22 10:38:58', + 'date' => '1951-01-04', + 'modified' => '2006-12-01 13:31:26', + 'mytime' => '22:57:17' + ), + array( + 'id' => 3, + 'apple_id' => 2, + 'color' => 'blue green', + 'name' => 'green blue', + 'created' => '2006-12-25 05:13:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:24', + 'mytime' => '22:57:17' + ), + array( + 'id' => 4, + 'apple_id' => 2, + 'color' => 'Blue Green', + 'name' => 'Test Name', + 'created' => '2006-12-25 05:23:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:36', + 'mytime' => '22:57:17' + ))), + 'Sample' => array( + 'id' => 3, + 'apple_id' => 4, + 'name' => 'sample3', + 'Apple' => array( + 'id' => 4, + 'apple_id' => 2, + 'color' => 'Blue Green', + 'name' => 'Test Name', + 'created' => '2006-12-25 05:23:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:36', + 'mytime' => '22:57:17' + ))), + array( + 'Apple' => array( + 'id' => 5, + 'apple_id' => 5, + 'color' => 'Green', + 'name' => 'Blue Green', + 'created' => '2006-12-25 05:24:06', + 'date' => '2006-12-25', + 'modified' => + '2006-12-25 05:29:16', + 'mytime' => '22:57:17' + ), + 'Parent' => array( + 'id' => 5, + 'apple_id' => 5, + 'color' => 'Green', + 'name' => 'Blue Green', + 'created' => '2006-12-25 05:24:06', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:29:16', + 'mytime' => '22:57:17', + 'Sample' => array( + 'id' => 4, + 'apple_id' => 5, + 'name' => 'sample4' + ), + 'Child' => array( + array( + 'id' => 5, + 'apple_id' => 5, + 'color' => 'Green', + 'name' => 'Blue Green', + 'created' => '2006-12-25 05:24:06', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:29:16', + 'mytime' => '22:57:17' + ))), + 'Sample' => array( + 'id' => 4, + 'apple_id' => 5, + 'name' => 'sample4', + 'Apple' => array( + 'id' => 5, + 'apple_id' => 5, + 'color' => 'Green', + 'name' => 'Blue Green', + 'created' => '2006-12-25 05:24:06', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:29:16', + 'mytime' => '22:57:17' + ))), + array( + 'Apple' => array( + 'id' => 6, + 'apple_id' => 4, + 'color' => 'My new appleOrange', + 'name' => 'My new apple', + 'created' => '2006-12-25 05:29:39', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:29:39', + 'mytime' => '22:57:17'), + 'Parent' => array( + 'id' => 4, + 'apple_id' => 2, + 'color' => 'Blue Green', + 'name' => 'Test Name', + 'created' => '2006-12-25 05:23:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:36', + 'mytime' => '22:57:17', + 'Sample' => array( + 'id' => 3, + 'apple_id' => 4, + 'name' => 'sample3' + ), + 'Child' => array( + array( + 'id' => 6, + 'apple_id' => 4, + 'color' => 'My new appleOrange', + 'name' => 'My new apple', + 'created' => '2006-12-25 05:29:39', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:29:39', + 'mytime' => '22:57:17' + ))), + 'Sample' => array( + 'id' => '', + 'apple_id' => '', + 'name' => '' + )), + array( + 'Apple' => array( + 'id' => 7, + 'apple_id' => 6, + 'color' => 'Some wierd color', + 'name' => 'Some odd color', + 'created' => '2006-12-25 05:34:21', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:34:21', + 'mytime' => '22:57:17' + ), + 'Parent' => array( + 'id' => 6, + 'apple_id' => 4, + 'color' => 'My new appleOrange', + 'name' => 'My new apple', + 'created' => '2006-12-25 05:29:39', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:29:39', + 'mytime' => '22:57:17', + 'Sample' => array(), + 'Child' => array( + array( + 'id' => 7, + 'apple_id' => 6, + 'color' => 'Some wierd color', + 'name' => 'Some odd color', + 'created' => '2006-12-25 05:34:21', + 'date' => '2006-12-25', 'modified' => + '2006-12-25 05:34:21', + 'mytime' => '22:57:17' + ))), + 'Sample' => array( + 'id' => '', + 'apple_id' => '', + 'name' => '' + ))); + $this->assertEquals($expected, $result); + } + +/** + * testSelfAssociationAfterFind method + * + * @return void + */ + public function testSelfAssociationAfterFind() { + $this->loadFixtures('Apple', 'Sample'); + $afterFindModel = new NodeAfterFind(); + $afterFindModel->recursive = 3; + $afterFindData = $afterFindModel->find('all'); + + $duplicateModel = new NodeAfterFind(); + $duplicateModel->recursive = 3; + $duplicateModelData = $duplicateModel->find('all'); + + $noAfterFindModel = new NodeNoAfterFind(); + $noAfterFindModel->recursive = 3; + $noAfterFindData = $noAfterFindModel->find('all'); + + $this->assertFalse($afterFindModel == $noAfterFindModel); + $this->assertEquals($afterFindData, $noAfterFindData); + } + +/** + * testFindThreadedNoParent method + * + * @return void + */ + public function testFindThreadedNoParent() { + $this->loadFixtures('Apple', 'Sample'); + $Apple = new Apple(); + $result = $Apple->find('threaded'); + $result = Hash::extract($result, '{n}.children'); + $expected = array(array(), array(), array(), array(), array(), array(), array()); + $this->assertEquals($expected, $result); + } + +/** + * testFindThreaded method + * + * @return void + */ + public function testFindThreaded() { + $this->loadFixtures('Person'); + $Model = new Person(); + $Model->recursive = -1; + $result = $Model->find('threaded'); + $result = Hash::extract($result, '{n}.children'); + $expected = array(array(), array(), array(), array(), array(), array(), array()); + $this->assertEquals($expected, $result); + + $result = $Model->find('threaded', array('parent' => 'mother_id')); + $expected = array( + array( + 'Person' => array( + 'id' => '4', + 'name' => 'mother - grand mother', + 'mother_id' => '0', + 'father_id' => '0' + ), + 'children' => array( + array( + 'Person' => array( + 'id' => '2', + 'name' => 'mother', + 'mother_id' => '4', + 'father_id' => '5' + ), + 'children' => array( + array( + 'Person' => array( + 'id' => '1', + 'name' => 'person', + 'mother_id' => '2', + 'father_id' => '3' + ), + 'children' => array() + ) + ) + ) + ) + ), + array( + 'Person' => array( + 'id' => '5', + 'name' => 'mother - grand father', + 'mother_id' => '0', + 'father_id' => '0' + ), + 'children' => array() + ), + array( + 'Person' => array( + 'id' => '6', + 'name' => 'father - grand mother', + 'mother_id' => '0', + 'father_id' => '0' + ), + 'children' => array( + array( + 'Person' => array( + 'id' => '3', + 'name' => 'father', + 'mother_id' => '6', + 'father_id' => '7' + ), + 'children' => array() + ) + ) + ), + array( + 'Person' => array( + 'id' => '7', + 'name' => 'father - grand father', + 'mother_id' => '0', + 'father_id' => '0' + ), + 'children' => array() + ) + ); + $this->assertEquals($expected, $result); + } + +/** + * testFindAllThreaded method + * + * @return void + */ + public function testFindAllThreaded() { + $this->loadFixtures('Category'); + $TestModel = new Category(); + + $result = $TestModel->find('threaded'); + $expected = array( + array( + 'Category' => array( + 'id' => '1', + 'parent_id' => '0', + 'name' => 'Category 1', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31' + ), + 'children' => array( + array( + 'Category' => array( + 'id' => '2', + 'parent_id' => '1', + 'name' => 'Category 1.1', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31' + ), + 'children' => array( + array('Category' => array( + 'id' => '7', + 'parent_id' => '2', + 'name' => 'Category 1.1.1', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31'), + 'children' => array()), + array('Category' => array( + 'id' => '8', + 'parent_id' => '2', + 'name' => 'Category 1.1.2', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31'), + 'children' => array())) + ), + array( + 'Category' => array( + 'id' => '3', + 'parent_id' => '1', + 'name' => 'Category 1.2', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31' + ), + 'children' => array() + ) + ) + ), + array( + 'Category' => array( + 'id' => '4', + 'parent_id' => '0', + 'name' => 'Category 2', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31' + ), + 'children' => array() + ), + array( + 'Category' => array( + 'id' => '5', + 'parent_id' => '0', + 'name' => 'Category 3', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31' + ), + 'children' => array( + array( + 'Category' => array( + 'id' => '6', + 'parent_id' => '5', + 'name' => 'Category 3.1', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31' + ), + 'children' => array() + ) + ) + ) + ); + $this->assertEquals($expected, $result); + + $result = $TestModel->find('threaded', array( + 'conditions' => array('Category.name LIKE' => 'Category 1%') + )); + + $expected = array( + array( + 'Category' => array( + 'id' => '1', + 'parent_id' => '0', + 'name' => 'Category 1', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31' + ), + 'children' => array( + array( + 'Category' => array( + 'id' => '2', + 'parent_id' => '1', + 'name' => 'Category 1.1', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31' + ), + 'children' => array( + array('Category' => array( + 'id' => '7', + 'parent_id' => '2', + 'name' => 'Category 1.1.1', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31'), + 'children' => array()), + array('Category' => array( + 'id' => '8', + 'parent_id' => '2', + 'name' => 'Category 1.1.2', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31'), + 'children' => array())) + ), + array( + 'Category' => array( + 'id' => '3', + 'parent_id' => '1', + 'name' => 'Category 1.2', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31' + ), + 'children' => array() + ) + ) + ) + ); + $this->assertEquals($expected, $result); + + $result = $TestModel->find('threaded', array( + 'fields' => 'id, parent_id, name' + )); + + $expected = array( + array( + 'Category' => array( + 'id' => '1', + 'parent_id' => '0', + 'name' => 'Category 1' + ), + 'children' => array( + array( + 'Category' => array( + 'id' => '2', + 'parent_id' => '1', + 'name' => 'Category 1.1' + ), + 'children' => array( + array('Category' => array( + 'id' => '7', + 'parent_id' => '2', + 'name' => 'Category 1.1.1'), + 'children' => array()), + array('Category' => array( + 'id' => '8', + 'parent_id' => '2', + 'name' => 'Category 1.1.2'), + 'children' => array())) + ), + array( + 'Category' => array( + 'id' => '3', + 'parent_id' => '1', + 'name' => 'Category 1.2' + ), + 'children' => array() + ) + ) + ), + array( + 'Category' => array( + 'id' => '4', + 'parent_id' => '0', + 'name' => 'Category 2' + ), + 'children' => array() + ), + array( + 'Category' => array( + 'id' => '5', + 'parent_id' => '0', + 'name' => 'Category 3' + ), + 'children' => array( + array( + 'Category' => array( + 'id' => '6', + 'parent_id' => '5', + 'name' => 'Category 3.1' + ), + 'children' => array() + ) + ) + ) + ); + $this->assertEquals($expected, $result); + + $result = $TestModel->find('threaded', array('order' => 'id DESC')); + + $expected = array( + array( + 'Category' => array( + 'id' => 5, + 'parent_id' => 0, + 'name' => 'Category 3', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31' + ), + 'children' => array( + array( + 'Category' => array( + 'id' => 6, + 'parent_id' => 5, + 'name' => 'Category 3.1', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31' + ), + 'children' => array() + ) + ) + ), + array( + 'Category' => array( + 'id' => 4, + 'parent_id' => 0, + 'name' => 'Category 2', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31' + ), + 'children' => array() + ), + array( + 'Category' => array( + 'id' => 1, + 'parent_id' => 0, + 'name' => 'Category 1', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31' + ), + 'children' => array( + array( + 'Category' => array( + 'id' => 3, + 'parent_id' => 1, + 'name' => 'Category 1.2', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31' + ), + 'children' => array() + ), + array( + 'Category' => array( + 'id' => 2, + 'parent_id' => 1, + 'name' => 'Category 1.1', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31' + ), + 'children' => array( + array('Category' => array( + 'id' => '8', + 'parent_id' => '2', + 'name' => 'Category 1.1.2', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31'), + 'children' => array()), + array('Category' => array( + 'id' => '7', + 'parent_id' => '2', + 'name' => 'Category 1.1.1', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31'), + 'children' => array())) + ) + ) + ) + ); + $this->assertEquals($expected, $result); + + $result = $TestModel->find('threaded', array( + 'conditions' => array('Category.name LIKE' => 'Category 3%') + )); + $expected = array( + array( + 'Category' => array( + 'id' => '5', + 'parent_id' => '0', + 'name' => 'Category 3', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31' + ), + 'children' => array( + array( + 'Category' => array( + 'id' => '6', + 'parent_id' => '5', + 'name' => 'Category 3.1', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31' + ), + 'children' => array() + ) + ) + ) + ); + $this->assertEquals($expected, $result); + + $result = $TestModel->find('threaded', array( + 'conditions' => array('Category.name LIKE' => 'Category 1.1%') + )); + $expected = array( + array('Category' => + array( + 'id' => '2', + 'parent_id' => '1', + 'name' => 'Category 1.1', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31'), + 'children' => array( + array('Category' => array( + 'id' => '7', + 'parent_id' => '2', + 'name' => 'Category 1.1.1', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31'), + 'children' => array()), + array('Category' => array( + 'id' => '8', + 'parent_id' => '2', + 'name' => 'Category 1.1.2', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31'), + 'children' => array())))); + $this->assertEquals($expected, $result); + + $result = $TestModel->find('threaded', array( + 'fields' => 'id, parent_id, name', + 'conditions' => array('Category.id !=' => 2) + )); + $expected = array( + array( + 'Category' => array( + 'id' => '1', + 'parent_id' => '0', + 'name' => 'Category 1' + ), + 'children' => array( + array( + 'Category' => array( + 'id' => '3', + 'parent_id' => '1', + 'name' => 'Category 1.2' + ), + 'children' => array() + ) + ) + ), + array( + 'Category' => array( + 'id' => '4', + 'parent_id' => '0', + 'name' => 'Category 2' + ), + 'children' => array() + ), + array( + 'Category' => array( + 'id' => '5', + 'parent_id' => '0', + 'name' => 'Category 3' + ), + 'children' => array( + array( + 'Category' => array( + 'id' => '6', + 'parent_id' => '5', + 'name' => 'Category 3.1' + ), + 'children' => array() + ) + ) + ) + ); + $this->assertEquals($expected, $result); + + $result = $TestModel->find('all', array( + 'fields' => 'id, name, parent_id', + 'conditions' => array('Category.id !=' => 1) + )); + $expected = array( + array('Category' => array( + 'id' => '2', + 'name' => 'Category 1.1', + 'parent_id' => '1' + )), + array('Category' => array( + 'id' => '3', + 'name' => 'Category 1.2', + 'parent_id' => '1' + )), + array('Category' => array( + 'id' => '4', + 'name' => 'Category 2', + 'parent_id' => '0' + )), + array('Category' => array( + 'id' => '5', + 'name' => 'Category 3', + 'parent_id' => '0' + )), + array('Category' => array( + 'id' => '6', + 'name' => 'Category 3.1', + 'parent_id' => '5' + )), + array('Category' => array( + 'id' => '7', + 'name' => 'Category 1.1.1', + 'parent_id' => '2' + )), + array('Category' => array( + 'id' => '8', + 'name' => 'Category 1.1.2', + 'parent_id' => '2' + ))); + $this->assertEquals($expected, $result); + + $result = $TestModel->find('threaded', array( + 'fields' => 'id, parent_id, name', + 'conditions' => array('Category.id !=' => 1) + )); + $expected = array( + array( + 'Category' => array( + 'id' => '2', + 'parent_id' => '1', + 'name' => 'Category 1.1' + ), + 'children' => array( + array('Category' => array( + 'id' => '7', + 'parent_id' => '2', + 'name' => 'Category 1.1.1'), + 'children' => array()), + array('Category' => array( + 'id' => '8', + 'parent_id' => '2', + 'name' => 'Category 1.1.2'), + 'children' => array())) + ), + array( + 'Category' => array( + 'id' => '3', + 'parent_id' => '1', + 'name' => 'Category 1.2' + ), + 'children' => array() + ) + ); + $this->assertEquals($expected, $result); + } + +/** + * test find('neighbors') + * + * @return void + */ + public function testFindNeighbors() { + $this->loadFixtures('User', 'Article', 'Comment', 'Tag', 'ArticlesTag', 'Attachment'); + $TestModel = new Article(); + + $TestModel->id = 1; + $result = $TestModel->find('neighbors', array('fields' => array('id'))); + + $this->assertNull($result['prev']); + $this->assertEquals(array('id' => 2), $result['next']['Article']); + $this->assertEquals(2, count($result['next']['Comment'])); + $this->assertEquals(2, count($result['next']['Tag'])); + + $TestModel->id = 2; + $TestModel->recursive = 0; + $result = $TestModel->find('neighbors', array( + 'fields' => array('id') + )); + + $expected = array( + 'prev' => array( + 'Article' => array( + 'id' => 1 + )), + 'next' => array( + 'Article' => array( + 'id' => 3 + ))); + $this->assertEquals($expected, $result); + + $TestModel->id = 3; + $TestModel->recursive = 1; + $result = $TestModel->find('neighbors', array('fields' => array('id'))); + + $this->assertNull($result['next']); + $this->assertEquals(array('id' => 2), $result['prev']['Article']); + $this->assertEquals(2, count($result['prev']['Comment'])); + $this->assertEquals(2, count($result['prev']['Tag'])); + + $TestModel->id = 1; + $result = $TestModel->find('neighbors', array('recursive' => -1)); + $expected = array( + 'prev' => null, + 'next' => array( + 'Article' => array( + 'id' => 2, + 'user_id' => 3, + 'title' => 'Second Article', + 'body' => 'Second Article Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:41:23', + 'updated' => '2007-03-18 10:43:31' + ) + ) + ); + $this->assertEquals($expected, $result); + + $TestModel->id = 2; + $result = $TestModel->find('neighbors', array('recursive' => -1)); + $expected = array( + 'prev' => array( + 'Article' => array( + 'id' => 1, + 'user_id' => 1, + 'title' => 'First Article', + 'body' => 'First Article Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:39:23', + 'updated' => '2007-03-18 10:41:31' + ) + ), + 'next' => array( + 'Article' => array( + 'id' => 3, + 'user_id' => 1, + 'title' => 'Third Article', + 'body' => 'Third Article Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:43:23', + 'updated' => '2007-03-18 10:45:31' + ) + ) + ); + $this->assertEquals($expected, $result); + + $TestModel->id = 3; + $result = $TestModel->find('neighbors', array('recursive' => -1)); + $expected = array( + 'prev' => array( + 'Article' => array( + 'id' => 2, + 'user_id' => 3, + 'title' => 'Second Article', + 'body' => 'Second Article Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:41:23', + 'updated' => '2007-03-18 10:43:31' + ) + ), + 'next' => null + ); + $this->assertEquals($expected, $result); + + $TestModel->recursive = 0; + $TestModel->id = 1; + $one = $TestModel->read(); + $TestModel->id = 2; + $two = $TestModel->read(); + $TestModel->id = 3; + $three = $TestModel->read(); + + $TestModel->id = 1; + $result = $TestModel->find('neighbors'); + $expected = array('prev' => null, 'next' => $two); + $this->assertEquals($expected, $result); + + $TestModel->id = 2; + $result = $TestModel->find('neighbors'); + $expected = array('prev' => $one, 'next' => $three); + $this->assertEquals($expected, $result); + + $TestModel->id = 3; + $result = $TestModel->find('neighbors'); + $expected = array('prev' => $two, 'next' => null); + $this->assertEquals($expected, $result); + + $TestModel->recursive = 2; + $TestModel->id = 1; + $one = $TestModel->read(); + $TestModel->id = 2; + $two = $TestModel->read(); + $TestModel->id = 3; + $three = $TestModel->read(); + + $TestModel->id = 1; + $result = $TestModel->find('neighbors', array('recursive' => 2)); + $expected = array('prev' => null, 'next' => $two); + $this->assertEquals($expected, $result); + + $TestModel->id = 2; + $result = $TestModel->find('neighbors', array('recursive' => 2)); + $expected = array('prev' => $one, 'next' => $three); + $this->assertEquals($expected, $result); + + $TestModel->id = 3; + $result = $TestModel->find('neighbors', array('recursive' => 2)); + $expected = array('prev' => $two, 'next' => null); + $this->assertEquals($expected, $result); + } + +/** + * testFindCombinedRelations method + * + * @return void + */ + public function testFindCombinedRelations() { + $this->skipIf($this->db instanceof Sqlserver, 'The test of testRecursiveUnbind test is not compatible with SQL Server, because it check for time columns.'); + + $this->loadFixtures('Apple', 'Sample'); + $TestModel = new Apple(); + + $result = $TestModel->find('all'); + + $expected = array( + array( + 'Apple' => array( + 'id' => '1', + 'apple_id' => '2', + 'color' => 'Red 1', + 'name' => 'Red Apple 1', + 'created' => '2006-11-22 10:38:58', + 'date' => '1951-01-04', + 'modified' => '2006-12-01 13:31:26', + 'mytime' => '22:57:17' + ), + 'Parent' => array( + 'id' => '2', + 'apple_id' => '1', + 'color' => 'Bright Red 1', + 'name' => 'Bright Red Apple', + 'created' => '2006-11-22 10:43:13', + 'date' => '2014-01-01', + 'modified' => '2006-11-30 18:38:10', + 'mytime' => '22:57:17' + ), + 'Sample' => array( + 'id' => null, + 'apple_id' => null, + 'name' => null + ), + 'Child' => array( + array( + 'id' => '2', + 'apple_id' => '1', + 'color' => 'Bright Red 1', + 'name' => 'Bright Red Apple', + 'created' => '2006-11-22 10:43:13', + 'date' => '2014-01-01', + 'modified' => '2006-11-30 18:38:10', + 'mytime' => '22:57:17' + ))), + array( + 'Apple' => array( + 'id' => '2', + 'apple_id' => '1', + 'color' => 'Bright Red 1', + 'name' => 'Bright Red Apple', + 'created' => '2006-11-22 10:43:13', + 'date' => '2014-01-01', + 'modified' => '2006-11-30 18:38:10', + 'mytime' => '22:57:17' + ), + 'Parent' => array( + 'id' => '1', + 'apple_id' => '2', + 'color' => 'Red 1', + 'name' => 'Red Apple 1', + 'created' => '2006-11-22 10:38:58', + 'date' => '1951-01-04', + 'modified' => '2006-12-01 13:31:26', + 'mytime' => '22:57:17' + ), + 'Sample' => array( + 'id' => '2', + 'apple_id' => '2', + 'name' => 'sample2' + ), + 'Child' => array( + array( + 'id' => '1', + 'apple_id' => '2', + 'color' => 'Red 1', + 'name' => 'Red Apple 1', + 'created' => '2006-11-22 10:38:58', + 'date' => '1951-01-04', + 'modified' => '2006-12-01 13:31:26', + 'mytime' => '22:57:17' + ), + array( + 'id' => '3', + 'apple_id' => '2', + 'color' => 'blue green', + 'name' => 'green blue', + 'created' => '2006-12-25 05:13:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:24', + 'mytime' => '22:57:17' + ), + array( + 'id' => '4', + 'apple_id' => '2', + 'color' => 'Blue Green', + 'name' => 'Test Name', + 'created' => '2006-12-25 05:23:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:36', + 'mytime' => '22:57:17' + ))), + array( + 'Apple' => array( + 'id' => '3', + 'apple_id' => '2', + 'color' => 'blue green', + 'name' => 'green blue', + 'created' => '2006-12-25 05:13:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:24', + 'mytime' => '22:57:17' + ), + 'Parent' => array( + 'id' => '2', + 'apple_id' => '1', + 'color' => 'Bright Red 1', + 'name' => 'Bright Red Apple', + 'created' => '2006-11-22 10:43:13', + 'date' => '2014-01-01', + 'modified' => '2006-11-30 18:38:10', + 'mytime' => '22:57:17' + ), + 'Sample' => array( + 'id' => '1', + 'apple_id' => '3', + 'name' => 'sample1' + ), + 'Child' => array() + ), + array( + 'Apple' => array( + 'id' => '4', + 'apple_id' => '2', + 'color' => 'Blue Green', + 'name' => 'Test Name', + 'created' => '2006-12-25 05:23:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:36', + 'mytime' => '22:57:17' + ), + 'Parent' => array( + 'id' => '2', + 'apple_id' => '1', + 'color' => 'Bright Red 1', + 'name' => 'Bright Red Apple', + 'created' => '2006-11-22 10:43:13', + 'date' => '2014-01-01', + 'modified' => '2006-11-30 18:38:10', + 'mytime' => '22:57:17' + ), + 'Sample' => array( + 'id' => '3', + 'apple_id' => '4', + 'name' => 'sample3' + ), + 'Child' => array( + array( + 'id' => '6', + 'apple_id' => '4', + 'color' => 'My new appleOrange', + 'name' => 'My new apple', + 'created' => '2006-12-25 05:29:39', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:29:39', + 'mytime' => '22:57:17' + ))), + array( + 'Apple' => array( + 'id' => '5', + 'apple_id' => '5', + 'color' => 'Green', + 'name' => 'Blue Green', + 'created' => '2006-12-25 05:24:06', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:29:16', + 'mytime' => '22:57:17' + ), + 'Parent' => array( + 'id' => '5', + 'apple_id' => '5', + 'color' => 'Green', + 'name' => 'Blue Green', + 'created' => '2006-12-25 05:24:06', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:29:16', + 'mytime' => '22:57:17' + ), + 'Sample' => array( + 'id' => '4', + 'apple_id' => '5', + 'name' => 'sample4' + ), + 'Child' => array( + array( + 'id' => '5', + 'apple_id' => '5', + 'color' => 'Green', + 'name' => 'Blue Green', + 'created' => '2006-12-25 05:24:06', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:29:16', + 'mytime' => '22:57:17' + ))), + array( + 'Apple' => array( + 'id' => '6', + 'apple_id' => '4', + 'color' => 'My new appleOrange', + 'name' => 'My new apple', + 'created' => '2006-12-25 05:29:39', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:29:39', + 'mytime' => '22:57:17' + ), + 'Parent' => array( + 'id' => '4', + 'apple_id' => '2', + 'color' => 'Blue Green', + 'name' => 'Test Name', + 'created' => '2006-12-25 05:23:36', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:23:36', + 'mytime' => '22:57:17' + ), + 'Sample' => array( + 'id' => null, + 'apple_id' => null, + 'name' => null + ), + 'Child' => array( + array( + 'id' => '7', + 'apple_id' => '6', + 'color' => 'Some wierd color', + 'name' => 'Some odd color', + 'created' => '2006-12-25 05:34:21', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:34:21', + 'mytime' => '22:57:17' + ))), + array( + 'Apple' => array( + 'id' => '7', + 'apple_id' => '6', + 'color' => 'Some wierd color', + 'name' => 'Some odd color', + 'created' => '2006-12-25 05:34:21', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:34:21', + 'mytime' => '22:57:17' + ), + 'Parent' => array( + 'id' => '6', + 'apple_id' => '4', + 'color' => 'My new appleOrange', + 'name' => 'My new apple', + 'created' => '2006-12-25 05:29:39', + 'date' => '2006-12-25', + 'modified' => '2006-12-25 05:29:39', + 'mytime' => '22:57:17' + ), + 'Sample' => array( + 'id' => null, + 'apple_id' => null, + 'name' => null + ), + 'Child' => array() + )); + $this->assertEquals($expected, $result); + } + +/** + * testSaveEmpty method + * + * @return void + */ + public function testSaveEmpty() { + $this->loadFixtures('Thread'); + $TestModel = new Thread(); + $data = array(); + $expected = $TestModel->save($data); + $this->assertFalse($expected); + } + +/** + * testFindAllWithConditionInChildQuery + * + * @todo external conditions like this are going to need to be revisited at some point + * @return void + */ + public function testFindAllWithConditionInChildQuery() { + $this->loadFixtures('Basket', 'FilmFile'); + + $TestModel = new Basket(); + $recursive = 3; + $result = $TestModel->find('all', compact('recursive')); + + $expected = array( + array( + 'Basket' => array( + 'id' => 1, + 'type' => 'nonfile', + 'name' => 'basket1', + 'object_id' => 1, + 'user_id' => 1, + ), + 'FilmFile' => array( + 'id' => '', + 'name' => '', + ) + ), + array( + 'Basket' => array( + 'id' => 2, + 'type' => 'file', + 'name' => 'basket2', + 'object_id' => 2, + 'user_id' => 1, + ), + 'FilmFile' => array( + 'id' => 2, + 'name' => 'two', + ) + ), + ); + $this->assertEquals($expected, $result); + } + +/** + * testFindAllWithConditionsHavingMixedDataTypes method + * + * @return void + */ + public function testFindAllWithConditionsHavingMixedDataTypes() { + $this->loadFixtures('Article', 'User', 'Tag', 'ArticlesTag'); + $TestModel = new Article(); + $expected = array( + array( + 'Article' => array( + 'id' => 1, + 'user_id' => 1, + 'title' => 'First Article', + 'body' => 'First Article Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:39:23', + 'updated' => '2007-03-18 10:41:31' + ) + ), + array( + 'Article' => array( + 'id' => 2, + 'user_id' => 3, + 'title' => 'Second Article', + 'body' => 'Second Article Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:41:23', + 'updated' => '2007-03-18 10:43:31' + ) + ) + ); + $conditions = array('id' => array('1', 2)); + $recursive = -1; + $order = 'Article.id ASC'; + $result = $TestModel->find('all', compact('conditions', 'recursive', 'order')); + $this->assertEquals($expected, $result); + + $this->skipIf($this->db instanceof Postgres, 'The rest of testFindAllWithConditionsHavingMixedDataTypes test is not compatible with Postgres.'); + + $conditions = array('id' => array('1', 2, '3.0')); + $order = 'Article.id ASC'; + $result = $TestModel->find('all', compact('recursive', 'conditions', 'order')); + $expected = array( + array( + 'Article' => array( + 'id' => 1, + 'user_id' => 1, + 'title' => 'First Article', + 'body' => 'First Article Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:39:23', + 'updated' => '2007-03-18 10:41:31' + ) + ), + array( + 'Article' => array( + 'id' => 2, + 'user_id' => 3, + 'title' => 'Second Article', + 'body' => 'Second Article Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:41:23', + 'updated' => '2007-03-18 10:43:31' + ) + ), + array( + 'Article' => array( + 'id' => 3, + 'user_id' => 1, + 'title' => 'Third Article', + 'body' => 'Third Article Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:43:23', + 'updated' => '2007-03-18 10:45:31' + ) + ) + ); + $this->assertEquals($expected, $result); + } + +/** + * testBindUnbind method + * + * @return void + */ + public function testBindUnbind() { + $this->loadFixtures( + 'User', + 'Comment', + 'FeatureSet', + 'DeviceType', + 'DeviceTypeCategory', + 'ExteriorTypeCategory', + 'Device', + 'Document', + 'DocumentDirectory' + ); + $TestModel = new User(); + + $result = $TestModel->hasMany; + $expected = array(); + $this->assertEquals($expected, $result); + + $result = $TestModel->bindModel(array('hasMany' => array('Comment'))); + $this->assertTrue($result); + + $result = $TestModel->find('all', array( + 'fields' => 'User.id, User.user' + )); + $expected = array( + array( + 'User' => array( + 'id' => '1', + 'user' => 'mariano' + ), + 'Comment' => array( + array( + 'id' => '3', + 'article_id' => '1', + 'user_id' => '1', + 'comment' => 'Third Comment for First Article', + 'published' => 'Y', + 'created' => '2007-03-18 10:49:23', + 'updated' => '2007-03-18 10:51:31' + ), + array( + 'id' => '4', + 'article_id' => '1', + 'user_id' => '1', + 'comment' => 'Fourth Comment for First Article', + 'published' => 'N', + 'created' => '2007-03-18 10:51:23', + 'updated' => '2007-03-18 10:53:31' + ), + array( + 'id' => '5', + 'article_id' => '2', + 'user_id' => '1', + 'comment' => 'First Comment for Second Article', + 'published' => 'Y', + 'created' => '2007-03-18 10:53:23', + 'updated' => '2007-03-18 10:55:31' + ))), + array( + 'User' => array( + 'id' => '2', + 'user' => 'nate' + ), + 'Comment' => array( + array( + 'id' => '1', + 'article_id' => '1', + 'user_id' => '2', + 'comment' => 'First Comment for First Article', + 'published' => 'Y', + 'created' => '2007-03-18 10:45:23', + 'updated' => '2007-03-18 10:47:31' + ), + array( + 'id' => '6', + 'article_id' => '2', + 'user_id' => '2', + 'comment' => 'Second Comment for Second Article', + 'published' => 'Y', + 'created' => '2007-03-18 10:55:23', + 'updated' => '2007-03-18 10:57:31' + ))), + array( + 'User' => array( + 'id' => '3', + 'user' => 'larry' + ), + 'Comment' => array() + ), + array( + 'User' => array( + 'id' => '4', + 'user' => 'garrett' + ), + 'Comment' => array( + array( + 'id' => '2', + 'article_id' => '1', + 'user_id' => '4', + 'comment' => 'Second Comment for First Article', + 'published' => 'Y', + 'created' => '2007-03-18 10:47:23', + 'updated' => '2007-03-18 10:49:31' + )))); + + $this->assertEquals($expected, $result); + + $TestModel->resetAssociations(); + $result = $TestModel->hasMany; + $this->assertEquals(array(), $result); + + $result = $TestModel->bindModel(array('hasMany' => array('Comment')), false); + $this->assertTrue($result); + + $result = $TestModel->find('all', array( + 'fields' => 'User.id, User.user' + )); + + $expected = array( + array( + 'User' => array( + 'id' => '1', + 'user' => 'mariano' + ), + 'Comment' => array( + array( + 'id' => '3', + 'article_id' => '1', + 'user_id' => '1', + 'comment' => 'Third Comment for First Article', + 'published' => 'Y', + 'created' => '2007-03-18 10:49:23', + 'updated' => '2007-03-18 10:51:31' + ), + array( + 'id' => '4', + 'article_id' => '1', + 'user_id' => '1', + 'comment' => 'Fourth Comment for First Article', + 'published' => 'N', + 'created' => '2007-03-18 10:51:23', + 'updated' => '2007-03-18 10:53:31' + ), + array( + 'id' => '5', + 'article_id' => '2', + 'user_id' => '1', + 'comment' => 'First Comment for Second Article', + 'published' => 'Y', + 'created' => '2007-03-18 10:53:23', + 'updated' => '2007-03-18 10:55:31' + ))), + array( + 'User' => array( + 'id' => '2', + 'user' => 'nate' + ), + 'Comment' => array( + array( + 'id' => '1', + 'article_id' => '1', + 'user_id' => '2', + 'comment' => 'First Comment for First Article', + 'published' => 'Y', + 'created' => '2007-03-18 10:45:23', + 'updated' => '2007-03-18 10:47:31' + ), + array( + 'id' => '6', + 'article_id' => '2', + 'user_id' => '2', + 'comment' => 'Second Comment for Second Article', + 'published' => 'Y', + 'created' => '2007-03-18 10:55:23', + 'updated' => '2007-03-18 10:57:31' + ))), + array( + 'User' => array( + 'id' => '3', + 'user' => 'larry' + ), + 'Comment' => array() + ), + array( + 'User' => array( + 'id' => '4', + 'user' => 'garrett' + ), + 'Comment' => array( + array( + 'id' => '2', + 'article_id' => '1', + 'user_id' => '4', + 'comment' => 'Second Comment for First Article', + 'published' => 'Y', + 'created' => '2007-03-18 10:47:23', + 'updated' => '2007-03-18 10:49:31' + )))); + + $this->assertEquals($expected, $result); + + $result = $TestModel->hasMany; + $expected = array( + 'Comment' => array( + 'className' => 'Comment', + 'foreignKey' => 'user_id', + 'conditions' => null, + 'fields' => null, + 'order' => null, + 'limit' => null, + 'offset' => null, + 'dependent' => null, + 'exclusive' => null, + 'finderQuery' => null, + 'counterQuery' => null + )); + $this->assertEquals($expected, $result); + + $result = $TestModel->unbindModel(array('hasMany' => array('Comment'))); + $this->assertTrue($result); + + $result = $TestModel->hasMany; + $expected = array(); + $this->assertEquals($expected, $result); + + $result = $TestModel->find('all', array( + 'fields' => 'User.id, User.user' + )); + $expected = array( + array('User' => array('id' => '1', 'user' => 'mariano')), + array('User' => array('id' => '2', 'user' => 'nate')), + array('User' => array('id' => '3', 'user' => 'larry')), + array('User' => array('id' => '4', 'user' => 'garrett'))); + $this->assertEquals($expected, $result); + + $result = $TestModel->find('all', array( + 'fields' => 'User.id, User.user' + )); + $expected = array( + array( + 'User' => array( + 'id' => '1', + 'user' => 'mariano' + ), + 'Comment' => array( + array( + 'id' => '3', + 'article_id' => '1', + 'user_id' => '1', + 'comment' => 'Third Comment for First Article', + 'published' => 'Y', + 'created' => '2007-03-18 10:49:23', + 'updated' => '2007-03-18 10:51:31' + ), + array( + 'id' => '4', + 'article_id' => '1', + 'user_id' => '1', + 'comment' => 'Fourth Comment for First Article', + 'published' => 'N', + 'created' => '2007-03-18 10:51:23', + 'updated' => '2007-03-18 10:53:31' + ), + array( + 'id' => '5', + 'article_id' => '2', + 'user_id' => '1', + 'comment' => 'First Comment for Second Article', + 'published' => 'Y', + 'created' => '2007-03-18 10:53:23', + 'updated' => '2007-03-18 10:55:31' + ))), + array( + 'User' => array( + 'id' => '2', + 'user' => 'nate' + ), + 'Comment' => array( + array( + 'id' => '1', + 'article_id' => '1', + 'user_id' => '2', + 'comment' => 'First Comment for First Article', + 'published' => 'Y', + 'created' => '2007-03-18 10:45:23', + 'updated' => '2007-03-18 10:47:31' + ), + array( + 'id' => '6', + 'article_id' => '2', + 'user_id' => '2', + 'comment' => 'Second Comment for Second Article', + 'published' => 'Y', + 'created' => '2007-03-18 10:55:23', + 'updated' => '2007-03-18 10:57:31' + ))), + array( + 'User' => array( + 'id' => '3', + 'user' => 'larry' + ), + 'Comment' => array() + ), + array( + 'User' => array( + 'id' => '4', + 'user' => 'garrett' + ), + 'Comment' => array( + array( + 'id' => '2', + 'article_id' => '1', + 'user_id' => '4', + 'comment' => + 'Second Comment for First Article', + 'published' => 'Y', + 'created' => '2007-03-18 10:47:23', + 'updated' => '2007-03-18 10:49:31' + )))); + $this->assertEquals($expected, $result); + + $result = $TestModel->unbindModel(array('hasMany' => array('Comment')), false); + $this->assertTrue($result); + + $result = $TestModel->find('all', array('fields' => 'User.id, User.user')); + $expected = array( + array('User' => array('id' => '1', 'user' => 'mariano')), + array('User' => array('id' => '2', 'user' => 'nate')), + array('User' => array('id' => '3', 'user' => 'larry')), + array('User' => array('id' => '4', 'user' => 'garrett'))); + $this->assertEquals($expected, $result); + + $result = $TestModel->hasMany; + $expected = array(); + $this->assertEquals($expected, $result); + + $result = $TestModel->bindModel(array('hasMany' => array( + 'Comment' => array('className' => 'Comment', 'conditions' => 'Comment.published = \'Y\'') + ))); + $this->assertTrue($result); + + $result = $TestModel->find('all', array('fields' => 'User.id, User.user')); + $expected = array( + array( + 'User' => array( + 'id' => '1', + 'user' => 'mariano' + ), + 'Comment' => array( + array( + 'id' => '3', + 'article_id' => '1', + 'user_id' => '1', + 'comment' => 'Third Comment for First Article', + 'published' => 'Y', + 'created' => '2007-03-18 10:49:23', + 'updated' => '2007-03-18 10:51:31' + ), + array( + 'id' => '5', + 'article_id' => '2', + 'user_id' => '1', + 'comment' => 'First Comment for Second Article', + 'published' => 'Y', + 'created' => '2007-03-18 10:53:23', + 'updated' => '2007-03-18 10:55:31' + ))), + array( + 'User' => array( + 'id' => '2', + 'user' => 'nate' + ), + 'Comment' => array( + array( + 'id' => '1', + 'article_id' => '1', + 'user_id' => '2', + 'comment' => 'First Comment for First Article', + 'published' => 'Y', + 'created' => '2007-03-18 10:45:23', + 'updated' => '2007-03-18 10:47:31' + ), + array( + 'id' => '6', + 'article_id' => '2', + 'user_id' => '2', + 'comment' => 'Second Comment for Second Article', + 'published' => 'Y', + 'created' => '2007-03-18 10:55:23', + 'updated' => '2007-03-18 10:57:31' + ))), + array( + 'User' => array( + 'id' => '3', + 'user' => 'larry' + ), + 'Comment' => array() + ), + array( + 'User' => array( + 'id' => '4', + 'user' => 'garrett' + ), + 'Comment' => array( + array( + 'id' => '2', + 'article_id' => '1', + 'user_id' => '4', + 'comment' => 'Second Comment for First Article', + 'published' => 'Y', + 'created' => '2007-03-18 10:47:23', + 'updated' => '2007-03-18 10:49:31' + )))); + + $this->assertEquals($expected, $result); + + $TestModel2 = new DeviceType(); + + $expected = array( + 'className' => 'FeatureSet', + 'foreignKey' => 'feature_set_id', + 'conditions' => '', + 'fields' => '', + 'order' => '', + 'counterCache' => '' + ); + $this->assertEquals($expected, $TestModel2->belongsTo['FeatureSet']); + + $TestModel2->bindModel(array( + 'belongsTo' => array( + 'FeatureSet' => array( + 'className' => 'FeatureSet', + 'conditions' => array('active' => true) + ) + ) + )); + $expected['conditions'] = array('active' => true); + $this->assertEquals($expected, $TestModel2->belongsTo['FeatureSet']); + + $TestModel2->bindModel(array( + 'belongsTo' => array( + 'FeatureSet' => array( + 'className' => 'FeatureSet', + 'foreignKey' => false, + 'conditions' => array('Feature.name' => 'DeviceType.name') + ) + ) + )); + $expected['conditions'] = array('Feature.name' => 'DeviceType.name'); + $expected['foreignKey'] = false; + $this->assertEquals($expected, $TestModel2->belongsTo['FeatureSet']); + + $TestModel2->bindModel(array( + 'hasMany' => array( + 'NewFeatureSet' => array( + 'className' => 'FeatureSet', + 'conditions' => array('active' => true) + ) + ) + )); + + $expected = array( + 'className' => 'FeatureSet', + 'conditions' => array('active' => true), + 'foreignKey' => 'device_type_id', + 'fields' => '', + 'order' => '', + 'limit' => '', + 'offset' => '', + 'dependent' => '', + 'exclusive' => '', + 'finderQuery' => '', + 'counterQuery' => '' + ); + $this->assertEquals($expected, $TestModel2->hasMany['NewFeatureSet']); + $this->assertTrue(is_object($TestModel2->NewFeatureSet)); + } + +/** + * testBindMultipleTimes method + * + * @return void + */ + public function testBindMultipleTimes() { + $this->loadFixtures('User', 'Comment', 'Article', 'Tag', 'ArticlesTag'); + $TestModel = new User(); + + $result = $TestModel->hasMany; + $expected = array(); + $this->assertEquals($expected, $result); + + $result = $TestModel->bindModel(array( + 'hasMany' => array( + 'Items' => array('className' => 'Comment') + ))); + $this->assertTrue($result); + + $result = $TestModel->find('all', array( + 'fields' => 'User.id, User.user' + )); + + $expected = array( + array( + 'User' => array( + 'id' => '1', + 'user' => 'mariano' + ), + 'Items' => array( + array( + 'id' => '3', + 'article_id' => '1', + 'user_id' => '1', + 'comment' => 'Third Comment for First Article', + 'published' => 'Y', + 'created' => '2007-03-18 10:49:23', + 'updated' => '2007-03-18 10:51:31' + ), + array( + 'id' => '4', + 'article_id' => '1', + 'user_id' => '1', + 'comment' => 'Fourth Comment for First Article', + 'published' => 'N', + 'created' => '2007-03-18 10:51:23', + 'updated' => '2007-03-18 10:53:31' + ), + array( + 'id' => '5', + 'article_id' => '2', + 'user_id' => '1', + 'comment' => 'First Comment for Second Article', + 'published' => 'Y', + 'created' => '2007-03-18 10:53:23', + 'updated' => '2007-03-18 10:55:31' + ))), + array( + 'User' => array( + 'id' => '2', + 'user' => 'nate' + ), + 'Items' => array( + array( + 'id' => '1', + 'article_id' => '1', + 'user_id' => '2', + 'comment' => 'First Comment for First Article', + 'published' => 'Y', + 'created' => '2007-03-18 10:45:23', + 'updated' => '2007-03-18 10:47:31' + ), + array( + 'id' => '6', + 'article_id' => '2', + 'user_id' => '2', + 'comment' => 'Second Comment for Second Article', + 'published' => 'Y', + 'created' => '2007-03-18 10:55:23', + 'updated' => '2007-03-18 10:57:31' + ))), + array( + 'User' => array( + 'id' => '3', + 'user' => 'larry' + ), + 'Items' => array() + ), + array( + 'User' => array( + 'id' => '4', + 'user' => 'garrett' + ), + 'Items' => array( + array( + 'id' => '2', + 'article_id' => '1', + 'user_id' => '4', + 'comment' => 'Second Comment for First Article', + 'published' => 'Y', + 'created' => '2007-03-18 10:47:23', + 'updated' => '2007-03-18 10:49:31' + )))); + $this->assertEquals($expected, $result); + + $result = $TestModel->bindModel(array( + 'hasMany' => array( + 'Items' => array('className' => 'Article') + ))); + $this->assertTrue($result); + + $result = $TestModel->find('all', array( + 'fields' => 'User.id, User.user' + )); + $expected = array( + array( + 'User' => array( + 'id' => '1', + 'user' => 'mariano' + ), + 'Items' => array( + array( + 'id' => 1, + 'user_id' => 1, + 'title' => 'First Article', + 'body' => 'First Article Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:39:23', + 'updated' => '2007-03-18 10:41:31' + ), + array( + 'id' => 3, + 'user_id' => 1, + 'title' => 'Third Article', + 'body' => 'Third Article Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:43:23', + 'updated' => '2007-03-18 10:45:31' + ))), + array( + 'User' => array( + 'id' => '2', + 'user' => 'nate' + ), + 'Items' => array() + ), + array( + 'User' => array( + 'id' => '3', + 'user' => 'larry' + ), + 'Items' => array( + array( + 'id' => 2, + 'user_id' => 3, + 'title' => 'Second Article', + 'body' => 'Second Article Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:41:23', + 'updated' => '2007-03-18 10:43:31' + ))), + array( + 'User' => array( + 'id' => '4', + 'user' => 'garrett' + ), + 'Items' => array() + )); + + $this->assertEquals($expected, $result); + } + +/** + * test that multiple reset = true calls to bindModel() result in the original associations. + * + * @return void + */ + public function testBindModelMultipleTimesResetCorrectly() { + $this->loadFixtures('User', 'Comment', 'Article'); + $TestModel = new User(); + + $TestModel->bindModel(array('hasMany' => array('Comment'))); + $TestModel->bindModel(array('hasMany' => array('Comment'))); + $TestModel->resetAssociations(); + + $this->assertFalse(isset($TestModel->hasMany['Comment']), 'Association left behind'); + } + +/** + * testBindMultipleTimes method with different reset settings + * + * @return void + */ + public function testBindMultipleTimesWithDifferentResetSettings() { + $this->loadFixtures('User', 'Comment', 'Article'); + $TestModel = new User(); + + $result = $TestModel->hasMany; + $expected = array(); + $this->assertEquals($expected, $result); + + $result = $TestModel->bindModel(array( + 'hasMany' => array('Comment') + )); + $this->assertTrue($result); + $result = $TestModel->bindModel( + array('hasMany' => array('Article')), + false + ); + $this->assertTrue($result); + + $result = array_keys($TestModel->hasMany); + $expected = array('Comment', 'Article'); + $this->assertEquals($expected, $result); + + $TestModel->resetAssociations(); + + $result = array_keys($TestModel->hasMany); + $expected = array('Article'); + $this->assertEquals($expected, $result); + } + +/** + * test that bindModel behaves with Custom primary Key associations + * + * @return void + */ + public function testBindWithCustomPrimaryKey() { + $this->loadFixtures('Story', 'StoriesTag', 'Tag'); + $Model = ClassRegistry::init('StoriesTag'); + $Model->bindModel(array( + 'belongsTo' => array( + 'Tag' => array( + 'className' => 'Tag', + 'foreignKey' => 'story' + )))); + + $result = $Model->find('all'); + $this->assertFalse(empty($result)); + } + +/** + * test that calling unbindModel() with reset == true multiple times + * leaves associations in the correct state. + * + * @return void + */ + public function testUnbindMultipleTimesResetCorrectly() { + $this->loadFixtures('User', 'Comment', 'Article'); + $TestModel = new Article10(); + + $TestModel->unbindModel(array('hasMany' => array('Comment'))); + $TestModel->unbindModel(array('hasMany' => array('Comment'))); + $TestModel->resetAssociations(); + + $this->assertTrue(isset($TestModel->hasMany['Comment']), 'Association permanently removed'); + } + +/** + * testBindMultipleTimes method with different reset settings + * + * @return void + */ + public function testUnBindMultipleTimesWithDifferentResetSettings() { + $this->loadFixtures('User', 'Comment', 'Article'); + $TestModel = new Comment(); + + $result = array_keys($TestModel->belongsTo); + $expected = array('Article', 'User'); + $this->assertEquals($expected, $result); + + $result = $TestModel->unbindModel(array( + 'belongsTo' => array('User') + )); + $this->assertTrue($result); + $result = $TestModel->unbindModel( + array('belongsTo' => array('Article')), + false + ); + $this->assertTrue($result); + + $result = array_keys($TestModel->belongsTo); + $expected = array(); + $this->assertEquals($expected, $result); + + $TestModel->resetAssociations(); + + $result = array_keys($TestModel->belongsTo); + $expected = array('User'); + $this->assertEquals($expected, $result); + } + +/** + * testAssociationAfterFind method + * + * @return void + */ + public function testAssociationAfterFind() { + $this->loadFixtures('Post', 'Author', 'Comment'); + $TestModel = new Post(); + $result = $TestModel->find('all'); + $expected = array( + array( + 'Post' => array( + 'id' => '1', + 'author_id' => '1', + 'title' => 'First Post', + 'body' => 'First Post Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:39:23', + 'updated' => '2007-03-18 10:41:31' + ), + 'Author' => array( + 'id' => '1', + 'user' => 'mariano', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', + 'updated' => '2007-03-17 01:18:31', + 'test' => 'working' + )), + array( + 'Post' => array( + 'id' => '2', + 'author_id' => '3', + 'title' => 'Second Post', + 'body' => 'Second Post Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:41:23', + 'updated' => '2007-03-18 10:43:31' + ), + 'Author' => array( + 'id' => '3', + 'user' => 'larry', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:20:23', + 'updated' => '2007-03-17 01:22:31', + 'test' => 'working' + )), + array( + 'Post' => array( + 'id' => '3', + 'author_id' => '1', + 'title' => 'Third Post', + 'body' => 'Third Post Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:43:23', + 'updated' => '2007-03-18 10:45:31' + ), + 'Author' => array( + 'id' => '1', + 'user' => 'mariano', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', + 'updated' => '2007-03-17 01:18:31', + 'test' => 'working' + ))); + $this->assertEquals($expected, $result); + unset($TestModel); + + $Author = new Author(); + $Author->Post->bindModel(array( + 'hasMany' => array( + 'Comment' => array( + 'className' => 'ModifiedComment', + 'foreignKey' => 'article_id', + ) + ))); + $result = $Author->find('all', array( + 'conditions' => array('Author.id' => 1), + 'recursive' => 2 + )); + $expected = array( + 'id' => 1, + 'article_id' => 1, + 'user_id' => 2, + 'comment' => 'First Comment for First Article', + 'published' => 'Y', + 'created' => '2007-03-18 10:45:23', + 'updated' => '2007-03-18 10:47:31', + 'callback' => 'Fire' + ); + $this->assertEquals($expected, $result[0]['Post'][0]['Comment'][0]); + } + +/** + * testDeeperAssociationAfterFind method + * + * @return void + */ + public function testDeeperAssociationAfterFind() { + $this->loadFixtures('Post', 'Author', 'Comment', 'Attachment', 'Article'); + + $Post = new Post(); + $Post->bindModel(array( + 'hasMany' => array( + 'Comment' => array( + 'className' => 'ModifiedComment', + 'foreignKey' => 'article_id', + ) + ))); + $Post->Comment->bindModel(array( + 'hasOne' => array( + 'Attachment' => array( + 'className' => 'ModifiedAttachment', + ) + ))); + + $result = $Post->find('first', array( + 'conditions' => array('Post.id' => 2), + 'recursive' => 2 + )); + $this->assertTrue(isset($result['Comment'][0]['callback'])); + $this->assertEquals('Fire', $result['Comment'][0]['callback']); + $this->assertTrue(isset($result['Comment'][0]['Attachment']['callback'])); + $this->assertEquals('Fired', $result['Comment'][0]['Attachment']['callback']); + } + +/** + * Tests that callbacks can be properly disabled + * + * @return void + */ + public function testCallbackDisabling() { + $this->loadFixtures('Author'); + $TestModel = new ModifiedAuthor(); + + $result = Hash::extract($TestModel->find('all'), '{n}.Author.user'); + $expected = array('mariano (CakePHP)', 'nate (CakePHP)', 'larry (CakePHP)', 'garrett (CakePHP)'); + $this->assertEquals($expected, $result); + + $result = Hash::extract($TestModel->find('all', array('callbacks' => 'after')), '{n}.Author.user'); + $expected = array('mariano (CakePHP)', 'nate (CakePHP)', 'larry (CakePHP)', 'garrett (CakePHP)'); + $this->assertEquals($expected, $result); + + $result = Hash::extract($TestModel->find('all', array('callbacks' => 'before')), '{n}.Author.user'); + $expected = array('mariano', 'nate', 'larry', 'garrett'); + $this->assertEquals($expected, $result); + + $result = Hash::extract($TestModel->find('all', array('callbacks' => false)), '{n}.Author.user'); + $expected = array('mariano', 'nate', 'larry', 'garrett'); + $this->assertEquals($expected, $result); + } + +/** + * testAssociationAfterFindCallbacksDisabled method + * + * @return void + */ + public function testAssociationAfterFindCalbacksDisabled() { + $this->loadFixtures('Post', 'Author', 'Comment'); + $TestModel = new Post(); + $result = $TestModel->find('all', array('callbacks' => false)); + $expected = array( + array( + 'Post' => array( + 'id' => '1', + 'author_id' => '1', + 'title' => 'First Post', + 'body' => 'First Post Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:39:23', + 'updated' => '2007-03-18 10:41:31' + ), + 'Author' => array( + 'id' => '1', + 'user' => 'mariano', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', + 'updated' => '2007-03-17 01:18:31' + )), + array( + 'Post' => array( + 'id' => '2', + 'author_id' => '3', + 'title' => 'Second Post', + 'body' => 'Second Post Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:41:23', + 'updated' => '2007-03-18 10:43:31' + ), + 'Author' => array( + 'id' => '3', + 'user' => 'larry', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:20:23', + 'updated' => '2007-03-17 01:22:31' + )), + array( + 'Post' => array( + 'id' => '3', + 'author_id' => '1', + 'title' => 'Third Post', + 'body' => 'Third Post Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:43:23', + 'updated' => '2007-03-18 10:45:31' + ), + 'Author' => array( + 'id' => '1', + 'user' => 'mariano', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', + 'updated' => '2007-03-17 01:18:31' + ))); + $this->assertEquals($expected, $result); + unset($TestModel); + + $Author = new Author(); + $Author->Post->bindModel(array( + 'hasMany' => array( + 'Comment' => array( + 'className' => 'ModifiedComment', + 'foreignKey' => 'article_id', + ) + ))); + $result = $Author->find('all', array( + 'conditions' => array('Author.id' => 1), + 'recursive' => 2, + 'callbacks' => false + )); + $expected = array( + 'id' => 1, + 'article_id' => 1, + 'user_id' => 2, + 'comment' => 'First Comment for First Article', + 'published' => 'Y', + 'created' => '2007-03-18 10:45:23', + 'updated' => '2007-03-18 10:47:31' + ); + $this->assertEquals($expected, $result[0]['Post'][0]['Comment'][0]); + } + +/** + * Tests that the database configuration assigned to the model can be changed using + * (before|after)Find callbacks + * + * @return void + */ + public function testCallbackSourceChange() { + $this->loadFixtures('Post'); + $TestModel = new Post(); + $this->assertEquals(3, count($TestModel->find('all'))); + } + +/** + * testCallbackSourceChangeUnknownDatasource method + * + * @expectedException MissingDatasourceConfigException + * @return void + */ + public function testCallbackSourceChangeUnknownDatasource() { + $this->loadFixtures('Post', 'Author'); + $TestModel = new Post(); + $this->assertFalse($TestModel->find('all', array('connection' => 'foo'))); + } + +/** + * testMultipleBelongsToWithSameClass method + * + * @return void + */ + public function testMultipleBelongsToWithSameClass() { + $this->loadFixtures( + 'DeviceType', + 'DeviceTypeCategory', + 'FeatureSet', + 'ExteriorTypeCategory', + 'Document', + 'Device', + 'DocumentDirectory' + ); + + $DeviceType = new DeviceType(); + + $DeviceType->recursive = 2; + $result = $DeviceType->read(null, 1); + + $expected = array( + 'DeviceType' => array( + 'id' => 1, + 'device_type_category_id' => 1, + 'feature_set_id' => 1, + 'exterior_type_category_id' => 1, + 'image_id' => 1, + 'extra1_id' => 1, + 'extra2_id' => 1, + 'name' => 'DeviceType 1', + 'order' => 0 + ), + 'Image' => array( + 'id' => 1, + 'document_directory_id' => 1, + 'name' => 'Document 1', + 'DocumentDirectory' => array( + 'id' => 1, + 'name' => 'DocumentDirectory 1' + )), + 'Extra1' => array( + 'id' => 1, + 'document_directory_id' => 1, + 'name' => 'Document 1', + 'DocumentDirectory' => array( + 'id' => 1, + 'name' => 'DocumentDirectory 1' + )), + 'Extra2' => array( + 'id' => 1, + 'document_directory_id' => 1, + 'name' => 'Document 1', + 'DocumentDirectory' => array( + 'id' => 1, + 'name' => 'DocumentDirectory 1' + )), + 'DeviceTypeCategory' => array( + 'id' => 1, + 'name' => 'DeviceTypeCategory 1' + ), + 'FeatureSet' => array( + 'id' => 1, + 'name' => 'FeatureSet 1' + ), + 'ExteriorTypeCategory' => array( + 'id' => 1, + 'image_id' => 1, + 'name' => 'ExteriorTypeCategory 1', + 'Image' => array( + 'id' => 1, + 'device_type_id' => 1, + 'name' => 'Device 1', + 'typ' => 1 + )), + 'Device' => array( + array( + 'id' => 1, + 'device_type_id' => 1, + 'name' => 'Device 1', + 'typ' => 1 + ), + array( + 'id' => 2, + 'device_type_id' => 1, + 'name' => 'Device 2', + 'typ' => 1 + ), + array( + 'id' => 3, + 'device_type_id' => 1, + 'name' => 'Device 3', + 'typ' => 2 + ))); + + $this->assertEquals($expected, $result); + } + +/** + * testHabtmRecursiveBelongsTo method + * + * @return void + */ + public function testHabtmRecursiveBelongsTo() { + $this->loadFixtures('Portfolio', 'Item', 'ItemsPortfolio', 'Syfile', 'Image'); + $Portfolio = new Portfolio(); + + $result = $Portfolio->find('first', array('conditions' => array('id' => 2), 'recursive' => 3)); + $expected = array( + 'Portfolio' => array( + 'id' => 2, + 'seller_id' => 1, + 'name' => 'Portfolio 2' + ), + 'Item' => array( + array( + 'id' => 2, + 'syfile_id' => 2, + 'published' => false, + 'name' => 'Item 2', + 'ItemsPortfolio' => array( + 'id' => 2, + 'item_id' => 2, + 'portfolio_id' => 2 + ), + 'Syfile' => array( + 'id' => 2, + 'image_id' => 2, + 'name' => 'Syfile 2', + 'item_count' => null, + 'Image' => array( + 'id' => 2, + 'name' => 'Image 2' + ) + )), + array( + 'id' => 6, + 'syfile_id' => 6, + 'published' => false, + 'name' => 'Item 6', + 'ItemsPortfolio' => array( + 'id' => 6, + 'item_id' => 6, + 'portfolio_id' => 2 + ), + 'Syfile' => array( + 'id' => 6, + 'image_id' => null, + 'name' => 'Syfile 6', + 'item_count' => null, + 'Image' => array() + )))); + + $this->assertEquals($expected, $result); + } + +/** + * testNonNumericHabtmJoinKey method + * + * @return void + */ + public function testNonNumericHabtmJoinKey() { + $this->loadFixtures('Post', 'Tag', 'PostsTag', 'Author'); + $Post = new Post(); + $Post->bindModel(array( + 'hasAndBelongsToMany' => array('Tag') + )); + $Post->Tag->primaryKey = 'tag'; + + $result = $Post->find('all'); + $expected = array( + array( + 'Post' => array( + 'id' => '1', + 'author_id' => '1', + 'title' => 'First Post', + 'body' => 'First Post Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:39:23', + 'updated' => '2007-03-18 10:41:31' + ), + 'Author' => array( + 'id' => 1, + 'user' => 'mariano', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', + 'updated' => '2007-03-17 01:18:31', + 'test' => 'working' + ), + 'Tag' => array( + array( + 'id' => '1', + 'tag' => 'tag1', + 'created' => '2007-03-18 12:22:23', + 'updated' => '2007-03-18 12:24:31' + ), + array( + 'id' => '2', + 'tag' => 'tag2', + 'created' => '2007-03-18 12:24:23', + 'updated' => '2007-03-18 12:26:31' + ))), + array( + 'Post' => array( + 'id' => '2', + 'author_id' => '3', + 'title' => 'Second Post', + 'body' => 'Second Post Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:41:23', + 'updated' => '2007-03-18 10:43:31' + ), + 'Author' => array( + 'id' => 3, + 'user' => 'larry', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:20:23', + 'updated' => '2007-03-17 01:22:31', + 'test' => 'working' + ), + 'Tag' => array( + array( + 'id' => '1', + 'tag' => 'tag1', + 'created' => '2007-03-18 12:22:23', + 'updated' => '2007-03-18 12:24:31' + ), + array( + 'id' => '3', + 'tag' => 'tag3', + 'created' => '2007-03-18 12:26:23', + 'updated' => '2007-03-18 12:28:31' + ))), + array( + 'Post' => array( + 'id' => '3', + 'author_id' => '1', + 'title' => 'Third Post', + 'body' => 'Third Post Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:43:23', + 'updated' => '2007-03-18 10:45:31' + ), + 'Author' => array( + 'id' => 1, + 'user' => 'mariano', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', + 'updated' => '2007-03-17 01:18:31', + 'test' => 'working' + ), + 'Tag' => array() + )); + $this->assertEquals($expected, $result); + } + +/** + * testHabtmFinderQuery method + * + * @return void + */ + public function testHabtmFinderQuery() { + $this->loadFixtures('Article', 'Tag', 'ArticlesTag'); + $Article = new Article(); + + $sql = $this->db->buildStatement( + array( + 'fields' => $this->db->fields($Article->Tag, null, array( + 'Tag.id', 'Tag.tag', 'ArticlesTag.article_id', 'ArticlesTag.tag_id' + )), + 'table' => $this->db->fullTableName('tags'), + 'alias' => 'Tag', + 'limit' => null, + 'offset' => null, + 'group' => null, + 'joins' => array(array( + 'alias' => 'ArticlesTag', + 'table' => 'articles_tags', + 'conditions' => array( + array("ArticlesTag.article_id" => '{$__cakeID__$}'), + array("ArticlesTag.tag_id" => $this->db->identifier('Tag.id')) + ) + )), + 'conditions' => array(), + 'order' => null + ), + $Article + ); + + $Article->hasAndBelongsToMany['Tag']['finderQuery'] = $sql; + $result = $Article->find('first'); + $expected = array( + array( + 'id' => '1', + 'tag' => 'tag1' + ), + array( + 'id' => '2', + 'tag' => 'tag2' + )); + + $this->assertEquals($expected, $result['Tag']); + } + +/** + * testHabtmLimitOptimization method + * + * @return void + */ + public function testHabtmLimitOptimization() { + $this->loadFixtures('Article', 'User', 'Comment', 'Tag', 'ArticlesTag'); + $TestModel = new Article(); + + $TestModel->hasAndBelongsToMany['Tag']['limit'] = 2; + $result = $TestModel->read(null, 2); + $expected = array( + 'Article' => array( + 'id' => '2', + 'user_id' => '3', + 'title' => 'Second Article', + 'body' => 'Second Article Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:41:23', + 'updated' => '2007-03-18 10:43:31' + ), + 'User' => array( + 'id' => '3', + 'user' => 'larry', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:20:23', + 'updated' => '2007-03-17 01:22:31' + ), + 'Comment' => array( + array( + 'id' => '5', + 'article_id' => '2', + 'user_id' => '1', + 'comment' => 'First Comment for Second Article', + 'published' => 'Y', + 'created' => '2007-03-18 10:53:23', + 'updated' => '2007-03-18 10:55:31' + ), + array( + 'id' => '6', + 'article_id' => '2', + 'user_id' => '2', + 'comment' => 'Second Comment for Second Article', + 'published' => 'Y', + 'created' => '2007-03-18 10:55:23', + 'updated' => '2007-03-18 10:57:31' + )), + 'Tag' => array( + array( + 'id' => '1', + 'tag' => 'tag1', + 'created' => '2007-03-18 12:22:23', + 'updated' => '2007-03-18 12:24:31' + ), + array( + 'id' => '3', + 'tag' => 'tag3', + 'created' => '2007-03-18 12:26:23', + 'updated' => '2007-03-18 12:28:31' + ))); + + $this->assertEquals($expected, $result); + + $TestModel->hasAndBelongsToMany['Tag']['limit'] = 1; + $result = $TestModel->read(null, 2); + unset($expected['Tag'][1]); + + $this->assertEquals($expected, $result); + } + +/** + * testHasManyLimitOptimization method + * + * @return void + */ + public function testHasManyLimitOptimization() { + $this->loadFixtures('Project', 'Thread', 'Message', 'Bid'); + $Project = new Project(); + $Project->recursive = 3; + + $result = $Project->find('all'); + $expected = array( + array( + 'Project' => array( + 'id' => 1, + 'name' => 'Project 1' + ), + 'Thread' => array( + array( + 'id' => 1, + 'project_id' => 1, + 'name' => 'Project 1, Thread 1', + 'Project' => array( + 'id' => 1, + 'name' => 'Project 1', + 'Thread' => array( + array( + 'id' => 1, + 'project_id' => 1, + 'name' => 'Project 1, Thread 1' + ), + array( + 'id' => 2, + 'project_id' => 1, + 'name' => 'Project 1, Thread 2' + ))), + 'Message' => array( + array( + 'id' => 1, + 'thread_id' => 1, + 'name' => 'Thread 1, Message 1', + 'Bid' => array( + 'id' => 1, + 'message_id' => 1, + 'name' => 'Bid 1.1' + )))), + array( + 'id' => 2, + 'project_id' => 1, + 'name' => 'Project 1, Thread 2', + 'Project' => array( + 'id' => 1, + 'name' => 'Project 1', + 'Thread' => array( + array( + 'id' => 1, + 'project_id' => 1, + 'name' => 'Project 1, Thread 1' + ), + array( + 'id' => 2, + 'project_id' => 1, + 'name' => 'Project 1, Thread 2' + ))), + 'Message' => array( + array( + 'id' => 2, + 'thread_id' => 2, + 'name' => 'Thread 2, Message 1', + 'Bid' => array( + 'id' => 4, + 'message_id' => 2, + 'name' => 'Bid 2.1' + )))))), + array( + 'Project' => array( + 'id' => 2, + 'name' => 'Project 2' + ), + 'Thread' => array( + array( + 'id' => 3, + 'project_id' => 2, + 'name' => 'Project 2, Thread 1', + 'Project' => array( + 'id' => 2, + 'name' => 'Project 2', + 'Thread' => array( + array( + 'id' => 3, + 'project_id' => 2, + 'name' => 'Project 2, Thread 1' + ))), + 'Message' => array( + array( + 'id' => 3, + 'thread_id' => 3, + 'name' => 'Thread 3, Message 1', + 'Bid' => array( + 'id' => 3, + 'message_id' => 3, + 'name' => 'Bid 3.1' + )))))), + array( + 'Project' => array( + 'id' => 3, + 'name' => 'Project 3' + ), + 'Thread' => array() + )); + + $this->assertEquals($expected, $result); + } + +/** + * testFindAllRecursiveSelfJoin method + * + * @return void + */ + public function testFindAllRecursiveSelfJoin() { + $this->loadFixtures('Home', 'AnotherArticle', 'Advertisement'); + $TestModel = new Home(); + $TestModel->recursive = 2; + + $result = $TestModel->find('all'); + $expected = array( + array( + 'Home' => array( + 'id' => '1', + 'another_article_id' => '1', + 'advertisement_id' => '1', + 'title' => 'First Home', + 'created' => '2007-03-18 10:39:23', + 'updated' => '2007-03-18 10:41:31' + ), + 'AnotherArticle' => array( + 'id' => '1', + 'title' => 'First Article', + 'created' => '2007-03-18 10:39:23', + 'updated' => '2007-03-18 10:41:31', + 'Home' => array( + array( + 'id' => '1', + 'another_article_id' => '1', + 'advertisement_id' => '1', + 'title' => 'First Home', + 'created' => '2007-03-18 10:39:23', + 'updated' => '2007-03-18 10:41:31' + ))), + 'Advertisement' => array( + 'id' => '1', + 'title' => 'First Ad', + 'created' => '2007-03-18 10:39:23', + 'updated' => '2007-03-18 10:41:31', + 'Home' => array( + array( + 'id' => '1', + 'another_article_id' => '1', + 'advertisement_id' => '1', + 'title' => 'First Home', + 'created' => '2007-03-18 10:39:23', + 'updated' => '2007-03-18 10:41:31' + ), + array( + 'id' => '2', + 'another_article_id' => '3', + 'advertisement_id' => '1', + 'title' => 'Second Home', + 'created' => '2007-03-18 10:41:23', + 'updated' => '2007-03-18 10:43:31' + )))), + array( + 'Home' => array( + 'id' => '2', + 'another_article_id' => '3', + 'advertisement_id' => '1', + 'title' => 'Second Home', + 'created' => '2007-03-18 10:41:23', + 'updated' => '2007-03-18 10:43:31' + ), + 'AnotherArticle' => array( + 'id' => '3', + 'title' => 'Third Article', + 'created' => '2007-03-18 10:43:23', + 'updated' => '2007-03-18 10:45:31', + 'Home' => array( + array( + 'id' => '2', + 'another_article_id' => '3', + 'advertisement_id' => '1', + 'title' => 'Second Home', + 'created' => '2007-03-18 10:41:23', + 'updated' => '2007-03-18 10:43:31' + ))), + 'Advertisement' => array( + 'id' => '1', + 'title' => 'First Ad', + 'created' => '2007-03-18 10:39:23', + 'updated' => '2007-03-18 10:41:31', + 'Home' => array( + array( + 'id' => '1', + 'another_article_id' => '1', + 'advertisement_id' => '1', + 'title' => 'First Home', + 'created' => '2007-03-18 10:39:23', + 'updated' => '2007-03-18 10:41:31' + ), + array( + 'id' => '2', + 'another_article_id' => '3', + 'advertisement_id' => '1', + 'title' => 'Second Home', + 'created' => '2007-03-18 10:41:23', + 'updated' => '2007-03-18 10:43:31' + ))))); + + $this->assertEquals($expected, $result); + } + +/** + * testFindAllRecursiveWithHabtm method + * + * @return void + */ + public function testFindAllRecursiveWithHabtm() { + $this->loadFixtures( + 'MyCategoriesMyUsers', + 'MyCategoriesMyProducts', + 'MyCategory', + 'MyUser', + 'MyProduct' + ); + + $MyUser = new MyUser(); + $MyUser->recursive = 2; + + $result = $MyUser->find('all'); + $expected = array( + array( + 'MyUser' => array('id' => '1', 'firstname' => 'userA'), + 'MyCategory' => array( + array( + 'id' => '1', + 'name' => 'A', + 'MyProduct' => array( + array( + 'id' => '1', + 'name' => 'book' + ))), + array( + 'id' => '3', + 'name' => 'C', + 'MyProduct' => array( + array( + 'id' => '2', + 'name' => 'computer' + ))))), + array( + 'MyUser' => array( + 'id' => '2', + 'firstname' => 'userB' + ), + 'MyCategory' => array( + array( + 'id' => '1', + 'name' => 'A', + 'MyProduct' => array( + array( + 'id' => '1', + 'name' => 'book' + ))), + array( + 'id' => '2', + 'name' => 'B', + 'MyProduct' => array( + array( + 'id' => '1', + 'name' => 'book' + ), + array( + 'id' => '2', + 'name' => 'computer' + )))))); + + $this->assertEquals($expected, $result); + } + +/** + * testReadFakeThread method + * + * @return void + */ + public function testReadFakeThread() { + $this->loadFixtures('CategoryThread'); + $TestModel = new CategoryThread(); + + $fullDebug = $this->db->fullDebug; + $this->db->fullDebug = true; + $TestModel->recursive = 6; + $TestModel->id = 7; + $result = $TestModel->read(); + $expected = array( + 'CategoryThread' => array( + 'id' => 7, + 'parent_id' => 6, + 'name' => 'Category 2.1', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31' + ), + 'ParentCategory' => array( + 'id' => 6, + 'parent_id' => 5, + 'name' => 'Category 2', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31', + 'ParentCategory' => array( + 'id' => 5, + 'parent_id' => 4, + 'name' => 'Category 1.1.1.1', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31', + 'ParentCategory' => array( + 'id' => 4, + 'parent_id' => 3, + 'name' => 'Category 1.1.2', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31', + 'ParentCategory' => array( + 'id' => 3, + 'parent_id' => 2, + 'name' => 'Category 1.1.1', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31', + 'ParentCategory' => array( + 'id' => 2, + 'parent_id' => 1, + 'name' => 'Category 1.1', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31', + 'ParentCategory' => array( + 'id' => 1, + 'parent_id' => 0, + 'name' => 'Category 1', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31' + ))))))); + + $this->db->fullDebug = $fullDebug; + $this->assertEquals($expected, $result); + } + +/** + * testFindFakeThread method + * + * @return void + */ + public function testFindFakeThread() { + $this->loadFixtures('CategoryThread'); + $TestModel = new CategoryThread(); + + $fullDebug = $this->db->fullDebug; + $this->db->fullDebug = true; + $TestModel->recursive = 6; + $result = $TestModel->find('first', array('conditions' => array('CategoryThread.id' => 7))); + + $expected = array( + 'CategoryThread' => array( + 'id' => 7, + 'parent_id' => 6, + 'name' => 'Category 2.1', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31' + ), + 'ParentCategory' => array( + 'id' => 6, + 'parent_id' => 5, + 'name' => 'Category 2', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31', + 'ParentCategory' => array( + 'id' => 5, + 'parent_id' => 4, + 'name' => 'Category 1.1.1.1', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31', + 'ParentCategory' => array( + 'id' => 4, + 'parent_id' => 3, + 'name' => 'Category 1.1.2', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31', + 'ParentCategory' => array( + 'id' => 3, + 'parent_id' => 2, + 'name' => 'Category 1.1.1', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31', + 'ParentCategory' => array( + 'id' => 2, + 'parent_id' => 1, + 'name' => 'Category 1.1', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31', + 'ParentCategory' => array( + 'id' => 1, + 'parent_id' => 0, + 'name' => 'Category 1', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31' + ))))))); + + $this->db->fullDebug = $fullDebug; + $this->assertEquals($expected, $result); + } + +/** + * testFindAllFakeThread method + * + * @return void + */ + public function testFindAllFakeThread() { + $this->loadFixtures('CategoryThread'); + $TestModel = new CategoryThread(); + + $fullDebug = $this->db->fullDebug; + $this->db->fullDebug = true; + $TestModel->recursive = 6; + $result = $TestModel->find('all', null, null, 'CategoryThread.id ASC'); + $expected = array( + array( + 'CategoryThread' => array( + 'id' => 1, + 'parent_id' => 0, + 'name' => 'Category 1', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31' + ), + 'ParentCategory' => array( + 'id' => null, + 'parent_id' => null, + 'name' => null, + 'created' => null, + 'updated' => null, + 'ParentCategory' => array() + )), + array( + 'CategoryThread' => array( + 'id' => 2, + 'parent_id' => 1, + 'name' => 'Category 1.1', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31' + ), + 'ParentCategory' => array( + 'id' => 1, + 'parent_id' => 0, + 'name' => 'Category 1', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31', + 'ParentCategory' => array() + )), + array( + 'CategoryThread' => array( + 'id' => 3, + 'parent_id' => 2, + 'name' => 'Category 1.1.1', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31' + ), + 'ParentCategory' => array( + 'id' => 2, + 'parent_id' => 1, + 'name' => 'Category 1.1', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31', + 'ParentCategory' => array( + 'id' => 1, + 'parent_id' => 0, + 'name' => 'Category 1', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31', + 'ParentCategory' => array() + ))), + array( + 'CategoryThread' => array( + 'id' => 4, + 'parent_id' => 3, + 'name' => 'Category 1.1.2', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31' + ), + 'ParentCategory' => array( + 'id' => 3, + 'parent_id' => 2, + 'name' => 'Category 1.1.1', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31', + 'ParentCategory' => array( + 'id' => 2, + 'parent_id' => 1, + 'name' => 'Category 1.1', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31', + 'ParentCategory' => array( + 'id' => 1, + 'parent_id' => 0, + 'name' => 'Category 1', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31', + 'ParentCategory' => array() + )))), + array( + 'CategoryThread' => array( + 'id' => 5, + 'parent_id' => 4, + 'name' => 'Category 1.1.1.1', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31' + ), + 'ParentCategory' => array( + 'id' => 4, + 'parent_id' => 3, + 'name' => 'Category 1.1.2', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31', + 'ParentCategory' => array( + 'id' => 3, + 'parent_id' => 2, + 'name' => 'Category 1.1.1', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31', + 'ParentCategory' => array( + 'id' => 2, + 'parent_id' => 1, + 'name' => 'Category 1.1', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31', + 'ParentCategory' => array( + 'id' => 1, + 'parent_id' => 0, + 'name' => 'Category 1', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31', + 'ParentCategory' => array() + ))))), + array( + 'CategoryThread' => array( + 'id' => 6, + 'parent_id' => 5, + 'name' => 'Category 2', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31' + ), + 'ParentCategory' => array( + 'id' => 5, + 'parent_id' => 4, + 'name' => 'Category 1.1.1.1', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31', + 'ParentCategory' => array( + 'id' => 4, + 'parent_id' => 3, + 'name' => 'Category 1.1.2', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31', + 'ParentCategory' => array( + 'id' => 3, + 'parent_id' => 2, + 'name' => 'Category 1.1.1', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31', + 'ParentCategory' => array( + 'id' => 2, + 'parent_id' => 1, + 'name' => 'Category 1.1', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31', + 'ParentCategory' => array( + 'id' => 1, + 'parent_id' => 0, + 'name' => 'Category 1', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31', + 'ParentCategory' => array() + )))))), + array( + 'CategoryThread' => array( + 'id' => 7, + 'parent_id' => 6, + 'name' => 'Category 2.1', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31' + ), + 'ParentCategory' => array( + 'id' => 6, + 'parent_id' => 5, + 'name' => 'Category 2', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31', + 'ParentCategory' => array( + 'id' => 5, + 'parent_id' => 4, + 'name' => 'Category 1.1.1.1', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31', + 'ParentCategory' => array( + 'id' => 4, + 'parent_id' => 3, + 'name' => 'Category 1.1.2', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31', + 'ParentCategory' => array( + 'id' => 3, + 'parent_id' => 2, + 'name' => 'Category 1.1.1', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31', + 'ParentCategory' => array( + 'id' => 2, + 'parent_id' => 1, + 'name' => 'Category 1.1', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31', + 'ParentCategory' => array( + 'id' => 1, + 'parent_id' => 0, + 'name' => 'Category 1', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31' + )))))))); + + $this->db->fullDebug = $fullDebug; + $this->assertEquals($expected, $result); + } + +/** + * testConditionalNumerics method + * + * @return void + */ + public function testConditionalNumerics() { + $this->loadFixtures('NumericArticle'); + $NumericArticle = new NumericArticle(); + $data = array('conditions' => array('title' => '12345abcde')); + $result = $NumericArticle->find('first', $data); + $this->assertTrue(!empty($result)); + + $data = array('conditions' => array('title' => '12345')); + $result = $NumericArticle->find('first', $data); + $this->assertTrue(empty($result)); + } + +/** + * test buildQuery() + * + * @return void + */ + public function testBuildQuery() { + $this->loadFixtures('User'); + $TestModel = new User(); + $TestModel->cacheQueries = false; + + $expected = array( + 'conditions' => array( + 'user' => 'larry' + ), + 'fields' => null, + 'joins' => array(), + 'limit' => null, + 'offset' => null, + 'order' => array( + 0 => null + ), + 'page' => 1, + 'group' => null, + 'callbacks' => true, + 'returnQuery' => true + ); + $result = $TestModel->buildQuery('all', array('returnQuery' => true, 'conditions' => array('user' => 'larry'))); + $this->assertEquals($expected, $result); + } + +/** + * test find('all') method + * + * @return void + */ + public function testFindAll() { + $this->loadFixtures('User'); + $TestModel = new User(); + $TestModel->cacheQueries = false; + + $result = $TestModel->find('all'); + $expected = array( + array( + 'User' => array( + 'id' => '1', + 'user' => 'mariano', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', + 'updated' => '2007-03-17 01:18:31' + )), + array( + 'User' => array( + 'id' => '2', + 'user' => 'nate', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:18:23', + 'updated' => '2007-03-17 01:20:31' + )), + array( + 'User' => array( + 'id' => '3', + 'user' => 'larry', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:20:23', + 'updated' => '2007-03-17 01:22:31' + )), + array( + 'User' => array( + 'id' => '4', + 'user' => 'garrett', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:22:23', + 'updated' => '2007-03-17 01:24:31' + ))); + $this->assertEquals($expected, $result); + + $result = $TestModel->find('all', array('conditions' => 'User.id > 2')); + $expected = array( + array( + 'User' => array( + 'id' => '3', + 'user' => 'larry', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:20:23', + 'updated' => '2007-03-17 01:22:31' + )), + array( + 'User' => array( + 'id' => '4', + 'user' => 'garrett', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:22:23', + 'updated' => '2007-03-17 01:24:31' + ))); + $this->assertEquals($expected, $result); + + $result = $TestModel->find('all', array( + 'conditions' => array('User.id !=' => '0', 'User.user LIKE' => '%arr%') + )); + $expected = array( + array( + 'User' => array( + 'id' => '3', + 'user' => 'larry', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:20:23', + 'updated' => '2007-03-17 01:22:31' + )), + array( + 'User' => array( + 'id' => '4', + 'user' => 'garrett', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:22:23', + 'updated' => '2007-03-17 01:24:31' + ))); + $this->assertEquals($expected, $result); + + $result = $TestModel->find('all', array('conditions' => array('User.id' => '0'))); + $expected = array(); + $this->assertEquals($expected, $result); + + $result = $TestModel->find('all', array( + 'conditions' => array('or' => array('User.id' => '0', 'User.user LIKE' => '%a%') + ))); + + $expected = array( + array( + 'User' => array( + 'id' => '1', + 'user' => 'mariano', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', + 'updated' => '2007-03-17 01:18:31' + )), + array( + 'User' => array( + 'id' => '2', + 'user' => 'nate', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:18:23', + 'updated' => '2007-03-17 01:20:31' + )), + array( + 'User' => array( + 'id' => '3', + 'user' => 'larry', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:20:23', + 'updated' => '2007-03-17 01:22:31' + )), + array( + 'User' => array( + 'id' => '4', + 'user' => 'garrett', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:22:23', + 'updated' => '2007-03-17 01:24:31' + ))); + $this->assertEquals($expected, $result); + + $result = $TestModel->find('all', array('fields' => 'User.id, User.user')); + $expected = array( + array('User' => array('id' => '1', 'user' => 'mariano')), + array('User' => array('id' => '2', 'user' => 'nate')), + array('User' => array('id' => '3', 'user' => 'larry')), + array('User' => array('id' => '4', 'user' => 'garrett'))); + $this->assertEquals($expected, $result); + + $result = $TestModel->find('all', array('fields' => 'User.user', 'order' => 'User.user ASC')); + $expected = array( + array('User' => array('user' => 'garrett')), + array('User' => array('user' => 'larry')), + array('User' => array('user' => 'mariano')), + array('User' => array('user' => 'nate'))); + $this->assertEquals($expected, $result); + + $result = $TestModel->find('all', array('fields' => 'User.user', 'order' => 'User.user DESC')); + $expected = array( + array('User' => array('user' => 'nate')), + array('User' => array('user' => 'mariano')), + array('User' => array('user' => 'larry')), + array('User' => array('user' => 'garrett'))); + $this->assertEquals($expected, $result); + + $result = $TestModel->find('all', array('limit' => 3, 'page' => 1)); + + $expected = array( + array( + 'User' => array( + 'id' => '1', + 'user' => 'mariano', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', + 'updated' => '2007-03-17 01:18:31' + )), + array( + 'User' => array( + 'id' => '2', + 'user' => 'nate', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:18:23', + 'updated' => '2007-03-17 01:20:31' + )), + array( + 'User' => array( + 'id' => '3', + 'user' => 'larry', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:20:23', + 'updated' => '2007-03-17 01:22:31' + ))); + $this->assertEquals($expected, $result); + + $ids = array(4 => 1, 5 => 3); + $result = $TestModel->find('all', array( + 'conditions' => array('User.id' => $ids), + 'order' => 'User.id' + )); + $expected = array( + array( + 'User' => array( + 'id' => '1', + 'user' => 'mariano', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', + 'updated' => '2007-03-17 01:18:31' + )), + array( + 'User' => array( + 'id' => '3', + 'user' => 'larry', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:20:23', + 'updated' => '2007-03-17 01:22:31' + ))); + $this->assertEquals($expected, $result); + + // These tests are expected to fail on SQL Server since the LIMIT/OFFSET + // hack can't handle small record counts. + if (!($this->db instanceof Sqlserver)) { + $result = $TestModel->find('all', array('limit' => 3, 'page' => 2)); + $expected = array( + array( + 'User' => array( + 'id' => '4', + 'user' => 'garrett', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:22:23', + 'updated' => '2007-03-17 01:24:31' + ))); + $this->assertEquals($expected, $result); + + $result = $TestModel->find('all', array('limit' => 3, 'page' => 3)); + $expected = array(); + $this->assertEquals($expected, $result); + } + } + +/** + * test find('list') method + * + * @return void + */ + public function testGenerateFindList() { + $this->loadFixtures('Article', 'Apple', 'Post', 'Author', 'User', 'Comment'); + + $TestModel = new Article(); + $TestModel->displayField = 'title'; + + $result = $TestModel->find('list', array( + 'order' => 'Article.title ASC' + )); + + $expected = array( + 1 => 'First Article', + 2 => 'Second Article', + 3 => 'Third Article' + ); + $this->assertEquals($expected, $result); + + $db = ConnectionManager::getDataSource('test'); + if ($db instanceof Mysql) { + $result = $TestModel->find('list', array( + 'order' => array('FIELD(Article.id, 3, 2) ASC', 'Article.title ASC') + )); + $expected = array( + 1 => 'First Article', + 3 => 'Third Article', + 2 => 'Second Article' + ); + $this->assertEquals($expected, $result); + } + + $result = Hash::combine( + $TestModel->find('all', array( + 'order' => 'Article.title ASC', + 'fields' => array('id', 'title') + )), + '{n}.Article.id', '{n}.Article.title' + ); + $expected = array( + 1 => 'First Article', + 2 => 'Second Article', + 3 => 'Third Article' + ); + $this->assertEquals($expected, $result); + + $result = Hash::combine( + $TestModel->find('all', array( + 'order' => 'Article.title ASC' + )), + '{n}.Article.id', '{n}.Article' + ); + $expected = array( + 1 => array( + 'id' => 1, + 'user_id' => 1, + 'title' => 'First Article', + 'body' => 'First Article Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:39:23', + 'updated' => '2007-03-18 10:41:31' + ), + 2 => array( + 'id' => 2, + 'user_id' => 3, + 'title' => 'Second Article', + 'body' => 'Second Article Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:41:23', + 'updated' => '2007-03-18 10:43:31' + ), + 3 => array( + 'id' => 3, + 'user_id' => 1, + 'title' => 'Third Article', + 'body' => 'Third Article Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:43:23', + 'updated' => '2007-03-18 10:45:31' + )); + + $this->assertEquals($expected, $result); + + $result = Hash::combine( + $TestModel->find('all', array( + 'order' => 'Article.title ASC' + )), + '{n}.Article.id', '{n}.Article', '{n}.Article.user_id' + ); + $expected = array( + 1 => array( + 1 => array( + 'id' => 1, + 'user_id' => 1, + 'title' => 'First Article', + 'body' => 'First Article Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:39:23', + 'updated' => '2007-03-18 10:41:31' + ), + 3 => array( + 'id' => 3, + 'user_id' => 1, + 'title' => 'Third Article', + 'body' => 'Third Article Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:43:23', + 'updated' => '2007-03-18 10:45:31' + )), + 3 => array( + 2 => array( + 'id' => 2, + 'user_id' => 3, + 'title' => 'Second Article', + 'body' => 'Second Article Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:41:23', + 'updated' => '2007-03-18 10:43:31' + ))); + + $this->assertEquals($expected, $result); + + $result = Hash::combine( + $TestModel->find('all', array( + 'order' => 'Article.title ASC', + 'fields' => array('id', 'title', 'user_id') + )), + '{n}.Article.id', '{n}.Article.title', '{n}.Article.user_id' + ); + + $expected = array( + 1 => array( + 1 => 'First Article', + 3 => 'Third Article' + ), + 3 => array( + 2 => 'Second Article' + )); + $this->assertEquals($expected, $result); + + $TestModel = new Apple(); + $expected = array( + 1 => 'Red Apple 1', + 2 => 'Bright Red Apple', + 3 => 'green blue', + 4 => 'Test Name', + 5 => 'Blue Green', + 6 => 'My new apple', + 7 => 'Some odd color' + ); + + $this->assertEquals($expected, $TestModel->find('list')); + $this->assertEquals($expected, $TestModel->Parent->find('list')); + + $TestModel = new Post(); + $result = $TestModel->find('list', array( + 'fields' => 'Post.title' + )); + $expected = array( + 1 => 'First Post', + 2 => 'Second Post', + 3 => 'Third Post' + ); + $this->assertEquals($expected, $result); + + $result = $TestModel->find('list', array( + 'fields' => 'title' + )); + $expected = array( + 1 => 'First Post', + 2 => 'Second Post', + 3 => 'Third Post' + ); + $this->assertEquals($expected, $result); + + $result = $TestModel->find('list', array( + 'fields' => array('title', 'id') + )); + $expected = array( + 'First Post' => '1', + 'Second Post' => '2', + 'Third Post' => '3' + ); + $this->assertEquals($expected, $result); + + $result = $TestModel->find('list', array( + 'fields' => array('title', 'id', 'created') + )); + $expected = array( + '2007-03-18 10:39:23' => array( + 'First Post' => '1' + ), + '2007-03-18 10:41:23' => array( + 'Second Post' => '2' + ), + '2007-03-18 10:43:23' => array( + 'Third Post' => '3' + ), + ); + $this->assertEquals($expected, $result); + + $result = $TestModel->find('list', array( + 'fields' => array('Post.body') + )); + $expected = array( + 1 => 'First Post Body', + 2 => 'Second Post Body', + 3 => 'Third Post Body' + ); + $this->assertEquals($expected, $result); + + $result = $TestModel->find('list', array( + 'fields' => array('Post.title', 'Post.body') + )); + $expected = array( + 'First Post' => 'First Post Body', + 'Second Post' => 'Second Post Body', + 'Third Post' => 'Third Post Body' + ); + $this->assertEquals($expected, $result); + + $result = $TestModel->find('list', array( + 'fields' => array('Post.id', 'Post.title', 'Author.user'), + 'recursive' => 1 + )); + $expected = array( + 'mariano' => array( + 1 => 'First Post', + 3 => 'Third Post' + ), + 'larry' => array( + 2 => 'Second Post' + )); + $this->assertEquals($expected, $result); + + $TestModel = new User(); + $result = $TestModel->find('list', array( + 'fields' => array('User.user', 'User.password') + )); + $expected = array( + 'mariano' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'nate' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'larry' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'garrett' => '5f4dcc3b5aa765d61d8327deb882cf99' + ); + $this->assertEquals($expected, $result); + + $TestModel = new ModifiedAuthor(); + $result = $TestModel->find('list', array( + 'fields' => array('Author.id', 'Author.user') + )); + $expected = array( + 1 => 'mariano (CakePHP)', + 2 => 'nate (CakePHP)', + 3 => 'larry (CakePHP)', + 4 => 'garrett (CakePHP)' + ); + $this->assertEquals($expected, $result); + + $TestModel = new Article(); + $TestModel->displayField = 'title'; + $result = $TestModel->find('list', array( + 'conditions' => array('User.user' => 'mariano'), + 'recursive' => 0 + )); + $expected = array( + 1 => 'First Article', + 3 => 'Third Article' + ); + $this->assertEquals($expected, $result); + } + +/** + * testFindField method + * + * @return void + */ + public function testFindField() { + $this->loadFixtures('User'); + $TestModel = new User(); + + $TestModel->id = 1; + $result = $TestModel->field('user'); + $this->assertEquals('mariano', $result); + + $result = $TestModel->field('User.user'); + $this->assertEquals('mariano', $result); + + $TestModel->id = false; + $result = $TestModel->field('user', array( + 'user' => 'mariano' + )); + $this->assertEquals('mariano', $result); + + $result = $TestModel->field('COUNT(*) AS count', true); + $this->assertEquals(4, $result); + + $result = $TestModel->field('COUNT(*)', true); + $this->assertEquals(4, $result); + } + +/** + * testFindUnique method + * + * @return void + */ + public function testFindUnique() { + $this->loadFixtures('User'); + $TestModel = new User(); + + $this->assertFalse($TestModel->isUnique(array( + 'user' => 'nate' + ))); + $TestModel->id = 2; + $this->assertTrue($TestModel->isUnique(array( + 'user' => 'nate' + ))); + $this->assertFalse($TestModel->isUnique(array( + 'user' => 'nate', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99' + ))); + } + +/** + * test find('count') method + * + * @return void + */ + public function testFindCount() { + $this->loadFixtures('User', 'Article', 'Comment', 'Tag', 'ArticlesTag'); + + $TestModel = new User(); + $this->db->getLog(false, true); + $result = $TestModel->find('count'); + $this->assertEquals(4, $result); + + $this->db->getLog(false, true); + $fullDebug = $this->db->fullDebug; + $this->db->fullDebug = true; + $TestModel->order = 'User.id'; + $result = $TestModel->find('count'); + $this->db->fullDebug = $fullDebug; + $this->assertEquals(4, $result); + + $log = $this->db->getLog(); + $this->assertTrue(isset($log['log'][0]['query'])); + $this->assertNotRegExp('/ORDER\s+BY/', $log['log'][0]['query']); + + $Article = new Article(); + $Article->recursive = -1; + $expected = count($Article->find('all', array( + 'fields' => array('Article.user_id'), + 'group' => 'Article.user_id') + )); + $result = $Article->find('count', array('group' => array('Article.user_id'))); + $this->assertEquals($expected, $result); + } + +/** + * Test that find('first') does not use the id set to the object. + * + * @return void + */ + public function testFindFirstNoIdUsed() { + $this->loadFixtures('Project'); + + $Project = new Project(); + $Project->id = 3; + $result = $Project->find('first'); + + $this->assertEquals('Project 1', $result['Project']['name'], 'Wrong record retrieved'); + } + +/** + * test find with COUNT(DISTINCT field) + * + * @return void + */ + public function testFindCountDistinct() { + $this->skipIf($this->db instanceof Sqlite, 'SELECT COUNT(DISTINCT field) is not compatible with SQLite.'); + $this->skipIf($this->db instanceof Sqlserver, 'This test is not compatible with SQL Server.'); + + $this->loadFixtures('Project'); + $TestModel = new Project(); + $TestModel->create(array('name' => 'project')) && $TestModel->save(); + $TestModel->create(array('name' => 'project')) && $TestModel->save(); + $TestModel->create(array('name' => 'project')) && $TestModel->save(); + + $result = $TestModel->find('count', array('fields' => 'DISTINCT name')); + $this->assertEquals(4, $result); + } + +/** + * Test find(count) with Db::expression + * + * @return void + */ + public function testFindCountWithDbExpressions() { + $this->skipIf($this->db instanceof Postgres, 'testFindCountWithDbExpressions is not compatible with Postgres.'); + + $this->loadFixtures('Project', 'Thread'); + $db = ConnectionManager::getDataSource('test'); + $TestModel = new Project(); + + $result = $TestModel->find('count', array('conditions' => array( + $db->expression('Project.name = \'Project 3\'') + ))); + $this->assertEquals(1, $result); + + $result = $TestModel->find('count', array('conditions' => array( + 'Project.name' => $db->expression('\'Project 3\'') + ))); + $this->assertEquals(1, $result); + } + +/** + * testFindMagic method + * + * @return void + */ + public function testFindMagic() { + $this->loadFixtures('User'); + $TestModel = new User(); + + $result = $TestModel->findByUser('mariano'); + $expected = array( + 'User' => array( + 'id' => '1', + 'user' => 'mariano', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', + 'updated' => '2007-03-17 01:18:31' + )); + $this->assertEquals($expected, $result); + + $result = $TestModel->findByPassword('5f4dcc3b5aa765d61d8327deb882cf99'); + $expected = array('User' => array( + 'id' => '1', + 'user' => 'mariano', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', + 'updated' => '2007-03-17 01:18:31' + )); + $this->assertEquals($expected, $result); + } + +/** + * testRead method + * + * @return void + */ + public function testRead() { + $this->loadFixtures('User', 'Article'); + $TestModel = new User(); + + $result = $TestModel->read(); + $this->assertFalse($result); + + $TestModel->id = 2; + $result = $TestModel->read(); + $expected = array( + 'User' => array( + 'id' => '2', + 'user' => 'nate', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:18:23', + 'updated' => '2007-03-17 01:20:31' + )); + $this->assertEquals($expected, $result); + + $result = $TestModel->read(null, 2); + $expected = array( + 'User' => array( + 'id' => '2', + 'user' => 'nate', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:18:23', + 'updated' => '2007-03-17 01:20:31' + )); + $this->assertEquals($expected, $result); + + $TestModel->id = 2; + $result = $TestModel->read(array('id', 'user')); + $expected = array('User' => array('id' => '2', 'user' => 'nate')); + $this->assertEquals($expected, $result); + + $result = $TestModel->read('id, user', 2); + $expected = array( + 'User' => array( + 'id' => '2', + 'user' => 'nate' + )); + $this->assertEquals($expected, $result); + + $result = $TestModel->bindModel(array('hasMany' => array('Article'))); + $this->assertTrue($result); + + $TestModel->id = 1; + $result = $TestModel->read('id, user'); + $expected = array( + 'User' => array( + 'id' => '1', + 'user' => 'mariano' + ), + 'Article' => array( + array( + 'id' => '1', + 'user_id' => '1', + 'title' => 'First Article', + 'body' => 'First Article Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:39:23', + 'updated' => '2007-03-18 10:41:31' + ), + array( + 'id' => '3', + 'user_id' => '1', + 'title' => 'Third Article', + 'body' => 'Third Article Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:43:23', + 'updated' => '2007-03-18 10:45:31' + ))); + $this->assertEquals($expected, $result); + } + +/** + * testRecursiveRead method + * + * @return void + */ + public function testRecursiveRead() { + $this->loadFixtures( + 'User', + 'Article', + 'Comment', + 'Tag', + 'ArticlesTag', + 'Featured', + 'ArticleFeatured' + ); + $TestModel = new User(); + + $result = $TestModel->bindModel(array('hasMany' => array('Article')), false); + $this->assertTrue($result); + + $TestModel->recursive = 0; + $result = $TestModel->read('id, user', 1); + $expected = array( + 'User' => array('id' => '1', 'user' => 'mariano'), + ); + $this->assertEquals($expected, $result); + + $TestModel->recursive = 1; + $result = $TestModel->read('id, user', 1); + $expected = array( + 'User' => array( + 'id' => '1', + 'user' => 'mariano' + ), + 'Article' => array( + array( + 'id' => '1', + 'user_id' => '1', + 'title' => 'First Article', + 'body' => 'First Article Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:39:23', + 'updated' => '2007-03-18 10:41:31' + ), + array( + 'id' => '3', + 'user_id' => '1', + 'title' => 'Third Article', + 'body' => 'Third Article Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:43:23', + 'updated' => '2007-03-18 10:45:31' + ))); + $this->assertEquals($expected, $result); + + $TestModel->recursive = 2; + $result = $TestModel->read('id, user', 3); + $expected = array( + 'User' => array( + 'id' => '3', + 'user' => 'larry' + ), + 'Article' => array( + array( + 'id' => '2', + 'user_id' => '3', + 'title' => 'Second Article', + 'body' => 'Second Article Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:41:23', + 'updated' => '2007-03-18 10:43:31', + 'User' => array( + 'id' => '3', + 'user' => 'larry', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:20:23', + 'updated' => '2007-03-17 01:22:31' + ), + 'Comment' => array( + array( + 'id' => '5', + 'article_id' => '2', + 'user_id' => '1', + 'comment' => 'First Comment for Second Article', + 'published' => 'Y', + 'created' => '2007-03-18 10:53:23', + 'updated' => '2007-03-18 10:55:31' + ), + array( + 'id' => '6', + 'article_id' => '2', + 'user_id' => '2', + 'comment' => 'Second Comment for Second Article', + 'published' => 'Y', + 'created' => '2007-03-18 10:55:23', + 'updated' => '2007-03-18 10:57:31' + )), + 'Tag' => array( + array( + 'id' => '1', + 'tag' => 'tag1', + 'created' => '2007-03-18 12:22:23', + 'updated' => '2007-03-18 12:24:31' + ), + array( + 'id' => '3', + 'tag' => 'tag3', + 'created' => '2007-03-18 12:26:23', + 'updated' => '2007-03-18 12:28:31' + ))))); + $this->assertEquals($expected, $result); + } + + public function testRecursiveFindAll() { + $this->loadFixtures( + 'User', + 'Article', + 'Comment', + 'Tag', + 'ArticlesTag', + 'Attachment', + 'ArticleFeatured', + 'ArticleFeaturedsTags', + 'Featured', + 'Category' + ); + $TestModel = new Article(); + + $result = $TestModel->find('all', array('conditions' => array('Article.user_id' => 1))); + $expected = array( + array( + 'Article' => array( + 'id' => '1', + 'user_id' => '1', + 'title' => 'First Article', + 'body' => 'First Article Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:39:23', + 'updated' => '2007-03-18 10:41:31' + ), + 'User' => array( + 'id' => '1', + 'user' => 'mariano', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', + 'updated' => '2007-03-17 01:18:31' + ), + 'Comment' => array( + array( + 'id' => '1', + 'article_id' => '1', + 'user_id' => '2', + 'comment' => 'First Comment for First Article', + 'published' => 'Y', + 'created' => '2007-03-18 10:45:23', + 'updated' => '2007-03-18 10:47:31' + ), + array( + 'id' => '2', + 'article_id' => '1', + 'user_id' => '4', + 'comment' => 'Second Comment for First Article', + 'published' => 'Y', + 'created' => '2007-03-18 10:47:23', + 'updated' => '2007-03-18 10:49:31' + ), + array( + 'id' => '3', + 'article_id' => '1', + 'user_id' => '1', + 'comment' => 'Third Comment for First Article', + 'published' => 'Y', + 'created' => '2007-03-18 10:49:23', + 'updated' => '2007-03-18 10:51:31' + ), + array( + 'id' => '4', + 'article_id' => '1', + 'user_id' => '1', + 'comment' => 'Fourth Comment for First Article', + 'published' => 'N', + 'created' => '2007-03-18 10:51:23', + 'updated' => '2007-03-18 10:53:31' + ) + ), + 'Tag' => array( + array( + 'id' => '1', + 'tag' => 'tag1', + 'created' => '2007-03-18 12:22:23', + 'updated' => '2007-03-18 12:24:31' + ), + array( + 'id' => '2', + 'tag' => 'tag2', + 'created' => '2007-03-18 12:24:23', + 'updated' => '2007-03-18 12:26:31' + ))), + array( + 'Article' => array( + 'id' => '3', + 'user_id' => '1', + 'title' => 'Third Article', + 'body' => 'Third Article Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:43:23', + 'updated' => '2007-03-18 10:45:31' + ), + 'User' => array( + 'id' => '1', + 'user' => 'mariano', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', + 'updated' => '2007-03-17 01:18:31' + ), + 'Comment' => array(), + 'Tag' => array() + ) + ); + $this->assertEquals($expected, $result); + + $result = $TestModel->find('all', array( + 'conditions' => array('Article.user_id' => 3), + 'limit' => 1, + 'recursive' => 2 + )); + + $expected = array( + array( + 'Article' => array( + 'id' => '2', + 'user_id' => '3', + 'title' => 'Second Article', + 'body' => 'Second Article Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:41:23', + 'updated' => '2007-03-18 10:43:31' + ), + 'User' => array( + 'id' => '3', + 'user' => 'larry', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:20:23', + 'updated' => '2007-03-17 01:22:31' + ), + 'Comment' => array( + array( + 'id' => '5', + 'article_id' => '2', + 'user_id' => '1', + 'comment' => 'First Comment for Second Article', + 'published' => 'Y', + 'created' => '2007-03-18 10:53:23', + 'updated' => '2007-03-18 10:55:31', + 'Article' => array( + 'id' => '2', + 'user_id' => '3', + 'title' => 'Second Article', + 'body' => 'Second Article Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:41:23', + 'updated' => '2007-03-18 10:43:31' + ), + 'User' => array( + 'id' => '1', + 'user' => 'mariano', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', + 'updated' => '2007-03-17 01:18:31' + ), + 'Attachment' => array( + 'id' => '1', + 'comment_id' => 5, + 'attachment' => 'attachment.zip', + 'created' => '2007-03-18 10:51:23', + 'updated' => '2007-03-18 10:53:31' + ) + ), + array( + 'id' => '6', + 'article_id' => '2', + 'user_id' => '2', + 'comment' => 'Second Comment for Second Article', + 'published' => 'Y', + 'created' => '2007-03-18 10:55:23', + 'updated' => '2007-03-18 10:57:31', + 'Article' => array( + 'id' => '2', + 'user_id' => '3', + 'title' => 'Second Article', + 'body' => 'Second Article Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:41:23', + 'updated' => '2007-03-18 10:43:31' + ), + 'User' => array( + 'id' => '2', + 'user' => 'nate', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:18:23', + 'updated' => '2007-03-17 01:20:31' + ), + 'Attachment' => array() + ) + ), + 'Tag' => array( + array( + 'id' => '1', + 'tag' => 'tag1', + 'created' => '2007-03-18 12:22:23', + 'updated' => '2007-03-18 12:24:31' + ), + array( + 'id' => '3', + 'tag' => 'tag3', + 'created' => '2007-03-18 12:26:23', + 'updated' => '2007-03-18 12:28:31' + )))); + + $this->assertEquals($expected, $result); + + $Featured = new Featured(); + + $Featured->recursive = 2; + $Featured->bindModel(array( + 'belongsTo' => array( + 'ArticleFeatured' => array( + 'conditions' => "ArticleFeatured.published = 'Y'", + 'fields' => 'id, title, user_id, published' + ) + ) + )); + + $Featured->ArticleFeatured->unbindModel(array( + 'hasMany' => array('Attachment', 'Comment'), + 'hasAndBelongsToMany' => array('Tag')) + ); + + $orderBy = 'ArticleFeatured.id ASC'; + $result = $Featured->find('all', array( + 'order' => $orderBy, 'limit' => 3 + )); + + $expected = array( + array( + 'Featured' => array( + 'id' => '1', + 'article_featured_id' => '1', + 'category_id' => '1', + 'published_date' => '2007-03-31 10:39:23', + 'end_date' => '2007-05-15 10:39:23', + 'created' => '2007-03-18 10:39:23', + 'updated' => '2007-03-18 10:41:31' + ), + 'ArticleFeatured' => array( + 'id' => '1', + 'title' => 'First Article', + 'user_id' => '1', + 'published' => 'Y', + 'User' => array( + 'id' => '1', + 'user' => 'mariano', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', + 'updated' => '2007-03-17 01:18:31' + ), + 'Category' => array(), + 'Featured' => array( + 'id' => '1', + 'article_featured_id' => '1', + 'category_id' => '1', + 'published_date' => '2007-03-31 10:39:23', + 'end_date' => '2007-05-15 10:39:23', + 'created' => '2007-03-18 10:39:23', + 'updated' => '2007-03-18 10:41:31' + )), + 'Category' => array( + 'id' => '1', + 'parent_id' => '0', + 'name' => 'Category 1', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31' + )), + array( + 'Featured' => array( + 'id' => '2', + 'article_featured_id' => '2', + 'category_id' => '1', + 'published_date' => '2007-03-31 10:39:23', + 'end_date' => '2007-05-15 10:39:23', + 'created' => '2007-03-18 10:39:23', + 'updated' => '2007-03-18 10:41:31' + ), + 'ArticleFeatured' => array( + 'id' => '2', + 'title' => 'Second Article', + 'user_id' => '3', + 'published' => 'Y', + 'User' => array( + 'id' => '3', + 'user' => 'larry', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:20:23', + 'updated' => '2007-03-17 01:22:31' + ), + 'Category' => array(), + 'Featured' => array( + 'id' => '2', + 'article_featured_id' => '2', + 'category_id' => '1', + 'published_date' => '2007-03-31 10:39:23', + 'end_date' => '2007-05-15 10:39:23', + 'created' => '2007-03-18 10:39:23', + 'updated' => '2007-03-18 10:41:31' + )), + 'Category' => array( + 'id' => '1', + 'parent_id' => '0', + 'name' => 'Category 1', + 'created' => '2007-03-18 15:30:23', + 'updated' => '2007-03-18 15:32:31' + ))); + $this->assertEquals($expected, $result); + } + +/** + * testRecursiveFindAllWithLimit method + * + * @return void + */ + public function testRecursiveFindAllWithLimit() { + $this->loadFixtures('Article', 'User', 'Tag', 'ArticlesTag', 'Comment', 'Attachment'); + $TestModel = new Article(); + + $TestModel->hasMany['Comment']['limit'] = 2; + + $result = $TestModel->find('all', array( + 'conditions' => array('Article.user_id' => 1) + )); + $expected = array( + array( + 'Article' => array( + 'id' => '1', + 'user_id' => '1', + 'title' => 'First Article', + 'body' => 'First Article Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:39:23', + 'updated' => '2007-03-18 10:41:31' + ), + 'User' => array( + 'id' => '1', + 'user' => 'mariano', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', + 'updated' => '2007-03-17 01:18:31' + ), + 'Comment' => array( + array( + 'id' => '1', + 'article_id' => '1', + 'user_id' => '2', + 'comment' => 'First Comment for First Article', + 'published' => 'Y', + 'created' => '2007-03-18 10:45:23', + 'updated' => '2007-03-18 10:47:31' + ), + array( + 'id' => '2', + 'article_id' => '1', + 'user_id' => '4', + 'comment' => 'Second Comment for First Article', + 'published' => 'Y', + 'created' => '2007-03-18 10:47:23', + 'updated' => '2007-03-18 10:49:31' + ), + ), + 'Tag' => array( + array( + 'id' => '1', + 'tag' => 'tag1', + 'created' => '2007-03-18 12:22:23', + 'updated' => '2007-03-18 12:24:31' + ), + array( + 'id' => '2', + 'tag' => 'tag2', + 'created' => '2007-03-18 12:24:23', + 'updated' => '2007-03-18 12:26:31' + ))), + array( + 'Article' => array( + 'id' => '3', + 'user_id' => '1', + 'title' => 'Third Article', + 'body' => 'Third Article Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:43:23', + 'updated' => '2007-03-18 10:45:31' + ), + 'User' => array( + 'id' => '1', + 'user' => 'mariano', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', + 'updated' => '2007-03-17 01:18:31' + ), + 'Comment' => array(), + 'Tag' => array() + ) + ); + $this->assertEquals($expected, $result); + + $TestModel->hasMany['Comment']['limit'] = 1; + + $result = $TestModel->find('all', array( + 'conditions' => array('Article.user_id' => 3), + 'limit' => 1, + 'recursive' => 2 + )); + $expected = array( + array( + 'Article' => array( + 'id' => '2', + 'user_id' => '3', + 'title' => 'Second Article', + 'body' => 'Second Article Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:41:23', + 'updated' => '2007-03-18 10:43:31' + ), + 'User' => array( + 'id' => '3', + 'user' => 'larry', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:20:23', + 'updated' => '2007-03-17 01:22:31' + ), + 'Comment' => array( + array( + 'id' => '5', + 'article_id' => '2', + 'user_id' => '1', + 'comment' => 'First Comment for Second Article', + 'published' => 'Y', + 'created' => '2007-03-18 10:53:23', + 'updated' => '2007-03-18 10:55:31', + 'Article' => array( + 'id' => '2', + 'user_id' => '3', + 'title' => 'Second Article', + 'body' => 'Second Article Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:41:23', + 'updated' => '2007-03-18 10:43:31' + ), + 'User' => array( + 'id' => '1', + 'user' => 'mariano', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', + 'updated' => '2007-03-17 01:18:31' + ), + 'Attachment' => array( + 'id' => '1', + 'comment_id' => 5, + 'attachment' => 'attachment.zip', + 'created' => '2007-03-18 10:51:23', + 'updated' => '2007-03-18 10:53:31' + ) + ) + ), + 'Tag' => array( + array( + 'id' => '1', + 'tag' => 'tag1', + 'created' => '2007-03-18 12:22:23', + 'updated' => '2007-03-18 12:24:31' + ), + array( + 'id' => '3', + 'tag' => 'tag3', + 'created' => '2007-03-18 12:26:23', + 'updated' => '2007-03-18 12:28:31' + ) + ) + ) + ); + $this->assertEquals($expected, $result); + } + +/** + * Testing availability of $this->findQueryType in Model callbacks + * + * @return void + */ + public function testFindQueryTypeInCallbacks() { + $this->loadFixtures('Comment'); + $Comment = new AgainModifiedComment(); + $comments = $Comment->find('all'); + $this->assertEquals('all', $comments[0]['Comment']['querytype']); + $comments = $Comment->find('first'); + $this->assertEquals('first', $comments['Comment']['querytype']); + } + +/** + * testVirtualFields() + * + * Test correct fetching of virtual fields + * currently is not possible to do Relation.virtualField + * + * @return void + */ + public function testVirtualFields() { + $this->loadFixtures('Post', 'Author'); + $Post = ClassRegistry::init('Post'); + $Post->virtualFields = array('two' => "1 + 1"); + $result = $Post->find('first'); + $this->assertEquals(2, $result['Post']['two']); + + // SQL Server does not support operators in expressions + if (!($this->db instanceof Sqlserver)) { + $Post->Author->virtualFields = array('false' => '1 = 2'); + $result = $Post->find('first'); + $this->assertEquals(2, $result['Post']['two']); + $this->assertFalse((bool)$result['Author']['false']); + } + + $result = $Post->find('first',array('fields' => array('author_id'))); + $this->assertFalse(isset($result['Post']['two'])); + $this->assertFalse(isset($result['Author']['false'])); + + $result = $Post->find('first',array('fields' => array('author_id', 'two'))); + $this->assertEquals(2, $result['Post']['two']); + $this->assertFalse(isset($result['Author']['false'])); + + $result = $Post->find('first',array('fields' => array('two'))); + $this->assertEquals(2, $result['Post']['two']); + + $Post->id = 1; + $result = $Post->field('two'); + $this->assertEquals(2, $result); + + $result = $Post->find('first',array( + 'conditions' => array('two' => 2), + 'limit' => 1 + )); + $this->assertEquals(2, $result['Post']['two']); + + $result = $Post->find('first',array( + 'conditions' => array('two <' => 3), + 'limit' => 1 + )); + $this->assertEquals(2, $result['Post']['two']); + + $result = $Post->find('first',array( + 'conditions' => array('NOT' => array('two >' => 3)), + 'limit' => 1 + )); + $this->assertEquals(2, $result['Post']['two']); + + $dbo = $Post->getDataSource(); + $Post->virtualFields = array('other_field' => 'Post.id + 1'); + $result = $Post->find('first', array( + 'conditions' => array('other_field' => 3), + 'limit' => 1 + )); + $this->assertEquals(2, $result['Post']['id']); + + $Post->virtualFields = array('other_field' => 'Post.id + 1'); + $result = $Post->find('all', array( + 'fields' => array($dbo->calculate($Post, 'max', array('other_field'))) + )); + $this->assertEquals(4, $result[0][0]['other_field']); + + ClassRegistry::flush(); + $Writing = ClassRegistry::init(array('class' => 'Post', 'alias' => 'Writing'), 'Model'); + $Writing->virtualFields = array('two' => "1 + 1"); + $result = $Writing->find('first'); + $this->assertEquals(2, $result['Writing']['two']); + + $Post->create(); + $Post->virtualFields = array('other_field' => 'COUNT(Post.id) + 1'); + $result = $Post->field('other_field'); + $this->assertEquals(4, $result); + } + +/** + * testVirtualFieldsOrder() + * + * Test correct order on virtual fields + * + * @return void + */ + public function testVirtualFieldsOrder() { + $this->loadFixtures('Post', 'Author'); + $Post = ClassRegistry::init('Post'); + $Post->virtualFields = array('other_field' => '10 - Post.id'); + $result = $Post->find('list', array('order' => array('Post.other_field' => 'ASC'))); + $expected = array( + '3' => 'Third Post', + '2' => 'Second Post', + '1' => 'First Post' + ); + $this->assertEquals($expected, $result); + + $result = $Post->find('list', array('order' => array('Post.other_field' => 'DESC'))); + $expected = array( + '1' => 'First Post', + '2' => 'Second Post', + '3' => 'Third Post' + ); + $this->assertEquals($expected, $result); + + $Post->Author->virtualFields = array('joined' => 'Post.id * Author.id'); + $result = $Post->find('all'); + $result = Hash::extract($result, '{n}.Author.joined'); + $expected = array(1, 6, 3); + $this->assertEquals($expected, $result); + + $result = $Post->find('all', array('order' => array('Author.joined' => 'ASC'))); + $result = Hash::extract($result, '{n}.Author.joined'); + $expected = array(1, 3, 6); + $this->assertEquals($expected, $result); + + $result = $Post->find('all', array('order' => array('Author.joined' => 'DESC'))); + $result = Hash::extract($result, '{n}.Author.joined'); + $expected = array(6, 3, 1); + $this->assertEquals($expected, $result); + } + +/** + * testVirtualFieldsMysql() + * + * Test correct fetching of virtual fields + * currently is not possible to do Relation.virtualField + * + */ + public function testVirtualFieldsMysql() { + $this->skipIf(!($this->db instanceof Mysql), 'The rest of virtualFields test only compatible with Mysql.'); + + $this->loadFixtures('Post', 'Author'); + $Post = ClassRegistry::init('Post'); + + $Post->create(); + $Post->virtualFields = array( + 'low_title' => 'lower(Post.title)', + 'unique_test_field' => 'COUNT(Post.id)' + ); + + $expectation = array( + 'Post' => array( + 'low_title' => 'first post', + 'unique_test_field' => 1 + ) + ); + + $result = $Post->find('first', array( + 'fields' => array_keys($Post->virtualFields), + 'group' => array('low_title') + )); + + $this->assertEquals($expectation, $result); + + $Author = ClassRegistry::init('Author'); + $Author->virtualFields = array( + 'full_name' => 'CONCAT(Author.user, " ", Author.id)' + ); + + $result = $Author->find('first', array( + 'conditions' => array('Author.user' => 'mariano'), + 'fields' => array('Author.password', 'Author.full_name'), + 'recursive' => -1 + )); + $this->assertTrue(isset($result['Author']['full_name'])); + + $result = $Author->find('first', array( + 'conditions' => array('Author.user' => 'mariano'), + 'fields' => array('Author.full_name', 'Author.password'), + 'recursive' => -1 + )); + $this->assertTrue(isset($result['Author']['full_name'])); + } + +/** + * test that virtual fields work when they don't contain functions. + * + * @return void + */ + public function testVirtualFieldAsAString() { + $this->loadFixtures('Post', 'Author'); + $Post = new Post(); + $Post->virtualFields = array( + 'writer' => 'Author.user' + ); + $result = $Post->find('first'); + $this->assertTrue(isset($result['Post']['writer']), 'virtual field not fetched %s'); + } + +/** + * test that isVirtualField will accept both aliased and non aliased fieldnames + * + * @return void + */ + public function testIsVirtualField() { + $this->loadFixtures('Post'); + $Post = ClassRegistry::init('Post'); + $Post->virtualFields = array('other_field' => 'COUNT(Post.id) + 1'); + + $this->assertTrue($Post->isVirtualField('other_field')); + $this->assertTrue($Post->isVirtualField('Post.other_field')); + $this->assertFalse($Post->isVirtualField('Comment.other_field'), 'Other models should not match.'); + $this->assertFalse($Post->isVirtualField('id')); + $this->assertFalse($Post->isVirtualField('Post.id')); + $this->assertFalse($Post->isVirtualField(array())); + } + +/** + * test that getting virtual fields works with and without model alias attached + * + * @return void + */ + public function testGetVirtualField() { + $this->loadFixtures('Post'); + $Post = ClassRegistry::init('Post'); + $Post->virtualFields = array('other_field' => 'COUNT(Post.id) + 1'); + + $this->assertEquals($Post->getVirtualField('other_field'), $Post->virtualFields['other_field']); + $this->assertEquals($Post->getVirtualField('Post.other_field'), $Post->virtualFields['other_field']); + } + +/** + * test that checks for error when NOT condition passed in key and a 1 element array value + * + * @return void + */ + public function testNotInArrayWithOneValue() { + $this->loadFixtures('Article'); + $Article = new Article(); + $Article->recursive = -1; + + $result = $Article->find( + 'all', + array( + 'conditions' => array( + 'Article.id NOT' => array(1) + ) + ) + ); + $this->assertTrue(is_array($result) && !empty($result)); + } + +/** + * test custom find method + * + * @return void + */ + public function testfindCustom() { + $this->loadFixtures('Article'); + $Article = new CustomArticle(); + $data = array('user_id' => 3, 'title' => 'Fourth Article', 'body' => 'Article Body, unpublished', 'published' => 'N'); + $Article->create($data); + $Article->save(null, false); + $this->assertEquals(4, $Article->id); + + $result = $Article->find('published'); + $this->assertEquals(3, count($result)); + + $result = $Article->find('unPublished'); + $this->assertEquals(1, count($result)); + } + +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/ModelTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/ModelTest.php new file mode 100644 index 0000000..e489d5b --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/ModelTest.php @@ -0,0 +1,47 @@ +addTestFile(CORE_TEST_CASES . DS . 'Model' . DS . 'Validator' . DS . 'CakeValidationSetTest.php'); + $suite->addTestFile(CORE_TEST_CASES . DS . 'Model' . DS . 'Validator' . DS . 'CakeValidationRuleTest.php'); + $suite->addTestFile(CORE_TEST_CASES . DS . 'Model' . DS . 'ModelReadTest.php'); + $suite->addTestFile(CORE_TEST_CASES . DS . 'Model' . DS . 'ModelWriteTest.php'); + $suite->addTestFile(CORE_TEST_CASES . DS . 'Model' . DS . 'ModelDeleteTest.php'); + $suite->addTestFile(CORE_TEST_CASES . DS . 'Model' . DS . 'ModelValidationTest.php'); + $suite->addTestFile(CORE_TEST_CASES . DS . 'Model' . DS . 'ModelIntegrationTest.php'); + $suite->addTestFile(CORE_TEST_CASES . DS . 'Model' . DS . 'ModelCrossSchemaHabtmTest.php'); + return $suite; + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/ModelTestBase.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/ModelTestBase.php new file mode 100644 index 0000000..371e27b --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/ModelTestBase.php @@ -0,0 +1,96 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Model + * @since CakePHP(tm) v 1.2.0.4206 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ + +App::uses('Model', 'Model'); +App::uses('AppModel', 'Model'); +require_once dirname(__FILE__) . DS . 'models.php'; + +/** + * ModelBaseTest + * + * @package Cake.Test.Case.Model + */ +abstract class BaseModelTest extends CakeTestCase { + +/** + * autoFixtures property + * + * @var bool false + */ + public $autoFixtures = false; + +/** + * Whether backup global state for each test method or not + * + * @var bool false + */ + public $backupGlobals = false; + +/** + * fixtures property + * + * @var array + */ + public $fixtures = array( + 'core.category', 'core.category_thread', 'core.user', 'core.my_category', 'core.my_product', + 'core.my_user', 'core.my_categories_my_users', 'core.my_categories_my_products', + 'core.article', 'core.featured', 'core.article_featureds_tags', 'core.article_featured', + 'core.numeric_article', 'core.tag', 'core.articles_tag', 'core.comment', + 'core.attachment', 'core.apple', 'core.sample', 'core.another_article', 'core.item', + 'core.advertisement', 'core.home', 'core.post', 'core.author', 'core.bid', 'core.portfolio', + 'core.product', 'core.project', 'core.thread', 'core.message', 'core.items_portfolio', + 'core.syfile', 'core.image', 'core.device_type', 'core.device_type_category', + 'core.feature_set', 'core.exterior_type_category', 'core.document', 'core.device', + 'core.document_directory', 'core.primary_model', 'core.secondary_model', 'core.something', + 'core.something_else', 'core.join_thing', 'core.join_a', 'core.join_b', 'core.join_c', + 'core.join_a_b', 'core.join_a_c', 'core.uuid', 'core.data_test', 'core.posts_tag', + 'core.the_paper_monkies', 'core.person', 'core.underscore_field', 'core.node', + 'core.dependency', 'core.story', 'core.stories_tag', 'core.cd', 'core.book', 'core.basket', + 'core.overall_favorite', 'core.account', 'core.content', 'core.content_account', + 'core.film_file', 'core.test_plugin_article', 'core.test_plugin_comment', 'core.uuiditem', + 'core.counter_cache_user', 'core.counter_cache_post', + 'core.counter_cache_user_nonstandard_primary_key', + 'core.counter_cache_post_nonstandard_primary_key', 'core.uuidportfolio', + 'core.uuiditems_uuidportfolio', 'core.uuiditems_uuidportfolio_numericid', 'core.fruit', + 'core.fruits_uuid_tag', 'core.uuid_tag', 'core.product_update_all', 'core.group_update_all', + 'core.player', 'core.guild', 'core.guilds_player', 'core.armor', 'core.armors_player', + 'core.bidding', 'core.bidding_message', 'core.site', 'core.domain', 'core.domains_site', + ); + +/** + * setUp method + * + * @return void + */ + public function setUp() { + parent::setUp(); + $this->debug = Configure::read('debug'); + } + +/** + * tearDown method + * + * @return void + */ + public function tearDown() { + parent::tearDown(); + Configure::write('debug', $this->debug); + ClassRegistry::flush(); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/ModelValidationTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/ModelValidationTest.php new file mode 100644 index 0000000..713e578 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/ModelValidationTest.php @@ -0,0 +1,2201 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Model + * @since CakePHP(tm) v 1.2.0.4206 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ +require_once dirname(__FILE__) . DS . 'ModelTestBase.php'; + +/** + * ModelValidationTest + * + * @package Cake.Test.Case.Model + */ +class ModelValidationTest extends BaseModelTest { + +/** + * Tests validation parameter order in custom validation methods + * + * @return void + */ + public function testValidationParams() { + $TestModel = new ValidationTest1(); + $TestModel->validate['title'] = array( + 'rule' => 'customValidatorWithParams', + 'required' => true + ); + $TestModel->create(array('title' => 'foo')); + $TestModel->invalidFields(); + + $expected = array( + 'data' => array( + 'title' => 'foo' + ), + 'validator' => array( + 'rule' => 'customValidatorWithParams', + 'on' => null, + 'last' => true, + 'allowEmpty' => false, + 'required' => true, + 'message' => null + ), + 'or' => true, + 'ignoreOnSame' => 'id' + ); + $this->assertEquals($expected, $TestModel->validatorParams); + + $TestModel->validate['title'] = array( + 'rule' => 'customValidatorWithMessage', + 'required' => true + ); + $expected = array( + 'title' => array('This field will *never* validate! Muhahaha!') + ); + + $this->assertEquals($expected, $TestModel->invalidFields()); + + $TestModel->validate['title'] = array( + 'rule' => array('customValidatorWithSixParams', 'one', 'two', null, 'four'), + 'required' => true + ); + $TestModel->create(array('title' => 'foo')); + $TestModel->invalidFields(); + $expected = array( + 'data' => array( + 'title' => 'foo' + ), + 'one' => 'one', + 'two' => 'two', + 'three' => null, + 'four' => 'four', + 'five' => array( + 'rule' => array(1 => 'one', 2 => 'two', 3 => null, 4 => 'four'), + 'on' => null, + 'last' => true, + 'allowEmpty' => false, + 'required' => true, + 'message' => null + ), + 'six' => 6 + ); + $this->assertEquals($expected, $TestModel->validatorParams); + + $TestModel->validate['title'] = array( + 'rule' => array('customValidatorWithSixParams', 'one', array('two'), null, 'four', array('five' => 5)), + 'required' => true + ); + $TestModel->create(array('title' => 'foo')); + $TestModel->invalidFields(); + $expected = array( + 'data' => array( + 'title' => 'foo' + ), + 'one' => 'one', + 'two' => array('two'), + 'three' => null, + 'four' => 'four', + 'five' => array('five' => 5), + 'six' => array( + 'rule' => array(1 => 'one', 2 => array('two'), 3 => null, 4 => 'four', 5 => array('five' => 5)), + 'on' => null, + 'last' => true, + 'allowEmpty' => false, + 'required' => true, + 'message' => null + ) + ); + $this->assertEquals($expected, $TestModel->validatorParams); + } + +/** + * Tests validation parameter fieldList in invalidFields + * + * @return void + */ + public function testInvalidFieldsWithFieldListParams() { + $TestModel = new ValidationTest1(); + $TestModel->validate = $validate = array( + 'title' => array( + 'rule' => 'alphaNumeric', + 'required' => true + ), + 'name' => array( + 'rule' => 'alphaNumeric', + 'required' => true + )); + $TestModel->set(array('title' => '$$', 'name' => '##')); + $TestModel->invalidFields(array('fieldList' => array('title'))); + $expected = array( + 'title' => array('This field cannot be left blank') + ); + $this->assertEquals($expected, $TestModel->validationErrors); + $TestModel->validationErrors = array(); + + $TestModel->invalidFields(array('fieldList' => array('name'))); + $expected = array( + 'name' => array('This field cannot be left blank') + ); + $this->assertEquals($expected, $TestModel->validationErrors); + $TestModel->validationErrors = array(); + + $TestModel->invalidFields(array('fieldList' => array('name', 'title'))); + $expected = array( + 'name' => array('This field cannot be left blank'), + 'title' => array('This field cannot be left blank') + ); + $this->assertEquals($expected, $TestModel->validationErrors); + $TestModel->validationErrors = array(); + + $TestModel->whitelist = array('name'); + $TestModel->invalidFields(); + $expected = array('name' => array('This field cannot be left blank')); + $this->assertEquals($expected, $TestModel->validationErrors); + + $this->assertEquals($TestModel->validate, $validate); + } + +/** + * Test that invalidFields() integrates well with save(). And that fieldList can be an empty type. + * + * @return void + */ + public function testInvalidFieldsWhitelist() { + $TestModel = new ValidationTest1(); + $TestModel->validate = array( + 'title' => array( + 'rule' => 'alphaNumeric', + 'required' => true + ), + 'name' => array( + 'rule' => 'alphaNumeric', + 'required' => true + )); + + $TestModel->whitelist = array('name'); + $TestModel->save(array('name' => '#$$#', 'title' => '$$$$')); + + $expected = array('name' => array('This field cannot be left blank')); + $this->assertEquals($expected, $TestModel->validationErrors); + } + +/** + * testValidates method + * + * @return void + */ + public function testValidates() { + $TestModel = new TestValidate(); + + $TestModel->validate = array( + 'user_id' => 'numeric', + 'title' => array('allowEmpty' => false, 'rule' => 'notEmpty'), + 'body' => 'notEmpty' + ); + + $data = array('TestValidate' => array( + 'user_id' => '1', + 'title' => '', + 'body' => 'body' + )); + $result = $TestModel->create($data); + $this->assertEquals($data, $result); + $result = $TestModel->validates(); + $this->assertFalse($result); + + $data = array('TestValidate' => array( + 'user_id' => '1', + 'title' => 'title', + 'body' => 'body' + )); + $result = $TestModel->create($data) && $TestModel->validates(); + $this->assertTrue($result); + + $data = array('TestValidate' => array( + 'user_id' => '1', + 'title' => '0', + 'body' => 'body' + )); + $result = $TestModel->create($data); + $this->assertEquals($data, $result); + $result = $TestModel->validates(); + $this->assertTrue($result); + + $data = array('TestValidate' => array( + 'user_id' => '1', + 'title' => 0, + 'body' => 'body' + )); + $result = $TestModel->create($data); + $this->assertEquals($data, $result); + $result = $TestModel->validates(); + $this->assertTrue($result); + + $TestModel->validate['modified'] = array('allowEmpty' => true, 'rule' => 'date'); + + $data = array('TestValidate' => array( + 'user_id' => '1', + 'title' => 0, + 'body' => 'body', + 'modified' => '' + )); + $result = $TestModel->create($data); + $this->assertEquals($data, $result); + $result = $TestModel->validates(); + $this->assertTrue($result); + + $data = array('TestValidate' => array( + 'user_id' => '1', + 'title' => 0, + 'body' => 'body', + 'modified' => '2007-05-01' + )); + $result = $TestModel->create($data); + $this->assertEquals($data, $result); + $result = $TestModel->validates(); + $this->assertTrue($result); + + $data = array('TestValidate' => array( + 'user_id' => '1', + 'title' => 0, + 'body' => 'body', + 'modified' => 'invalid-date-here' + )); + $result = $TestModel->create($data); + $this->assertEquals($data, $result); + $result = $TestModel->validates(); + $this->assertFalse($result); + + $data = array('TestValidate' => array( + 'user_id' => '1', + 'title' => 0, + 'body' => 'body', + 'modified' => 0 + )); + $result = $TestModel->create($data); + $this->assertEquals($data, $result); + $result = $TestModel->validates(); + $this->assertFalse($result); + + $data = array('TestValidate' => array( + 'user_id' => '1', + 'title' => 0, + 'body' => 'body', + 'modified' => '0' + )); + $result = $TestModel->create($data); + $this->assertEquals($data, $result); + $result = $TestModel->validates(); + $this->assertFalse($result); + + $TestModel->validate['modified'] = array('allowEmpty' => false, 'rule' => 'date'); + + $data = array('TestValidate' => array('modified' => null)); + $result = $TestModel->create($data); + $this->assertEquals($data, $result); + $result = $TestModel->validates(); + $this->assertFalse($result); + + $data = array('TestValidate' => array('modified' => false)); + $result = $TestModel->create($data); + $this->assertEquals($data, $result); + $result = $TestModel->validates(); + $this->assertFalse($result); + + $data = array('TestValidate' => array('modified' => '')); + $result = $TestModel->create($data); + $this->assertEquals($data, $result); + $result = $TestModel->validates(); + $this->assertFalse($result); + + $data = array('TestValidate' => array( + 'modified' => '2007-05-01' + )); + $result = $TestModel->create($data); + $this->assertEquals($data, $result); + $result = $TestModel->validates(); + $this->assertTrue($result); + + $TestModel->validate['slug'] = array('allowEmpty' => false, 'rule' => array('maxLength', 45)); + + $data = array('TestValidate' => array( + 'user_id' => '1', + 'title' => 0, + 'body' => 'body', + 'slug' => '' + )); + $result = $TestModel->create($data); + $this->assertEquals($data, $result); + $result = $TestModel->validates(); + $this->assertFalse($result); + + $data = array('TestValidate' => array( + 'user_id' => '1', + 'title' => 0, + 'body' => 'body', + 'slug' => 'slug-right-here' + )); + $result = $TestModel->create($data); + $this->assertEquals($data, $result); + $result = $TestModel->validates(); + $this->assertTrue($result); + + $data = array('TestValidate' => array( + 'user_id' => '1', + 'title' => 0, + 'body' => 'body', + 'slug' => 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz' + )); + $result = $TestModel->create($data); + $this->assertEquals($data, $result); + $result = $TestModel->validates(); + $this->assertFalse($result); + + $TestModel->validate = array( + 'number' => array( + 'rule' => 'validateNumber', + 'min' => 3, + 'max' => 5 + ), + 'title' => array( + 'allowEmpty' => false, + 'rule' => 'notEmpty' + )); + + $data = array('TestValidate' => array( + 'title' => 'title', + 'number' => '0' + )); + $result = $TestModel->create($data); + $this->assertEquals($data, $result); + $result = $TestModel->validates(); + $this->assertFalse($result); + + $data = array('TestValidate' => array( + 'title' => 'title', + 'number' => 0 + )); + $result = $TestModel->create($data); + $this->assertEquals($data, $result); + $result = $TestModel->validates(); + $this->assertFalse($result); + + $data = array('TestValidate' => array( + 'title' => 'title', + 'number' => '3' + )); + $result = $TestModel->create($data); + $this->assertEquals($data, $result); + $result = $TestModel->validates(); + $this->assertTrue($result); + + $data = array('TestValidate' => array( + 'title' => 'title', + 'number' => 3 + )); + $result = $TestModel->create($data); + $this->assertEquals($data, $result); + $result = $TestModel->validates(); + $this->assertTrue($result); + + $TestModel->validate = array( + 'number' => array( + 'rule' => 'validateNumber', + 'min' => 5, + 'max' => 10 + ), + 'title' => array( + 'allowEmpty' => false, + 'rule' => 'notEmpty' + )); + + $data = array('TestValidate' => array( + 'title' => 'title', + 'number' => '3' + )); + $result = $TestModel->create($data); + $this->assertEquals($data, $result); + $result = $TestModel->validates(); + $this->assertFalse($result); + + $data = array('TestValidate' => array( + 'title' => 'title', + 'number' => 3 + )); + $result = $TestModel->create($data); + $this->assertEquals($data, $result); + $result = $TestModel->validates(); + $this->assertFalse($result); + + $TestModel->validate = array( + 'title' => array( + 'allowEmpty' => false, + 'rule' => 'validateTitle' + )); + + $data = array('TestValidate' => array('title' => '')); + $result = $TestModel->create($data); + $this->assertEquals($data, $result); + $result = $TestModel->validates(); + $this->assertFalse($result); + + $data = array('TestValidate' => array('title' => 'new title')); + $result = $TestModel->create($data); + $this->assertEquals($data, $result); + $result = $TestModel->validates(); + $this->assertFalse($result); + + $data = array('TestValidate' => array('title' => 'title-new')); + $result = $TestModel->create($data); + $this->assertEquals($data, $result); + $result = $TestModel->validates(); + $this->assertTrue($result); + + $TestModel->validate = array('title' => array( + 'allowEmpty' => true, + 'rule' => 'validateTitle' + )); + $data = array('TestValidate' => array('title' => '')); + $result = $TestModel->create($data); + $this->assertEquals($data, $result); + $result = $TestModel->validates(); + $this->assertTrue($result); + + $TestModel->validate = array( + 'title' => array( + 'length' => array( + 'allowEmpty' => true, + 'rule' => array('maxLength', 10) + ))); + $data = array('TestValidate' => array('title' => '')); + $result = $TestModel->create($data); + $this->assertEquals($data, $result); + $result = $TestModel->validates(); + $this->assertTrue($result); + + $TestModel->validate = array( + 'title' => array( + 'rule' => array('userDefined', 'Article', 'titleDuplicate') + )); + $data = array('TestValidate' => array('title' => 'My Article Title')); + $result = $TestModel->create($data); + $this->assertEquals($data, $result); + $result = $TestModel->validates(); + $this->assertFalse($result); + + $data = array('TestValidate' => array( + 'title' => 'My Article With a Different Title' + )); + $result = $TestModel->create($data); + $this->assertEquals($data, $result); + $result = $TestModel->validates(); + $this->assertTrue($result); + + $TestModel->validate = array( + 'title' => array( + 'tooShort' => array('rule' => array('minLength', 50)), + 'onlyLetters' => array('rule' => '/^[a-z]+$/i') + ), + ); + $data = array('TestValidate' => array( + 'title' => 'I am a short string' + )); + $TestModel->create($data); + $result = $TestModel->validates(); + $this->assertFalse($result); + $result = $TestModel->validationErrors; + $expected = array( + 'title' => array('tooShort') + ); + $this->assertEquals($expected, $result); + + $TestModel->validate = array( + 'title' => array( + 'tooShort' => array( + 'rule' => array('minLength', 50), + 'last' => false + ), + 'onlyLetters' => array('rule' => '/^[a-z]+$/i') + ), + ); + $data = array('TestValidate' => array( + 'title' => 'I am a short string' + )); + $TestModel->create($data); + $result = $TestModel->validates(); + $this->assertFalse($result); + $result = $TestModel->validationErrors; + $expected = array( + 'title' => array('tooShort', 'onlyLetters') + ); + $this->assertEquals($expected, $result); + $result = $TestModel->validationErrors; + $this->assertEquals($expected, $result); + } + +/** + * test that validates() checks all the 'with' associations as well for validation + * as this can cause partial/wrong data insertion. + * + * @return void + */ + public function testValidatesWithAssociations() { + $this->loadFixtures('Something', 'SomethingElse', 'JoinThing'); + $data = array( + 'Something' => array( + 'id' => 5, + 'title' => 'Extra Fields', + 'body' => 'Extra Fields Body', + 'published' => '1' + ), + 'SomethingElse' => array( + array('something_else_id' => 1, 'doomed' => '') + ) + ); + + $Something = new Something(); + $JoinThing = $Something->JoinThing; + + $JoinThing->validate = array('doomed' => array('rule' => 'notEmpty')); + + $expectedError = array('doomed' => array('This field cannot be left blank')); + + $Something->create(); + $result = $Something->save($data); + $this->assertFalse($result, 'Save occurred even when with models failed. %s'); + $this->assertEquals($expectedError, $JoinThing->validationErrors); + $count = $Something->find('count', array('conditions' => array('Something.id' => $data['Something']['id']))); + $this->assertSame($count, 0); + + $data = array( + 'Something' => array( + 'id' => 5, + 'title' => 'Extra Fields', + 'body' => 'Extra Fields Body', + 'published' => '1' + ), + 'SomethingElse' => array( + array('something_else_id' => 1, 'doomed' => 1), + array('something_else_id' => 1, 'doomed' => '') + ) + ); + $Something->create(); + $result = $Something->save($data); + $this->assertFalse($result, 'Save occurred even when with models failed. %s'); + + $joinRecords = $JoinThing->find('count', array( + 'conditions' => array('JoinThing.something_id' => $data['Something']['id']) + )); + $this->assertEquals(0, $joinRecords, 'Records were saved on the join table. %s'); + } + +/** + * test that saveAll and with models with validation interact well + * + * @return void + */ + public function testValidatesWithModelsAndSaveAll() { + $this->loadFixtures('Something', 'SomethingElse', 'JoinThing'); + $data = array( + 'Something' => array( + 'id' => 5, + 'title' => 'Extra Fields', + 'body' => 'Extra Fields Body', + 'published' => '1' + ), + 'SomethingElse' => array( + array('something_else_id' => 1, 'doomed' => '') + ) + ); + $Something = new Something(); + $JoinThing = $Something->JoinThing; + + $JoinThing->validate = array('doomed' => array('rule' => 'notEmpty')); + $expectedError = array('doomed' => array('This field cannot be left blank')); + + $Something->create(); + $result = $Something->saveAll($data, array('validate' => 'only')); + $this->assertFalse($result); + $result = $Something->validateAssociated($data); + $this->assertFalse($result); + $this->assertEquals($expectedError, $JoinThing->validationErrors); + $result = $Something->validator()->validateAssociated($data); + $this->assertFalse($result); + + $Something->create(); + $result = $Something->saveAll($data, array('validate' => 'first')); + $this->assertFalse($result); + $this->assertEquals($expectedError, $JoinThing->validationErrors); + + $count = $Something->find('count', array('conditions' => array('Something.id' => $data['Something']['id']))); + $this->assertSame($count, 0); + + $joinRecords = $JoinThing->find('count', array( + 'conditions' => array('JoinThing.something_id' => $data['Something']['id']) + )); + $this->assertEquals(0, $joinRecords, 'Records were saved on the join table. %s'); + } + +/** + * test that saveAll and with models at initial insert (no id has set yet) + * with validation interact well + * + * @return void + */ + public function testValidatesWithModelsAndSaveAllWithoutId() { + $this->loadFixtures('Post', 'Author'); + + $data = array( + 'Author' => array( + 'name' => 'Foo Bar', + ), + 'Post' => array( + array('title' => 'Hello'), + array('title' => 'World'), + ) + ); + $Author = new Author(); + $Post = $Author->Post; + + $Post->validate = array('author_id' => array('rule' => 'numeric')); + + $Author->create(); + $result = $Author->saveAll($data, array('validate' => 'only')); + $this->assertTrue($result); + $result = $Author->validateAssociated($data); + $this->assertTrue($result); + $this->assertTrue($result); + + $Author->create(); + $result = $Author->saveAll($data, array('validate' => 'first')); + $this->assertTrue($result); + $this->assertFalse(is_null($Author->id)); + + $id = $Author->id; + $count = $Author->find('count', array('conditions' => array('Author.id' => $id))); + $this->assertSame($count, 1); + + $count = $Post->find('count', array( + 'conditions' => array('Post.author_id' => $id) + )); + $this->assertEquals($count, count($data['Post'])); + } + +/** + * Test that missing validation methods trigger errors in development mode. + * Helps to make development easier. + * + * @expectedException PHPUnit_Framework_Error + * @return void + */ + public function testMissingValidationErrorTriggering() { + Configure::write('debug', 2); + + $TestModel = new ValidationTest1(); + $TestModel->create(array('title' => 'foo')); + $TestModel->validate = array( + 'title' => array( + 'rule' => array('thisOneBringsThePain'), + 'required' => true + ) + ); + $TestModel->invalidFields(array('fieldList' => array('title'))); + } + +/** + * Test that missing validation methods does not trigger errors in production mode. + * + * @return void + */ + public function testMissingValidationErrorNoTriggering() { + Configure::write('debug', 0); + $TestModel = new ValidationTest1(); + $TestModel->create(array('title' => 'foo')); + $TestModel->validate = array( + 'title' => array( + 'rule' => array('thisOneBringsThePain'), + 'required' => true + ) + ); + $TestModel->invalidFields(array('fieldList' => array('title'))); + $this->assertEquals(array(), $TestModel->validationErrors); + } + +/** + * Test placeholder replacement when validation message is an array + * + * @return void + */ + public function testValidationMessageAsArray() { + $TestModel = new ValidationTest1(); + $TestModel->validate = array( + 'title' => array( + 'minLength' => array( + 'rule' => array('minLength', 6), + 'required' => true, + 'message' => 'Minimum length allowed is %d chars', + 'last' => false + ), + 'between' => array( + 'rule' => array('between', 5, 15), + 'message' => array('You may enter up to %s chars (minimum is %s chars)', 14, 6) + ) + ) + ); + + $TestModel->create(); + $expected = array( + 'title' => array( + 'Minimum length allowed is 6 chars', + ) + ); + $TestModel->invalidFields(); + $this->assertEquals($expected, $TestModel->validationErrors); + + $TestModel->create(array('title' => 'foo')); + $expected = array( + 'title' => array( + 'Minimum length allowed is 6 chars', + 'You may enter up to 14 chars (minimum is 6 chars)' + ) + ); + $TestModel->invalidFields(); + $this->assertEquals($expected, $TestModel->validationErrors); + } + +/** + * Test validation message translation + * + * @return void + */ + public function testValidationMessageTranslation() { + $lang = Configure::read('Config.language'); + Configure::write('Config.language', 'en'); + App::build(array( + 'Locale' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Locale' . DS), + ), App::RESET); + + $TestModel = new ValidationTest1(); + $TestModel->validationDomain = 'validation_messages'; + $TestModel->validate = array( + 'title' => array( + array( + 'rule' => array('customValidationMethod', 'arg1'), + 'required' => true, + 'message' => 'Validation failed: %s' + ) + ) + ); + + $TestModel->create(); + $expected = array( + 'title' => array( + 'Translated validation failed: Translated arg1', + ) + ); + $TestModel->invalidFields(); + $this->assertEquals($expected, $TestModel->validationErrors); + + $TestModel->validationDomain = 'default'; + Configure::write('Config.language', $lang); + App::build(); + } + +/** + * Test for 'on' => [create|update] in validation rules. + * + * @return void + */ + public function testStateValidation() { + $this->loadFixtures('Article'); + $Article = new Article(); + + $data = array( + 'Article' => array( + 'title' => '', + 'body' => 'Extra Fields Body', + 'published' => '1' + ) + ); + + $Article->validate = array( + 'title' => array( + 'notempty' => array( + 'rule' => 'notEmpty', + 'on' => 'create' + ) + ) + ); + + $Article->create($data); + $this->assertFalse($Article->validates()); + + $Article->save(null, array('validate' => false)); + $data['Article']['id'] = $Article->id; + $Article->set($data); + $this->assertTrue($Article->validates()); + + unset($data['Article']['id']); + $Article->validate = array( + 'title' => array( + 'notempty' => array( + 'rule' => 'notEmpty', + 'on' => 'update' + ) + ) + ); + + $Article->create($data); + $this->assertTrue($Article->validates()); + + $Article->save(null, array('validate' => false)); + $data['Article']['id'] = $Article->id; + $Article->set($data); + $this->assertFalse($Article->validates()); + } + +/** + * Test for 'required' => [create|update] in validation rules. + * + * @return void + */ + public function testStateRequiredValidation() { + $this->loadFixtures('Article'); + $Article = new Article(); + + // no title field present + $data = array( + 'Article' => array( + 'body' => 'Extra Fields Body', + 'published' => '1' + ) + ); + + $Article->validate = array( + 'title' => array( + 'notempty' => array( + 'rule' => 'notEmpty', + 'required' => 'create' + ) + ) + ); + + $Article->create($data); + $this->assertFalse($Article->validates()); + + $Article->save(null, array('validate' => false)); + $data['Article']['id'] = $Article->id; + $Article->set($data); + $this->assertTrue($Article->validates()); + + unset($data['Article']['id']); + $Article->validate = array( + 'title' => array( + 'notempty' => array( + 'rule' => 'notEmpty', + 'required' => 'update' + ) + ) + ); + + $Article->create($data); + $this->assertTrue($Article->validates()); + + $Article->save(null, array('validate' => false)); + $data['Article']['id'] = $Article->id; + $Article->set($data); + $this->assertFalse($Article->validates()); + } + +/** + * Test that 'required' and 'on' are not conflicting + * + * @return void + */ + public function testOnRequiredConflictValidation() { + $this->loadFixtures('Article'); + $Article = new Article(); + + // no title field present + $data = array( + 'Article' => array( + 'body' => 'Extra Fields Body', + 'published' => '1' + ) + ); + + $Article->validate = array( + 'title' => array( + 'notempty' => array( + 'rule' => 'notEmpty', + 'required' => 'create', + 'on' => 'create' + ) + ) + ); + + $Article->create($data); + $this->assertFalse($Article->validates()); + + $Article->validate = array( + 'title' => array( + 'notempty' => array( + 'rule' => 'notEmpty', + 'required' => 'update', + 'on' => 'create' + ) + ) + ); + + $Article->create($data); + $this->assertTrue($Article->validates()); + + $Article->validate = array( + 'title' => array( + 'notempty' => array( + 'rule' => 'notEmpty', + 'required' => 'create', + 'on' => 'update' + ) + ) + ); + + $Article->create($data); + $this->assertTrue($Article->validates()); + + $Article->validate = array( + 'title' => array( + 'notempty' => array( + 'rule' => 'notEmpty', + 'required' => 'update', + 'on' => 'update' + ) + ) + ); + + $Article->create($data); + $this->assertTrue($Article->validates()); + + $Article->validate = array( + 'title' => array( + 'notempty' => array( + 'rule' => 'notEmpty', + 'required' => 'create', + 'on' => 'create' + ) + ) + ); + + $Article->save(null, array('validate' => false)); + $data['Article']['id'] = $Article->id; + $Article->set($data); + $this->assertTrue($Article->validates()); + + $Article->validate = array( + 'title' => array( + 'notempty' => array( + 'rule' => 'notEmpty', + 'required' => 'update', + 'on' => 'create' + ) + ) + ); + + $Article->set($data); + $this->assertTrue($Article->validates()); + + $Article->validate = array( + 'title' => array( + 'notempty' => array( + 'rule' => 'notEmpty', + 'required' => 'create', + 'on' => 'update' + ) + ) + ); + + $Article->set($data); + $this->assertTrue($Article->validates()); + + $Article->validate = array( + 'title' => array( + 'notempty' => array( + 'rule' => 'notEmpty', + 'required' => 'update', + 'on' => 'update' + ) + ) + ); + + $Article->set($data); + $this->assertFalse($Article->validates()); + } + +/** + * testSaveAllDeepValidateOnly + * tests the validate methods with deeper recursive data + * + * @return void + */ + public function testSaveAllDeepValidateOnly() { + $this->loadFixtures('Article', 'Comment', 'User', 'Attachment'); + $TestModel = new Article(); + $TestModel->hasMany['Comment']['order'] = array('Comment.created' => 'ASC'); + $TestModel->hasAndBelongsToMany = array(); + $TestModel->Comment->Attachment->validate['attachment'] = 'notEmpty'; + $TestModel->Comment->validate['comment'] = 'notEmpty'; + + $data = array( + 'Article' => array('id' => 2), + 'Comment' => array( + array('comment' => 'First new comment', 'published' => 'Y', 'User' => array('user' => 'newuser', 'password' => 'newuserpass')), + array('comment' => 'Second new comment', 'published' => 'Y', 'user_id' => 2) + ) + ); + $result = $TestModel->saveAll($data, array('validate' => 'only', 'deep' => true)); + $this->assertTrue($result); + $result = $TestModel->validateAssociated($data, array('deep' => true)); + $this->assertTrue($result); + + $data = array( + 'Article' => array('id' => 2), + 'Comment' => array( + array('comment' => 'First new comment', 'published' => 'Y', 'User' => array('user' => '', 'password' => 'newuserpass')), + array('comment' => 'Second new comment', 'published' => 'Y', 'user_id' => 2) + ) + ); + $result = $TestModel->saveAll($data, array('validate' => 'only', 'deep' => true)); + $this->assertFalse($result); + $result = $TestModel->validateAssociated($data, array('deep' => true)); + $this->assertFalse($result); + + $data = array( + 'Article' => array('id' => 2), + 'Comment' => array( + array('comment' => 'First new comment', 'published' => 'Y', 'User' => array('user' => 'newuser', 'password' => 'newuserpass')), + array('comment' => 'Second new comment', 'published' => 'Y', 'user_id' => 2) + ) + ); + $expected = array( + 'Article' => true, + 'Comment' => array( + true, + true + ) + ); + $result = $TestModel->saveAll($data, array('validate' => 'only', 'atomic' => false, 'deep' => true)); + $this->assertSame($expected, $result); + $result = $TestModel->validateAssociated($data, array('atomic' => false, 'deep' => true)); + $this->assertSame($expected, $result); + + $data = array( + 'Article' => array('id' => 2), + 'Comment' => array( + array('comment' => 'First new comment', 'published' => 'Y', 'User' => array('user' => '', 'password' => 'newuserpass')), + array('comment' => 'Second new comment', 'published' => 'Y', 'user_id' => 2) + ) + ); + $expected = array( + 'Article' => true, + 'Comment' => array( + false, + true + ) + ); + $result = $TestModel->saveAll($data, array('validate' => 'only', 'atomic' => false, 'deep' => true)); + $this->assertSame($expected, $result); + $result = $TestModel->validateAssociated($data, array('atomic' => false, 'deep' => true)); + $this->assertSame($expected, $result); + + $data = array( + 'Article' => array('id' => 2), + 'Comment' => array( + array('comment' => 'Third new comment', 'published' => 'Y', 'user_id' => 5), + array('comment' => 'Fourth new comment', 'published' => 'Y', 'user_id' => 2, 'Attachment' => array('attachment' => 'deepsaved')) + ) + ); + $result = $TestModel->saveAll($data, array('validate' => 'only', 'deep' => true)); + $this->assertTrue($result); + $result = $TestModel->validateAssociated($data, array('deep' => true)); + $this->assertTrue($result); + + $data = array( + 'Article' => array('id' => 2), + 'Comment' => array( + array('comment' => 'Third new comment', 'published' => 'Y', 'user_id' => 5), + array('comment' => 'Fourth new comment', 'published' => 'Y', 'user_id' => 2, 'Attachment' => array('attachment' => '')) + ) + ); + $result = $TestModel->saveAll($data, array('validate' => 'only', 'deep' => true)); + $this->assertFalse($result); + $result = $TestModel->validateAssociated($data, array('deep' => true)); + $this->assertFalse($result); + + $data = array( + 'Article' => array('id' => 2), + 'Comment' => array( + array('comment' => 'Third new comment', 'published' => 'Y', 'user_id' => 5), + array('comment' => 'Fourth new comment', 'published' => 'Y', 'user_id' => 2, 'Attachment' => array('attachment' => 'deepsave')) + ) + ); + $expected = array( + 'Article' => true, + 'Comment' => array( + true, + true + ) + ); + $result = $TestModel->saveAll($data, array('validate' => 'only', 'atomic' => false, 'deep' => true)); + $this->assertSame($expected, $result); + $result = $TestModel->validateAssociated($data, array('atomic' => false, 'deep' => true)); + $this->assertSame($expected, $result); + + $data = array( + 'Article' => array('id' => 2), + 'Comment' => array( + array('comment' => 'Third new comment', 'published' => 'Y', 'user_id' => 5), + array('comment' => 'Fourth new comment', 'published' => 'Y', 'user_id' => 2, 'Attachment' => array('attachment' => '')) + ) + ); + $expected = array( + 'Article' => true, + 'Comment' => array( + true, + false + ) + ); + $result = $TestModel->saveAll($data, array('validate' => 'only', 'atomic' => false, 'deep' => true)); + $this->assertSame($expected, $result); + $result = $TestModel->validateAssociated($data, array('atomic' => false, 'deep' => true)); + $this->assertSame($expected, $result); + + $expected = array( + 'Comment' => array( + 1 => array( + 'Attachment' => array( + 'attachment' => array('This field cannot be left blank') + ) + ) + ) + ); + $result = $TestModel->validationErrors; + $this->assertSame($expected, $result); + + $data = array( + 'Attachment' => array( + 'attachment' => 'deepsave insert', + ), + 'Comment' => array( + 'comment' => 'First comment deepsave insert', + 'published' => 'Y', + 'user_id' => 5, + 'Article' => array( + 'title' => 'First Article deepsave insert', + 'body' => 'First Article Body deepsave insert', + 'User' => array( + 'user' => 'deepsave', + 'password' => 'magic' + ), + ), + ) + ); + + $result = $TestModel->Comment->Attachment->saveAll($data, array('validate' => 'only', 'deep' => true)); + $this->assertTrue($result); + $result = $TestModel->Comment->Attachment->validateAssociated($data, array('deep' => true)); + $this->assertTrue($result); + + $expected = array( + 'Attachment' => true, + 'Comment' => true + ); + $result = $TestModel->Comment->Attachment->saveAll($data, array('validate' => 'only', 'atomic' => false, 'deep' => true)); + $this->assertSame($expected, $result); + $result = $TestModel->Comment->Attachment->validateAssociated($data, array('atomic' => false, 'deep' => true)); + $this->assertSame($expected, $result); + + $data = array( + 'Attachment' => array( + 'attachment' => 'deepsave insert', + ), + 'Comment' => array( + 'comment' => 'First comment deepsave insert', + 'published' => 'Y', + 'user_id' => 5, + 'Article' => array( + 'title' => 'First Article deepsave insert', + 'body' => 'First Article Body deepsave insert', + 'User' => array( + 'user' => '', + 'password' => 'magic' + ), + ), + ) + ); + + $result = $TestModel->Comment->Attachment->saveAll($data, array('validate' => 'only', 'deep' => true)); + $this->assertFalse($result); + $result = $TestModel->Comment->Attachment->validateAssociated($data, array('deep' => true)); + $this->assertFalse($result); + + $result = $TestModel->Comment->Attachment->validationErrors; + $expected = array( + 'Comment' => array( + 'Article' => array( + 'User' => array( + 'user' => array('This field cannot be left blank') + ) + ) + ) + ); + $this->assertSame($expected, $result); + + $expected = array( + 'Attachment' => true, + 'Comment' => false + ); + $result = $TestModel->Comment->Attachment->saveAll($data, array('validate' => 'only', 'atomic' => false, 'deep' => true)); + $this->assertEquals($expected, $result); + $result = $TestModel->Comment->Attachment->validateAssociated($data, array('atomic' => false, 'deep' => true)); + $this->assertEquals($expected, $result); + + $data['Comment']['Article']['body'] = ''; + $result = $TestModel->Comment->Attachment->saveAll($data, array('validate' => 'only', 'deep' => true)); + $this->assertFalse($result); + $result = $TestModel->Comment->Attachment->validateAssociated($data, array('deep' => true)); + $this->assertFalse($result); + + $result = $TestModel->Comment->Attachment->validationErrors; + $expected = array( + 'Comment' => array( + 'Article' => array( + 'body' => array('This field cannot be left blank'), + 'User' => array( + 'user' => array('This field cannot be left blank') + ) + ) + ) + ); + $this->assertSame($expected, $result); + + $expected = array( + 'Attachment' => true, + 'Comment' => false + ); + $result = $TestModel->Comment->Attachment->saveAll($data, array('validate' => 'only', 'atomic' => false, 'deep' => true)); + $this->assertEquals($expected, $result); + $result = $TestModel->Comment->Attachment->validateAssociated($data, array('atomic' => false, 'deep' => true)); + $this->assertEquals($expected, $result); + + $data['Comment']['comment'] = ''; + $result = $TestModel->Comment->Attachment->saveAll($data, array('validate' => 'only', 'deep' => true)); + $this->assertFalse($result); + $result = $TestModel->Comment->Attachment->validateAssociated($data, array('deep' => true)); + $this->assertFalse($result); + + $result = $TestModel->Comment->Attachment->validationErrors; + $expected = array( + 'Comment' => array( + 'comment' => array('This field cannot be left blank'), + 'Article' => array( + 'body' => array('This field cannot be left blank'), + 'User' => array( + 'user' => array('This field cannot be left blank') + ) + ) + ) + ); + $this->assertSame($expected, $result); + + $expected = array( + 'Attachment' => true, + 'Comment' => false + ); + $result = $TestModel->Comment->Attachment->saveAll($data, array('validate' => 'only', 'atomic' => false, 'deep' => true)); + $this->assertEquals($expected, $result); + $result = $TestModel->Comment->Attachment->validateAssociated($data, array('atomic' => false, 'deep' => true)); + $this->assertEquals($expected, $result); + + $data['Attachment']['attachment'] = ''; + $result = $TestModel->Comment->Attachment->saveAll($data, array('validate' => 'only', 'deep' => true)); + $this->assertFalse($result); + $result = $TestModel->Comment->Attachment->validateAssociated($data, array('deep' => true)); + $this->assertFalse($result); + + $result = $TestModel->Comment->Attachment->validationErrors; + $expected = array( + 'attachment' => array('This field cannot be left blank'), + 'Comment' => array( + 'comment' => array('This field cannot be left blank'), + 'Article' => array( + 'body' => array('This field cannot be left blank'), + 'User' => array( + 'user' => array('This field cannot be left blank') + ) + ) + ) + ); + $this->assertSame($expected, $result); + + $result = $TestModel->Comment->validationErrors; + $expected = array( + 'comment' => array('This field cannot be left blank'), + 'Article' => array( + 'body' => array('This field cannot be left blank'), + 'User' => array( + 'user' => array('This field cannot be left blank') + ) + ) + ); + $this->assertSame($expected, $result); + + $expected = array( + 'Attachment' => false, + 'Comment' => false + ); + $result = $TestModel->Comment->Attachment->saveAll($data, array('validate' => 'only', 'atomic' => false, 'deep' => true)); + $this->assertEquals($expected, $result); + $result = $TestModel->Comment->Attachment->validateAssociated($data, array('atomic' => false, 'deep' => true)); + $this->assertEquals($expected, $result); + } + +/** + * testSaveAllNotDeepValidateOnly + * tests the validate methods to not validate deeper recursive data + * + * @return void + */ + public function testSaveAllNotDeepValidateOnly() { + $this->loadFixtures('Article', 'Comment', 'User', 'Attachment'); + $TestModel = new Article(); + $TestModel->hasMany['Comment']['order'] = array('Comment.created' => 'ASC'); + $TestModel->hasAndBelongsToMany = array(); + $TestModel->Comment->Attachment->validate['attachment'] = 'notEmpty'; + $TestModel->Comment->validate['comment'] = 'notEmpty'; + + $data = array( + 'Article' => array('id' => 2, 'body' => ''), + 'Comment' => array( + array('comment' => 'First new comment', 'published' => 'Y', 'User' => array('user' => '', 'password' => 'newuserpass')), + array('comment' => 'Second new comment', 'published' => 'Y', 'user_id' => 2) + ) + ); + $result = $TestModel->saveAll($data, array('validate' => 'only', 'deep' => false)); + $this->assertFalse($result); + $result = $TestModel->validateAssociated($data, array('deep' => false)); + $this->assertFalse($result); + + $expected = array('body' => array('This field cannot be left blank')); + $result = $TestModel->validationErrors; + $this->assertSame($expected, $result); + + $data = array( + 'Article' => array('id' => 2, 'body' => 'Ignore invalid user data'), + 'Comment' => array( + array('comment' => 'First new comment', 'published' => 'Y', 'User' => array('user' => '', 'password' => 'newuserpass')), + array('comment' => 'Second new comment', 'published' => 'Y', 'user_id' => 2) + ) + ); + $result = $TestModel->saveAll($data, array('validate' => 'only', 'deep' => false)); + $this->assertTrue($result); + $result = $TestModel->validateAssociated($data, array('deep' => false)); + $this->assertTrue($result); + + $data = array( + 'Article' => array('id' => 2, 'body' => 'Ignore invalid user data'), + 'Comment' => array( + array('comment' => 'First new comment', 'published' => 'Y', 'User' => array('user' => '', 'password' => 'newuserpass')), + array('comment' => 'Second new comment', 'published' => 'Y', 'user_id' => 2) + ) + ); + $expected = array( + 'Article' => true, + 'Comment' => array( + true, + true + ) + ); + $result = $TestModel->saveAll($data, array('validate' => 'only', 'atomic' => false, 'deep' => false)); + $this->assertSame($expected, $result); + $result = $TestModel->validateAssociated($data, array('atomic' => false, 'deep' => false)); + $this->assertSame($expected, $result); + + $data = array( + 'Article' => array('id' => 2, 'body' => 'Ignore invalid attachment data'), + 'Comment' => array( + array('comment' => 'Third new comment', 'published' => 'Y', 'user_id' => 5), + array('comment' => 'Fourth new comment', 'published' => 'Y', 'user_id' => 2, 'Attachment' => array('attachment' => '')) + ) + ); + $result = $TestModel->saveAll($data, array('validate' => 'only', 'deep' => false)); + $this->assertTrue($result); + $result = $TestModel->validateAssociated($data, array('deep' => false)); + $this->assertTrue($result); + + $data = array( + 'Article' => array('id' => 2, 'body' => 'Ignore invalid attachment data'), + 'Comment' => array( + array('comment' => 'Third new comment', 'published' => 'Y', 'user_id' => 5), + array('comment' => 'Fourth new comment', 'published' => 'Y', 'user_id' => 2, 'Attachment' => array('attachment' => '')) + ) + ); + $expected = array( + 'Article' => true, + 'Comment' => array( + true, + true + ) + ); + $result = $TestModel->saveAll($data, array('validate' => 'only', 'atomic' => false, 'deep' => false)); + $this->assertSame($expected, $result); + $result = $TestModel->validateAssociated($data, array('atomic' => false, 'deep' => false)); + $this->assertSame($expected, $result); + + $expected = array(); + $result = $TestModel->validationErrors; + $this->assertSame($expected, $result); + + $data = array( + 'Attachment' => array( + 'attachment' => 'deepsave insert', + ), + 'Comment' => array( + 'comment' => 'First comment deepsave insert', + 'published' => 'Y', + 'user_id' => 5, + 'Article' => array( + 'title' => 'First Article deepsave insert ignored', + 'body' => 'First Article Body deepsave insert', + 'User' => array( + 'user' => '', + 'password' => 'magic' + ), + ), + ) + ); + + $result = $TestModel->Comment->Attachment->saveAll($data, array('validate' => 'only', 'deep' => false)); + $this->assertTrue($result); + $result = $TestModel->Comment->Attachment->validateAssociated($data, array('deep' => false)); + $this->assertTrue($result); + + $result = $TestModel->Comment->Attachment->validationErrors; + $expected = array(); + $this->assertSame($expected, $result); + + $expected = array( + 'Attachment' => true, + 'Comment' => true + ); + $result = $TestModel->Comment->Attachment->saveAll($data, array('validate' => 'only', 'atomic' => false, 'deep' => false)); + $this->assertEquals($expected, $result); + $result = $TestModel->Comment->Attachment->validateAssociated($data, array('atomic' => false, 'deep' => false)); + $this->assertEquals($expected, $result); + + $data['Comment']['Article']['body'] = ''; + $result = $TestModel->Comment->Attachment->saveAll($data, array('validate' => 'only', 'deep' => false)); + $this->assertTrue($result); + $result = $TestModel->Comment->Attachment->validateAssociated($data, array('deep' => false)); + $this->assertTrue($result); + + $result = $TestModel->Comment->Attachment->validationErrors; + $expected = array(); + $this->assertSame($expected, $result); + + $expected = array( + 'Attachment' => true, + 'Comment' => true + ); + $result = $TestModel->Comment->Attachment->saveAll($data, array('validate' => 'only', 'atomic' => false, 'deep' => false)); + $this->assertEquals($expected, $result); + $result = $TestModel->Comment->Attachment->validateAssociated($data, array('atomic' => false, 'deep' => false)); + $this->assertEquals($expected, $result); + } + +/** + * testValidateAssociated method + * + * @return void + */ + public function testValidateAssociated() { + $this->loadFixtures('Comment', 'Attachment'); + $TestModel = new Comment(); + $TestModel->Attachment->validate = array('attachment' => 'notEmpty'); + + $data = array( + 'Comment' => array( + 'comment' => 'This is the comment' + ), + 'Attachment' => array( + 'attachment' => '' + ) + ); + $result = $TestModel->saveAll($data, array('validate' => 'only')); + $this->assertFalse($result); + $result = $TestModel->validateAssociated($data); + $this->assertFalse($result); + + $TestModel->validate = array('comment' => 'notEmpty'); + $record = array( + 'Comment' => array( + 'user_id' => 1, + 'article_id' => 1, + 'comment' => '', + ), + 'Attachment' => array( + 'attachment' => '' + ) + ); + $result = $TestModel->saveAll($record, array('validate' => 'only')); + $this->assertFalse($result); + $result = $TestModel->validateAssociated($record); + $this->assertFalse($result); + + $fieldList = array( + 'Comment' => array('id', 'article_id', 'user_id'), + 'Attachment' => array('comment_id') + ); + $result = $TestModel->saveAll($record, array( + 'fieldList' => $fieldList, 'validate' => 'only' + )); + $this->assertTrue($result); + $this->assertEmpty($TestModel->validationErrors); + $result = $TestModel->validateAssociated($record, array('fieldList' => $fieldList)); + $this->assertTrue($result); + $this->assertEmpty($TestModel->validationErrors); + + $TestModel = new Article(); + $TestModel->belongsTo = $TestModel->hasAndBelongsToMany = array(); + $TestModel->Comment->validate = array('comment' => 'notEmpty'); + $data = array( + 'Article' => array('id' => 2), + 'Comment' => array( + array( + 'id' => 1, + 'comment' => '', + 'published' => 'Y', + 'user_id' => 1, + ), + array( + 'id' => 2, + 'comment' => + 'comment', + 'published' => 'Y', + 'user_id' => 1 + ), + array( + 'id' => 3, + 'comment' => '', + 'published' => 'Y', + 'user_id' => 1 + ))); + $result = $TestModel->saveAll($data, array('validate' => 'only')); + $this->assertFalse($result); + $result = $TestModel->validateAssociated($data); + $this->assertFalse($result); + + $expected = array( + 'Article' => true, + 'Comment' => array(false, true, false) + ); + $result = $TestModel->saveAll($data, array('atomic' => false, 'validate' => 'only')); + $this->assertSame($expected, $result); + $result = $TestModel->validateAssociated($data, array('atomic' => false)); + $this->assertSame($expected, $result); + + $expected = array('Comment' => array( + 0 => array('comment' => array('This field cannot be left blank')), + 2 => array('comment' => array('This field cannot be left blank')) + )); + $this->assertEquals($expected['Comment'], $TestModel->Comment->validationErrors); + + $model = new Comment(); + $model->deleteAll(true); + $model->validate = array('comment' => 'notEmpty'); + $model->Attachment->validate = array('attachment' => 'notEmpty'); + $model->Attachment->bindModel(array('belongsTo' => array('Comment'))); + $expected = array( + 'comment' => array('This field cannot be left blank'), + 'Attachment' => array( + 'attachment' => array('This field cannot be left blank') + ) + ); + + $data = array( + 'Comment' => array('comment' => '', 'article_id' => 1, 'user_id' => 1), + 'Attachment' => array('attachment' => '') + ); + $result = $model->saveAll($data, array('validate' => 'only')); + $this->assertFalse($result); + $result = $model->validateAssociated($data); + $this->assertFalse($result); + $this->assertEquals($expected, $model->validationErrors); + $this->assertEquals($expected['Attachment'], $model->Attachment->validationErrors); + } + +/** + * testValidateMany method + * + * @return void + */ + public function testValidateMany() { + $TestModel = new Article(); + $TestModel->validate = array('title' => 'notEmpty'); + $data = array( + 0 => array('title' => ''), + 1 => array('title' => 'title 1'), + 2 => array('title' => 'title 2'), + ); + $expected = array( + 0 => array('title' => array('This field cannot be left blank')), + ); + + $result = $TestModel->saveAll($data, array('validate' => 'only')); + $this->assertFalse($result); + $this->assertEquals($expected, $TestModel->validationErrors); + $result = $TestModel->validateMany($data); + $this->assertFalse($result); + $this->assertEquals($expected, $TestModel->validationErrors); + + $data = array( + 0 => array('title' => 'title 0'), + 1 => array('title' => ''), + 2 => array('title' => 'title 2'), + ); + $expected = array( + 1 => array('title' => array('This field cannot be left blank')), + ); + $result = $TestModel->saveAll($data, array('validate' => 'only')); + $this->assertFalse($result); + $this->assertEquals($expected, $TestModel->validationErrors); + $result = $TestModel->validateMany($data); + $this->assertFalse($result); + $this->assertEquals($expected, $TestModel->validationErrors); + } + +/** + * testGetMethods method + * + * @return void + */ + public function testGetMethods() { + $this->loadFixtures('Article', 'Comment'); + $TestModel = new Article(); + $Validator = $TestModel->validator(); + + $result = $Validator->getMethods(); + + $expected = array_map('strtolower', get_class_methods('Article')); + $this->assertEquals($expected, array_keys($result)); + } + +/** + * testSetValidationDomain method + * + * @return void + */ + public function testSetValidationDomain() { + $this->loadFixtures('Article', 'Comment'); + $TestModel = new Article(); + $Validator = $TestModel->validator(); + + $result = $Validator->setValidationDomain('default'); + $this->assertEquals('default', $TestModel->validationDomain); + + $result = $Validator->setValidationDomain('other'); + $this->assertEquals('other', $TestModel->validationDomain); + } + +/** + * testGetModel method + * + * @return void + */ + public function testGetModel() { + $TestModel = new Article(); + $Validator = $TestModel->validator(); + + $result = $Validator->getModel(); + $this->assertInstanceOf('Article', $result); + } + +/** + * Tests it is possible to get validation sets for a field using an array inteface + * + * @return void + */ + public function testArrayAccessGet() { + $TestModel = new Article(); + $Validator = $TestModel->validator(); + + $titleValidator = $Validator['title']; + $this->assertEquals('title', $titleValidator->field); + $this->assertCount(1, $titleValidator->getRules()); + $rule = current($titleValidator->getRules()); + $this->assertEquals('notEmpty', $rule->rule); + + $titleValidator = $Validator['body']; + $this->assertEquals('body', $titleValidator->field); + $this->assertCount(1, $titleValidator->getRules()); + $rule = current($titleValidator->getRules()); + $this->assertEquals('notEmpty', $rule->rule); + + $titleValidator = $Validator['user_id']; + $this->assertEquals('user_id', $titleValidator->field); + $this->assertCount(1, $titleValidator->getRules()); + $rule = current($titleValidator->getRules()); + $this->assertEquals('numeric', $rule->rule); + } + +/** + * Tests it is possible to check for validation sets for a field using an array inteface + * + * @return void + */ + public function testArrayAccessExists() { + $TestModel = new Article(); + $Validator = $TestModel->validator(); + + $this->assertTrue(isset($Validator['title'])); + $this->assertTrue(isset($Validator['body'])); + $this->assertTrue(isset($Validator['user_id'])); + $this->assertFalse(isset($Validator['other'])); + } + +/** + * Tests it is possible to set validation rules for a field using an array inteface + * + * @return void + */ + public function testArrayAccessSet() { + $TestModel = new Article(); + $Validator = $TestModel->validator(); + + $set = array( + 'numeric' => array('rule' => 'numeric', 'allowEmpty' => false), + 'range' => array('rule' => array('between', 1, 5), 'allowEmpty' => false), + ); + $Validator['other'] = $set; + $rules = $Validator['other']; + $this->assertEquals('other', $rules->field); + + $validators = $rules->getRules(); + $this->assertCount(2, $validators); + $this->assertEquals('numeric', $validators['numeric']->rule); + $this->assertEquals(array('between', 1, 5), $validators['range']->rule); + + $Validator['new'] = new CakeValidationSet('new', $set, array()); + $rules = $Validator['new']; + $this->assertEquals('new', $rules->field); + + $validators = $rules->getRules(); + $this->assertCount(2, $validators); + $this->assertEquals('numeric', $validators['numeric']->rule); + $this->assertEquals(array('between', 1, 5), $validators['range']->rule); + } + +/** + * Tests it is possible to unset validation rules + * + * @return void + */ + public function testArrayAccessUset() { + $TestModel = new Article(); + $Validator = $TestModel->validator(); + + $this->assertTrue(isset($Validator['title'])); + unset($Validator['title']); + $this->assertFalse(isset($Validator['title'])); + } + +/** + * Tests it is possible to iterate a validation object + * + * @return void + */ + public function testIterator() { + $TestModel = new Article(); + $Validator = $TestModel->validator(); + + $i = 0; + foreach ($Validator as $field => $rules) { + if ($i === 0) { + $this->assertEquals('user_id', $field); + } + if ($i === 1) { + $this->assertEquals('title', $field); + } + if ($i === 2) { + $this->assertEquals('body', $field); + } + $this->assertInstanceOf('CakeValidationSet', $rules); + $i++; + } + $this->assertEquals(3, $i); + } + +/** + * Tests countable interface in ModelValidator + * + * @return void + */ + public function testCount() { + $TestModel = new Article(); + $Validator = $TestModel->validator(); + $this->assertCount(3, $Validator); + + $set = array( + 'numeric' => array('rule' => 'numeric', 'allowEmpty' => false), + 'range' => array('rule' => array('between', 1, 5), 'allowEmpty' => false), + ); + $Validator['other'] = $set; + $this->assertCount(4, $Validator); + + unset($Validator['title']); + $this->assertCount(3, $Validator); + unset($Validator['body']); + $this->assertCount(2, $Validator); + } + +/** + * Tests it is possible to add validation rules + * + * @return void + */ + public function testAddRule() { + $TestModel = new Article(); + $Validator = $TestModel->validator(); + + $Validator->add('other', 'numeric', array('rule' => 'numeric', 'allowEmpty' => false)); + $Validator->add('other', 'range', array('rule' => array('between', 1, 5), 'allowEmpty' => false)); + $rules = $Validator['other']; + $this->assertEquals('other', $rules->field); + + $validators = $rules->getRules(); + $this->assertCount(2, $validators); + $this->assertEquals('numeric', $validators['numeric']->rule); + $this->assertEquals(array('between', 1, 5), $validators['range']->rule); + } + +/** + * Tests it is possible to remove validation rules + * + * @return void + */ + public function testRemoveRule() { + $TestModel = new Article(); + $Validator = $TestModel->validator(); + + $this->assertTrue(isset($Validator['title'])); + $Validator->remove('title'); + $this->assertFalse(isset($Validator['title'])); + + $Validator->add('other', 'numeric', array('rule' => 'numeric', 'allowEmpty' => false)); + $Validator->add('other', 'range', array('rule' => array('between', 1, 5), 'allowEmpty' => false)); + $this->assertTrue(isset($Validator['other'])); + + $Validator->remove('other', 'numeric'); + $this->assertTrue(isset($Validator['other'])); + $this->assertFalse(isset($Validator['other']['numeric'])); + $this->assertTrue(isset($Validator['other']['range'])); + } + +/** + * Tests validation callbacks are triggered + * + * @return void + */ + public function testValidateCallbacks() { + $TestModel = $this->getMock('Article', array('beforeValidate', 'afterValidate')); + $TestModel->expects($this->once())->method('beforeValidate'); + $TestModel->expects($this->once())->method('afterValidate'); + + $TestModel->set(array('title' => '', 'body' => 'body')); + $TestModel->validates(); + } + +/** + * Tests that altering data in a beforeValidate callback will lead to saving those + * values in database + * + * @return void + */ + public function testValidateFirstWithBeforeValidate() { + $this->loadFixtures('Article', 'User'); + $model = new CustomArticle(); + $model->validate = array( + 'title' => array( + 'notempty' => array( + 'rule' => 'notEmpty', + 'required' => true, + 'allowEmpty' => false + ) + ) + ); + $data = array( + 'CustomArticle' => array( + 'body' => 'foo0' + ) + ); + $result = $model->saveAll($data, array('validate' => 'first')); + $this->assertTrue($result); + + $this->assertFalse($model->findMethods['unPublished'], 'beforeValidate was run twice'); + + $model->findMethods['unPublished'] = true; + $data = array( + 'CustomArticle' => array( + 'body' => 'foo1' + ) + ); + $result = $model->saveAll($data, array('validate' => 'first', 'deep' => true)); + $this->assertTrue($result); + $title = $model->field('title', array('body' => 'foo1')); + $this->assertEquals('foo', $title); + $this->assertFalse($model->findMethods['unPublished'], 'beforeValidate was run twice'); + + $data = array( + array('body' => 'foo2'), + array('body' => 'foo3'), + array('body' => 'foo4') + ); + + $result = $model->saveAll($data, array('validate' => 'first', 'deep' => true)); + $this->assertTrue($result); + + $this->assertEquals('foo', $model->field('title', array('body' => 'foo2'))); + $this->assertEquals('foo', $model->field('title', array('body' => 'foo3'))); + $this->assertEquals('foo', $model->field('title', array('body' => 'foo4'))); + } + +/** + * Tests that altering data in a beforeValidate callback will lead to saving those + * values in database + * + * @return void + */ + public function testValidateFirstAssociatedWithBeforeValidate() { + $this->loadFixtures('Article', 'User'); + $model = new CustomArticle(); + $model->validate = array( + 'title' => array( + 'notempty' => array( + 'rule' => 'notEmpty', + 'required' => true + ) + ) + ); + $articles = array( + array('body' => 'foo1'), + array('body' => 'foo2'), + array('body' => 'foo3') + ); + $user = new User(); + $user->bindModel(array('hasMany' => array('CustomArticle'))); + $data = array( + 'User' => array('user' => 'foo', 'password' => 'bar'), + 'CustomArticle' => $articles + ); + $result = $user->saveAll($data, array('validate' => 'first')); + $this->assertTrue($result); + + $this->assertEquals('foo', $model->field('title', array('body' => 'foo1'))); + $this->assertEquals('foo', $model->field('title', array('body' => 'foo2'))); + $this->assertEquals('foo', $model->field('title', array('body' => 'foo3'))); + } + +/** + * testValidateFirstWithDefaults method + * + * return @void + */ + public function testFirstWithDefaults() { + $this->loadFixtures('Article', 'Tag', 'Comment', 'User', 'ArticlesTag'); + $TestModel = new Article(); + + $result = $TestModel->find('first', array( + 'conditions' => array('Article.id' => 1) + )); + $expected = array( + 'Article' => array( + 'id' => 1, + 'user_id' => 1, + 'title' => 'First Article', + 'body' => 'First Article Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:39:23' + ), + ); + unset($result['Article']['updated']); + $this->assertEquals($expected['Article'], $result['Article']); + + $data = array( + 'Article' => array( + 'id' => 1, + 'title' => 'First Article (modified)' + ), + 'Comment' => array( + array('comment' => 'Article comment', 'user_id' => 1) + ) + ); + $result = $TestModel->saveAll($data, array('validate' => 'first')); + $this->assertTrue($result); + + $result = $TestModel->find('first', array( + 'conditions' => array('Article.id' => 1) + )); + $expected['Article']['title'] = 'First Article (modified)'; + unset($result['Article']['updated']); + $this->assertEquals($expected['Article'], $result['Article']); + } + + public function testAddMultipleRules() { + $TestModel = new Article(); + $Validator = $TestModel->validator(); + + $set = array( + 'numeric' => array('rule' => 'numeric', 'allowEmpty' => false), + 'range' => array('rule' => array('between', 1, 5), 'allowEmpty' => false), + ); + + $Validator->add('other', $set); + $rules = $Validator['other']; + $this->assertEquals('other', $rules->field); + + $validators = $rules->getRules(); + $this->assertCount(2, $validators); + $this->assertEquals('numeric', $validators['numeric']->rule); + $this->assertEquals(array('between', 1, 5), $validators['range']->rule); + + $set = new CakeValidationSet('other', array( + 'a' => array('rule' => 'numeric', 'allowEmpty' => false), + 'b' => array('rule' => array('between', 1, 5), 'allowEmpty' => false), + )); + + $Validator->add('other', $set); + $this->assertSame($set, $Validator->getField('other')); + } + +/** + * Test that rules are parsed correctly when calling getField() + * + * @return void + */ + public function testValidator() { + $TestModel = new Article(); + $Validator = $TestModel->validator(); + + $result = $Validator->getField(); + $expected = array('user_id', 'title', 'body'); + $this->assertEquals($expected, array_keys($result)); + $this->assertTrue($result['user_id'] instanceof CakeValidationSet); + + $result = $TestModel->validator()->getField('title'); + $this->assertTrue($result instanceof CakeValidationSet); + } + +/** + * Tests that altering data in a beforeValidate callback will lead to saving those + * values in database, this time with belongsTo associations + * + * @return void + */ + public function testValidateFirstAssociatedWithBeforeValidate2() { + $this->loadFixtures('Article', 'User'); + $model = new CustomArticle(); + $model->validate = array( + 'title' => array( + 'notempty' => array( + 'rule' => 'notEmpty', + 'required' => true + ) + ) + ); + + $data = array( + 'User' => array('user' => 'foo', 'password' => 'bar'), + 'CustomArticle' => array( + 'body' => 'a test' + ) + ); + $result = $model->saveAll($data, array('validate' => 'first')); + $this->assertTrue($result); + + $this->assertEquals('foo', $model->field('title', array('body' => 'a test'))); + } + +/** + * Testing you can dynamically add rules to a field, added this to dispel doubts + * after a presentation made to show off this new feature + * + * @return void + **/ + public function testDynamicValidationRuleBuilding() { + $model = new Article; + $validator = $model->validator(); + $validator->add('body', 'isSpecial', array('rule' => 'special')); + $rules = $validator['body']->getRules(); + $this->assertCount(2, $rules); + $this->assertEquals('special', $rules['isSpecial']->rule); + $validator['body']->setRule('isAwesome', array('rule' => 'awesome')); + $rules = $validator['body']->getRules(); + $this->assertCount(3, $rules); + $this->assertEquals('awesome', $rules['isAwesome']->rule); + } + +/** + * Test to ensure custom validation methods work with CakeValidationSet + * + * @return void + */ + public function testCustomMethodsWithCakeValidationSet() { + $TestModel = new TestValidate(); + $Validator = $TestModel->validator(); + + $Validator->add('title', 'validateTitle', array( + 'rule' => 'validateTitle', + 'message' => 'That aint right', + )); + $data = array('title' => 'notatitle'); + $result = $Validator->getField('title')->validate($data); + $expected = array(0 => 'That aint right'); + $this->assertEquals($expected, $result); + + $data = array('title' => 'title-is-good'); + $result = $Validator->getField('title')->validate($data); + $expected = array(); + $this->assertEquals($expected, $result); + } + + public function testCustomMethodWithEmptyValue() { + $this->loadFixtures('Article'); + + $model = $this->getMock('Article', array('isLegit')); + $model->validate = array( + 'title' => array( + 'custom' => array( + 'rule' => array('isLegit'), + 'message' => 'is no good' + ) + ) + ); + $model->expects($this->once()) + ->method('isLegit') + ->will($this->returnValue(false)); + + $model->set(array('title' => '')); + $this->assertFalse($model->validates()); + } + +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/ModelWriteTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/ModelWriteTest.php new file mode 100644 index 0000000..fe8714e --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/ModelWriteTest.php @@ -0,0 +1,6877 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Model + * @since CakePHP(tm) v 1.2.0.4206 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ +require_once dirname(__FILE__) . DS . 'ModelTestBase.php'; +/** + * ModelWriteTest + * + * @package Cake.Test.Case.Model + */ +class ModelWriteTest extends BaseModelTest { + +/** + * testInsertAnotherHabtmRecordWithSameForeignKey method + * + * @access public + * @return void + */ + public function testInsertAnotherHabtmRecordWithSameForeignKey() { + $this->loadFixtures('JoinA', 'JoinB', 'JoinAB', 'JoinC', 'JoinAC'); + $TestModel = new JoinA(); + + $result = $TestModel->JoinAsJoinB->findById(1); + $expected = array( + 'JoinAsJoinB' => array( + 'id' => 1, + 'join_a_id' => 1, + 'join_b_id' => 2, + 'other' => 'Data for Join A 1 Join B 2', + 'created' => '2008-01-03 10:56:33', + 'updated' => '2008-01-03 10:56:33' + )); + $this->assertEquals($expected, $result); + + $TestModel->JoinAsJoinB->create(); + $data = array( + 'join_a_id' => 1, + 'join_b_id' => 1, + 'other' => 'Data for Join A 1 Join B 1', + 'created' => '2008-01-03 10:56:44', + 'updated' => '2008-01-03 10:56:44' + ); + $result = $TestModel->JoinAsJoinB->save($data); + $lastInsertId = $TestModel->JoinAsJoinB->getLastInsertID(); + $data['id'] = $lastInsertId; + $this->assertEquals(array('JoinAsJoinB' => $data), $result); + $this->assertTrue($lastInsertId != null); + + $result = $TestModel->JoinAsJoinB->findById(1); + $expected = array( + 'JoinAsJoinB' => array( + 'id' => 1, + 'join_a_id' => 1, + 'join_b_id' => 2, + 'other' => 'Data for Join A 1 Join B 2', + 'created' => '2008-01-03 10:56:33', + 'updated' => '2008-01-03 10:56:33' + )); + $this->assertEquals($expected, $result); + + $updatedValue = 'UPDATED Data for Join A 1 Join B 2'; + $TestModel->JoinAsJoinB->id = 1; + $result = $TestModel->JoinAsJoinB->saveField('other', $updatedValue, false); + $this->assertFalse(empty($result)); + + $result = $TestModel->JoinAsJoinB->findById(1); + $this->assertEquals($updatedValue, $result['JoinAsJoinB']['other']); + } + +/** + * testSaveDateAsFirstEntry method + * + * @return void + */ + public function testSaveDateAsFirstEntry() { + $this->loadFixtures('Article', 'User', 'Comment', 'Attachment', 'Tag', 'ArticlesTag'); + + $Article = new Article(); + + $data = array( + 'Article' => array( + 'created' => array( + 'day' => '1', + 'month' => '1', + 'year' => '2008' + ), + 'title' => 'Test Title', + 'user_id' => 1 + )); + $Article->create(); + $result = $Article->save($data); + $this->assertFalse(empty($result)); + + $testResult = $Article->find('first', array('conditions' => array('Article.title' => 'Test Title'))); + + $this->assertEquals($data['Article']['title'], $testResult['Article']['title']); + $this->assertEquals('2008-01-01 00:00:00', $testResult['Article']['created']); + } + +/** + * testUnderscoreFieldSave method + * + * @return void + */ + public function testUnderscoreFieldSave() { + $this->loadFixtures('UnderscoreField'); + $UnderscoreField = new UnderscoreField(); + + $currentCount = $UnderscoreField->find('count'); + $this->assertEquals(3, $currentCount); + $data = array('UnderscoreField' => array( + 'user_id' => '1', + 'my_model_has_a_field' => 'Content here', + 'body' => 'Body', + 'published' => 'Y', + 'another_field' => 4 + )); + $ret = $UnderscoreField->save($data); + $this->assertFalse(empty($ret)); + + $currentCount = $UnderscoreField->find('count'); + $this->assertEquals(4, $currentCount); + } + +/** + * testAutoSaveUuid method + * + * @return void + */ + public function testAutoSaveUuid() { + // SQLite does not support non-integer primary keys + $this->skipIf($this->db instanceof Sqlite, 'This test is not compatible with SQLite.'); + + $this->loadFixtures('Uuid'); + $TestModel = new Uuid(); + + $TestModel->save(array('title' => 'Test record')); + $result = $TestModel->findByTitle('Test record'); + $this->assertEquals( + array('id', 'title', 'count', 'created', 'updated'), + array_keys($result['Uuid']) + ); + $this->assertEquals(36, strlen($result['Uuid']['id'])); + } + +/** + * Ensure that if the id key is null but present the save doesn't fail (with an + * x sql error: "Column id specified twice") + * + * @return void + */ + public function testSaveUuidNull() { + // SQLite does not support non-integer primary keys + $this->skipIf($this->db instanceof Sqlite, 'This test is not compatible with SQLite.'); + + $this->loadFixtures('Uuid'); + $TestModel = new Uuid(); + + $TestModel->save(array('title' => 'Test record', 'id' => null)); + $result = $TestModel->findByTitle('Test record'); + $this->assertEquals( + array('id', 'title', 'count', 'created', 'updated'), + array_keys($result['Uuid']) + ); + $this->assertEquals(36, strlen($result['Uuid']['id'])); + } + +/** + * testZeroDefaultFieldValue method + * + * @return void + */ + public function testZeroDefaultFieldValue() { + $this->skipIf($this->db instanceof Sqlite, 'SQLite uses loose typing, this operation is unsupported.'); + + $this->loadFixtures('DataTest'); + $TestModel = new DataTest(); + + $TestModel->create(array()); + $TestModel->save(); + $result = $TestModel->findById($TestModel->id); + $this->assertEquals(0, $result['DataTest']['count']); + $this->assertEquals(0, $result['DataTest']['float']); + } + +/** + * Tests validation parameter order in custom validation methods + * + * @return void + */ + public function testAllowSimulatedFields() { + $TestModel = new ValidationTest1(); + + $TestModel->create(array( + 'title' => 'foo', + 'bar' => 'baz' + )); + $expected = array( + 'ValidationTest1' => array( + 'title' => 'foo', + 'bar' => 'baz' + )); + $this->assertEquals($expected, $TestModel->data); + } + +/** + * test that Caches are getting cleared on save(). + * ensure that both inflections of controller names are getting cleared + * as url for controller could be either overallFavorites/index or overall_favorites/index + * + * @return void + */ + public function testCacheClearOnSave() { + $_back = array( + 'check' => Configure::read('Cache.check'), + 'disable' => Configure::read('Cache.disable'), + ); + Configure::write('Cache.check', true); + Configure::write('Cache.disable', false); + + $this->loadFixtures('OverallFavorite'); + $OverallFavorite = new OverallFavorite(); + + touch(CACHE . 'views' . DS . 'some_dir_overallfavorites_index.php'); + touch(CACHE . 'views' . DS . 'some_dir_overall_favorites_index.php'); + + $data = array( + 'OverallFavorite' => array( + 'id' => 22, + 'model_type' => '8-track', + 'model_id' => '3', + 'priority' => '1' + ) + ); + $OverallFavorite->create($data); + $OverallFavorite->save(); + + $this->assertFalse(file_exists(CACHE . 'views' . DS . 'some_dir_overallfavorites_index.php')); + $this->assertFalse(file_exists(CACHE . 'views' . DS . 'some_dir_overall_favorites_index.php')); + + Configure::write('Cache.check', $_back['check']); + Configure::write('Cache.disable', $_back['disable']); + } + +/** + * testSaveWithCounterCache method + * + * @return void + */ + public function testSaveWithCounterCache() { + $this->loadFixtures('Syfile', 'Item', 'Image', 'Portfolio', 'ItemsPortfolio'); + $TestModel = new Syfile(); + $TestModel2 = new Item(); + + $result = $TestModel->findById(1); + $this->assertSame($result['Syfile']['item_count'], null); + + $TestModel2->save(array( + 'name' => 'Item 7', + 'syfile_id' => 1, + 'published' => false + )); + + $result = $TestModel->findById(1); + $this->assertEquals(2, $result['Syfile']['item_count']); + + $TestModel2->delete(1); + $result = $TestModel->findById(1); + $this->assertEquals(1, $result['Syfile']['item_count']); + + $TestModel2->id = 2; + $TestModel2->saveField('syfile_id', 1); + + $result = $TestModel->findById(1); + $this->assertEquals(2, $result['Syfile']['item_count']); + + $result = $TestModel->findById(2); + $this->assertEquals(0, $result['Syfile']['item_count']); + } + +/** + * Tests that counter caches are updated when records are added + * + * @return void + */ + public function testCounterCacheIncrease() { + $this->loadFixtures('CounterCacheUser', 'CounterCachePost'); + $User = new CounterCacheUser(); + $Post = new CounterCachePost(); + $data = array('Post' => array( + 'id' => 22, + 'title' => 'New Post', + 'user_id' => 66 + )); + + $Post->save($data); + $user = $User->find('first', array( + 'conditions' => array('id' => 66), + 'recursive' => -1 + )); + + $result = $user[$User->alias]['post_count']; + $expected = 3; + $this->assertEquals($expected, $result); + } + +/** + * Tests that counter caches are updated when records are deleted + * + * @return void + */ + public function testCounterCacheDecrease() { + $this->loadFixtures('CounterCacheUser', 'CounterCachePost'); + $User = new CounterCacheUser(); + $Post = new CounterCachePost(); + + $Post->delete(2); + $user = $User->find('first', array( + 'conditions' => array('id' => 66), + 'recursive' => -1 + )); + + $result = $user[$User->alias]['post_count']; + $expected = 1; + $this->assertEquals($expected, $result); + } + +/** + * Tests that counter caches are updated when foreign keys of counted records change + * + * @return void + */ + public function testCounterCacheUpdated() { + $this->loadFixtures('CounterCacheUser', 'CounterCachePost'); + $User = new CounterCacheUser(); + $Post = new CounterCachePost(); + + $data = $Post->find('first', array( + 'conditions' => array('id' => 1), + 'recursive' => -1 + )); + $data[$Post->alias]['user_id'] = 301; + $Post->save($data); + + $users = $User->find('all',array('order' => 'User.id')); + $this->assertEquals(1, $users[0]['User']['post_count']); + $this->assertEquals(2, $users[1]['User']['post_count']); + } + +/** + * Test counter cache with models that use a non-standard (i.e. not using 'id') + * as their primary key. + * + * @return void + */ + public function testCounterCacheWithNonstandardPrimaryKey() { + $this->loadFixtures( + 'CounterCacheUserNonstandardPrimaryKey', + 'CounterCachePostNonstandardPrimaryKey' + ); + + $User = new CounterCacheUserNonstandardPrimaryKey(); + $Post = new CounterCachePostNonstandardPrimaryKey(); + + $data = $Post->find('first', array( + 'conditions' => array('pid' => 1), + 'recursive' => -1 + )); + $data[$Post->alias]['uid'] = 301; + $Post->save($data); + + $users = $User->find('all',array('order' => 'User.uid')); + $this->assertEquals(1, $users[0]['User']['post_count']); + $this->assertEquals(2, $users[1]['User']['post_count']); + } + +/** + * test Counter Cache With Self Joining table + * + * @return void + */ + public function testCounterCacheWithSelfJoin() { + $this->skipIf($this->db instanceof Sqlite, 'SQLite 2.x does not support ALTER TABLE ADD COLUMN'); + + $this->loadFixtures('CategoryThread'); + $column = 'COLUMN '; + if ($this->db instanceof Sqlserver) { + $column = ''; + } + $column .= $this->db->buildColumn(array('name' => 'child_count', 'type' => 'integer')); + $this->db->query('ALTER TABLE ' . $this->db->fullTableName('category_threads') . ' ADD ' . $column); + $this->db->flushMethodCache(); + $Category = new CategoryThread(); + $result = $Category->updateAll(array('CategoryThread.name' => "'updated'"), array('CategoryThread.parent_id' => 5)); + $this->assertFalse(empty($result)); + + $Category = new CategoryThread(); + $Category->belongsTo['ParentCategory']['counterCache'] = 'child_count'; + $Category->updateCounterCache(array('parent_id' => 5)); + $result = Hash::extract($Category->find('all', array('conditions' => array('CategoryThread.id' => 5))), '{n}.CategoryThread.child_count'); + $expected = array(1); + $this->assertEquals($expected, $result); + } + +/** + * testSaveWithCounterCacheScope method + * + * @return void + */ + public function testSaveWithCounterCacheScope() { + $this->loadFixtures('Syfile', 'Item', 'Image', 'ItemsPortfolio', 'Portfolio'); + $TestModel = new Syfile(); + $TestModel2 = new Item(); + $TestModel2->belongsTo['Syfile']['counterCache'] = true; + $TestModel2->belongsTo['Syfile']['counterScope'] = array('published' => true); + + $result = $TestModel->findById(1); + $this->assertSame($result['Syfile']['item_count'], null); + + $TestModel2->save(array( + 'name' => 'Item 7', + 'syfile_id' => 1, + 'published' => true + )); + + $result = $TestModel->findById(1); + + $this->assertEquals(1, $result['Syfile']['item_count']); + + $TestModel2->id = 1; + $TestModel2->saveField('published', true); + $result = $TestModel->findById(1); + $this->assertEquals(2, $result['Syfile']['item_count']); + + $TestModel2->save(array( + 'id' => 1, + 'syfile_id' => 1, + 'published' => false + )); + + $result = $TestModel->findById(1); + $this->assertEquals(1, $result['Syfile']['item_count']); + } + +/** + * Tests having multiple counter caches for an associated model + * + * @access public + * @return void + */ + public function testCounterCacheMultipleCaches() { + $this->loadFixtures('CounterCacheUser', 'CounterCachePost'); + $User = new CounterCacheUser(); + $Post = new CounterCachePost(); + $Post->unbindModel(array('belongsTo' => array('User')), false); + $Post->bindModel(array( + 'belongsTo' => array( + 'User' => array( + 'className' => 'CounterCacheUser', + 'foreignKey' => 'user_id', + 'counterCache' => array( + true, + 'posts_published' => array('Post.published' => true) + ) + ) + ) + ), false); + + // Count Increase + $user = $User->find('first', array( + 'conditions' => array('id' => 66), + 'recursive' => -1 + )); + $data = array('Post' => array( + 'id' => 22, + 'title' => 'New Post', + 'user_id' => 66, + 'published' => true + )); + $Post->save($data); + $result = $User->find('first', array( + 'conditions' => array('id' => 66), + 'recursive' => -1 + )); + $this->assertEquals(3, $result[$User->alias]['post_count']); + $this->assertEquals(2, $result[$User->alias]['posts_published']); + + // Count decrease + $Post->delete(1); + $result = $User->find('first', array( + 'conditions' => array('id' => 66), + 'recursive' => -1 + )); + $this->assertEquals(2, $result[$User->alias]['post_count']); + $this->assertEquals(2, $result[$User->alias]['posts_published']); + + // Count update + $data = $Post->find('first', array( + 'conditions' => array('id' => 1), + 'recursive' => -1 + )); + $data[$Post->alias]['user_id'] = 301; + $Post->save($data); + $result = $User->find('all',array('order' => 'User.id')); + $this->assertEquals(2, $result[0]['User']['post_count']); + $this->assertEquals(1, $result[1]['User']['posts_published']); + } + +/** + * test that beforeValidate returning false can abort saves. + * + * @return void + */ + public function testBeforeValidateSaveAbortion() { + $this->loadFixtures('Post'); + $Model = new CallbackPostTestModel(); + $Model->beforeValidateReturn = false; + + $data = array( + 'title' => 'new article', + 'body' => 'this is some text.' + ); + $Model->create(); + $result = $Model->save($data); + $this->assertFalse($result); + } + +/** + * test that beforeSave returning false can abort saves. + * + * @return void + */ + public function testBeforeSaveSaveAbortion() { + $this->loadFixtures('Post'); + $Model = new CallbackPostTestModel(); + $Model->beforeSaveReturn = false; + + $data = array( + 'title' => 'new article', + 'body' => 'this is some text.' + ); + $Model->create(); + $result = $Model->save($data); + $this->assertFalse($result); + } + +/** + * testSaveField method + * + * @return void + */ + public function testSaveField() { + $this->loadFixtures('Article'); + $TestModel = new Article(); + + $TestModel->id = 1; + $result = $TestModel->saveField('title', 'New First Article'); + $this->assertFalse(empty($result)); + + $TestModel->recursive = -1; + $result = $TestModel->read(array('id', 'user_id', 'title', 'body'), 1); + $expected = array('Article' => array( + 'id' => '1', + 'user_id' => '1', + 'title' => 'New First Article', + 'body' => 'First Article Body' + )); + $this->assertEquals($expected, $result); + + $TestModel->id = 1; + $result = $TestModel->saveField('title', ''); + $this->assertFalse(empty($result)); + + $TestModel->recursive = -1; + $result = $TestModel->read(array('id', 'user_id', 'title', 'body'), 1); + $expected = array('Article' => array( + 'id' => '1', + 'user_id' => '1', + 'title' => '', + 'body' => 'First Article Body' + )); + $result['Article']['title'] = trim($result['Article']['title']); + $this->assertEquals($expected, $result); + + $TestModel->id = 1; + $TestModel->set('body', 'Messed up data'); + $result = $TestModel->saveField('title', 'First Article'); + $this->assertFalse(empty($result)); + $result = $TestModel->read(array('id', 'user_id', 'title', 'body'), 1); + $expected = array('Article' => array( + 'id' => '1', + 'user_id' => '1', + 'title' => 'First Article', + 'body' => 'First Article Body' + )); + $this->assertEquals($expected, $result); + + $TestModel->recursive = -1; + $TestModel->read(array('id', 'user_id', 'title', 'body'), 1); + + $TestModel->id = 1; + $result = $TestModel->saveField('title', '', true); + $this->assertFalse($result); + + $TestModel->recursive = -1; + $TestModel->id = 1; + $result = $TestModel->saveField('user_id', 9999); + $this->assertTrue((bool)$result); + + $result = $TestModel->read(array('id', 'user_id'), 1); + $expected = array('Article' => array( + 'id' => '1', + 'user_id' => '9999', + )); + $this->assertEquals($expected, $result); + + $this->loadFixtures('Node', 'Dependency'); + $Node = new Node(); + $Node->set('id', 1); + $result = $Node->read(); + $this->assertEquals(array('Second'), Hash::extract($result, 'ParentNode.{n}.name')); + + $Node->saveField('state', 10); + $result = $Node->read(); + $this->assertEquals(array('Second'), Hash::extract($result, 'ParentNode.{n}.name')); + } + +/** + * testSaveWithCreate method + * + * @return void + */ + public function testSaveWithCreate() { + $this->loadFixtures( + 'User', + 'Article', + 'User', + 'Comment', + 'Tag', + 'ArticlesTag', + 'Attachment' + ); + $TestModel = new User(); + + $data = array('User' => array( + 'user' => 'user', + 'password' => '' + )); + $result = $TestModel->save($data); + $this->assertFalse($result); + $this->assertTrue(!empty($TestModel->validationErrors)); + + $TestModel = new Article(); + + $data = array('Article' => array( + 'user_id' => '', + 'title' => '', + 'body' => '' + )); + $result = $TestModel->create($data) && $TestModel->save(); + $this->assertFalse($result); + $this->assertTrue(!empty($TestModel->validationErrors)); + + $data = array('Article' => array( + 'id' => 1, + 'user_id' => '1', + 'title' => 'New First Article', + 'body' => '' + )); + $result = $TestModel->create($data) && $TestModel->save(); + $this->assertFalse($result); + + $data = array('Article' => array( + 'id' => 1, + 'title' => 'New First Article' + )); + $result = $TestModel->create() && $TestModel->save($data, false); + $this->assertFalse(empty($result)); + + $TestModel->recursive = -1; + $result = $TestModel->read(array('id', 'user_id', 'title', 'body', 'published'), 1); + $expected = array('Article' => array( + 'id' => '1', + 'user_id' => '1', + 'title' => 'New First Article', + 'body' => 'First Article Body', + 'published' => 'N' + )); + $this->assertEquals($expected, $result); + + $data = array('Article' => array( + 'id' => 1, + 'user_id' => '2', + 'title' => 'First Article', + 'body' => 'New First Article Body', + 'published' => 'Y' + )); + $result = $TestModel->create() && $TestModel->save($data, true, array('id', 'title', 'published')); + $this->assertFalse(empty($result)); + + $TestModel->recursive = -1; + $result = $TestModel->read(array('id', 'user_id', 'title', 'body', 'published'), 1); + $expected = array('Article' => array( + 'id' => '1', + 'user_id' => '1', + 'title' => 'First Article', + 'body' => 'First Article Body', + 'published' => 'Y' + )); + $this->assertEquals($expected, $result); + + $data = array( + 'Article' => array( + 'user_id' => '2', + 'title' => 'New Article', + 'body' => 'New Article Body', + 'created' => '2007-03-18 14:55:23', + 'updated' => '2007-03-18 14:57:31' + ), + 'Tag' => array('Tag' => array(1, 3)) + ); + $TestModel->create(); + $result = $TestModel->create() && $TestModel->save($data); + $this->assertFalse(empty($result)); + + $TestModel->recursive = 2; + $result = $TestModel->read(null, 4); + $expected = array( + 'Article' => array( + 'id' => '4', + 'user_id' => '2', + 'title' => 'New Article', + 'body' => 'New Article Body', + 'published' => 'N', + 'created' => '2007-03-18 14:55:23', + 'updated' => '2007-03-18 14:57:31' + ), + 'User' => array( + 'id' => '2', + 'user' => 'nate', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:18:23', + 'updated' => '2007-03-17 01:20:31' + ), + 'Comment' => array(), + 'Tag' => array( + array( + 'id' => '1', + 'tag' => 'tag1', + 'created' => '2007-03-18 12:22:23', + 'updated' => '2007-03-18 12:24:31' + ), + array( + 'id' => '3', + 'tag' => 'tag3', + 'created' => '2007-03-18 12:26:23', + 'updated' => '2007-03-18 12:28:31' + ))); + $this->assertEquals($expected, $result); + + $data = array('Comment' => array( + 'article_id' => '4', + 'user_id' => '1', + 'comment' => 'Comment New Article', + 'published' => 'Y', + 'created' => '2007-03-18 14:57:23', + 'updated' => '2007-03-18 14:59:31' + )); + $result = $TestModel->Comment->create() && $TestModel->Comment->save($data); + $this->assertFalse(empty($result)); + + $data = array('Attachment' => array( + 'comment_id' => '7', + 'attachment' => 'newattachment.zip', + 'created' => '2007-03-18 15:02:23', + 'updated' => '2007-03-18 15:04:31' + )); + $result = $TestModel->Comment->Attachment->save($data); + $this->assertFalse(empty($result)); + + $TestModel->recursive = 2; + $result = $TestModel->read(null, 4); + $expected = array( + 'Article' => array( + 'id' => '4', + 'user_id' => '2', + 'title' => 'New Article', + 'body' => 'New Article Body', + 'published' => 'N', + 'created' => '2007-03-18 14:55:23', + 'updated' => '2007-03-18 14:57:31' + ), + 'User' => array( + 'id' => '2', + 'user' => 'nate', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:18:23', + 'updated' => '2007-03-17 01:20:31' + ), + 'Comment' => array( + array( + 'id' => '7', + 'article_id' => '4', + 'user_id' => '1', + 'comment' => 'Comment New Article', + 'published' => 'Y', + 'created' => '2007-03-18 14:57:23', + 'updated' => '2007-03-18 14:59:31', + 'Article' => array( + 'id' => '4', + 'user_id' => '2', + 'title' => 'New Article', + 'body' => 'New Article Body', + 'published' => 'N', + 'created' => '2007-03-18 14:55:23', + 'updated' => '2007-03-18 14:57:31' + ), + 'User' => array( + 'id' => '1', + 'user' => 'mariano', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:16:23', + 'updated' => '2007-03-17 01:18:31' + ), + 'Attachment' => array( + 'id' => '2', + 'comment_id' => '7', + 'attachment' => 'newattachment.zip', + 'created' => '2007-03-18 15:02:23', + 'updated' => '2007-03-18 15:04:31' + ))), + 'Tag' => array( + array( + 'id' => '1', + 'tag' => 'tag1', + 'created' => '2007-03-18 12:22:23', + 'updated' => '2007-03-18 12:24:31' + ), + array( + 'id' => '3', + 'tag' => 'tag3', + 'created' => '2007-03-18 12:26:23', + 'updated' => '2007-03-18 12:28:31' + ))); + + $this->assertEquals($expected, $result); + } + +/** + * test that a null Id doesn't cause errors + * + * @return void + */ + public function testSaveWithNullId() { + $this->loadFixtures('User'); + $User = new User(); + $User->read(null, 1); + $User->data['User']['id'] = null; + $result = $User->save(array('password' => 'test')); + $this->assertFalse(empty($result)); + $this->assertTrue($User->id > 0); + + $User->read(null, 2); + $User->data['User']['id'] = null; + $result = $User->save(array('password' => 'test')); + $this->assertFalse(empty($result)); + $this->assertTrue($User->id > 0); + + $User->data['User'] = array('password' => 'something'); + $result = $User->save(); + $this->assertFalse(empty($result)); + $result = $User->read(); + $this->assertEquals('something', $User->data['User']['password']); + } + +/** + * testSaveWithSet method + * + * @return void + */ + public function testSaveWithSet() { + $this->loadFixtures('Article'); + $TestModel = new Article(); + + // Create record we will be updating later + + $data = array('Article' => array( + 'user_id' => '1', + 'title' => 'Fourth Article', + 'body' => 'Fourth Article Body', + 'published' => 'Y' + )); + $result = $TestModel->create() && $TestModel->save($data); + $this->assertFalse(empty($result)); + + // Check record we created + + $TestModel->recursive = -1; + $result = $TestModel->read(array('id', 'user_id', 'title', 'body', 'published'), 4); + $expected = array('Article' => array( + 'id' => '4', + 'user_id' => '1', + 'title' => 'Fourth Article', + 'body' => 'Fourth Article Body', + 'published' => 'Y' + )); + $this->assertEquals($expected, $result); + + // Create new record just to overlap Model->id on previously created record + + $data = array('Article' => array( + 'user_id' => '4', + 'title' => 'Fifth Article', + 'body' => 'Fifth Article Body', + 'published' => 'Y' + )); + $result = $TestModel->create() && $TestModel->save($data); + $this->assertFalse(empty($result)); + + $TestModel->recursive = -1; + $result = $TestModel->read(array('id', 'user_id', 'title', 'body', 'published'), 5); + $expected = array('Article' => array( + 'id' => '5', + 'user_id' => '4', + 'title' => 'Fifth Article', + 'body' => 'Fifth Article Body', + 'published' => 'Y' + )); + $this->assertEquals($expected, $result); + + // Go back and edit the first article we created, starting by checking it's still there + + $TestModel->recursive = -1; + $result = $TestModel->read(array('id', 'user_id', 'title', 'body', 'published'), 4); + $expected = array('Article' => array( + 'id' => '4', + 'user_id' => '1', + 'title' => 'Fourth Article', + 'body' => 'Fourth Article Body', + 'published' => 'Y' + )); + $this->assertEquals($expected, $result); + + // And now do the update with set() + + $data = array('Article' => array( + 'id' => '4', + 'title' => 'Fourth Article - New Title', + 'published' => 'N' + )); + $result = $TestModel->set($data) && $TestModel->save(); + $this->assertFalse(empty($result)); + + $TestModel->recursive = -1; + $result = $TestModel->read(array('id', 'user_id', 'title', 'body', 'published'), 4); + $expected = array('Article' => array( + 'id' => '4', + 'user_id' => '1', + 'title' => 'Fourth Article - New Title', + 'body' => 'Fourth Article Body', + 'published' => 'N' + )); + $this->assertEquals($expected, $result); + + $TestModel->recursive = -1; + $result = $TestModel->read(array('id', 'user_id', 'title', 'body', 'published'), 5); + $expected = array('Article' => array( + 'id' => '5', + 'user_id' => '4', + 'title' => 'Fifth Article', + 'body' => 'Fifth Article Body', + 'published' => 'Y' + )); + $this->assertEquals($expected, $result); + + $data = array('Article' => array('id' => '5', 'title' => 'Fifth Article - New Title 5')); + $result = ($TestModel->set($data) && $TestModel->save()); + $this->assertFalse(empty($result)); + + $TestModel->recursive = -1; + $result = $TestModel->read(array('id', 'user_id', 'title', 'body', 'published'), 5); + $expected = array('Article' => array( + 'id' => '5', + 'user_id' => '4', + 'title' => 'Fifth Article - New Title 5', + 'body' => 'Fifth Article Body', + 'published' => 'Y' + )); + $this->assertEquals($expected, $result); + + $TestModel->recursive = -1; + $result = $TestModel->find('all', array( + 'fields' => array('id', 'title'), + 'order' => array('Article.id' => 'ASC') + )); + $expected = array( + array('Article' => array('id' => 1, 'title' => 'First Article')), + array('Article' => array('id' => 2, 'title' => 'Second Article')), + array('Article' => array('id' => 3, 'title' => 'Third Article')), + array('Article' => array('id' => 4, 'title' => 'Fourth Article - New Title')), + array('Article' => array('id' => 5, 'title' => 'Fifth Article - New Title 5')) + ); + $this->assertEquals($expected, $result); + } + +/** + * testSaveWithNonExistentFields method + * + * @return void + */ + public function testSaveWithNonExistentFields() { + $this->loadFixtures('Article'); + $TestModel = new Article(); + $TestModel->recursive = -1; + + $data = array( + 'non_existent' => 'This field does not exist', + 'user_id' => '1', + 'title' => 'Fourth Article - New Title', + 'body' => 'Fourth Article Body', + 'published' => 'N' + ); + $result = $TestModel->create() && $TestModel->save($data); + $this->assertFalse(empty($result)); + + $expected = array('Article' => array( + 'id' => '4', + 'user_id' => '1', + 'title' => 'Fourth Article - New Title', + 'body' => 'Fourth Article Body', + 'published' => 'N' + )); + $result = $TestModel->read(array('id', 'user_id', 'title', 'body', 'published'), 4); + $this->assertEquals($expected, $result); + + $data = array( + 'user_id' => '1', + 'non_existent' => 'This field does not exist', + 'title' => 'Fifth Article - New Title', + 'body' => 'Fifth Article Body', + 'published' => 'N' + ); + $result = $TestModel->create() && $TestModel->save($data); + $this->assertFalse(empty($result)); + + $expected = array('Article' => array( + 'id' => '5', + 'user_id' => '1', + 'title' => 'Fifth Article - New Title', + 'body' => 'Fifth Article Body', + 'published' => 'N' + )); + $result = $TestModel->read(array('id', 'user_id', 'title', 'body', 'published'), 5); + $this->assertEquals($expected, $result); + } + +/** + * testSaveFromXml method + * + * @return void + */ + public function testSaveFromXml() { + $this->markTestSkipped('This feature needs to be fixed or dropped'); + $this->loadFixtures('Article'); + App::uses('Xml', 'Utility'); + + $Article = new Article(); + $result = $Article->save(Xml::build('
')); + $this->assertFalse(empty($result)); + $results = $Article->find('first', array('conditions' => array('Article.title' => 'test xml'))); + $this->assertFalse(empty($results)); + + $result = $Article->save(Xml::build('
testing6
')); + $this->assertFalse(empty($result)); + $results = $Article->find('first', array('conditions' => array('Article.title' => 'testing'))); + $this->assertFalse(empty($results)); + + $result = $Article->save(Xml::build('
testing with DOMDocument7
', array('return' => 'domdocument'))); + $this->assertFalse(empty($result)); + $results = $Article->find('first', array('conditions' => array('Article.title' => 'testing with DOMDocument'))); + $this->assertFalse(empty($results)); + } + +/** + * testSaveHabtm method + * + * @return void + */ + public function testSaveHabtm() { + $this->loadFixtures('Article', 'User', 'Comment', 'Tag', 'ArticlesTag'); + $TestModel = new Article(); + + $result = $TestModel->findById(2); + $expected = array( + 'Article' => array( + 'id' => '2', + 'user_id' => '3', + 'title' => 'Second Article', + 'body' => 'Second Article Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:41:23', + 'updated' => '2007-03-18 10:43:31' + ), + 'User' => array( + 'id' => '3', + 'user' => 'larry', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + 'created' => '2007-03-17 01:20:23', + 'updated' => '2007-03-17 01:22:31' + ), + 'Comment' => array( + array( + 'id' => '5', + 'article_id' => '2', + 'user_id' => '1', + 'comment' => 'First Comment for Second Article', + 'published' => 'Y', + 'created' => '2007-03-18 10:53:23', + 'updated' => '2007-03-18 10:55:31' + ), + array( + 'id' => '6', + 'article_id' => '2', + 'user_id' => '2', + 'comment' => 'Second Comment for Second Article', + 'published' => 'Y', + 'created' => '2007-03-18 10:55:23', + 'updated' => '2007-03-18 10:57:31' + )), + 'Tag' => array( + array( + 'id' => '1', + 'tag' => 'tag1', + 'created' => '2007-03-18 12:22:23', + 'updated' => '2007-03-18 12:24:31' + ), + array( + 'id' => '3', + 'tag' => 'tag3', + 'created' => '2007-03-18 12:26:23', + 'updated' => '2007-03-18 12:28:31' + ) + ) + ); + $this->assertEquals($expected, $result); + + $data = array( + 'Article' => array( + 'id' => '2', + 'title' => 'New Second Article' + ), + 'Tag' => array('Tag' => array(1, 2)) + ); + + $result = $TestModel->set($data); + $this->assertFalse(empty($result)); + $result = $TestModel->save(); + $this->assertFalse(empty($result)); + + $TestModel->unbindModel(array('belongsTo' => array('User'), 'hasMany' => array('Comment'))); + $result = $TestModel->find('first', array('fields' => array('id', 'user_id', 'title', 'body'), 'conditions' => array('Article.id' => 2))); + $expected = array( + 'Article' => array( + 'id' => '2', + 'user_id' => '3', + 'title' => 'New Second Article', + 'body' => 'Second Article Body' + ), + 'Tag' => array( + array( + 'id' => '1', + 'tag' => 'tag1', + 'created' => '2007-03-18 12:22:23', + 'updated' => '2007-03-18 12:24:31' + ), + array( + 'id' => '2', + 'tag' => 'tag2', + 'created' => '2007-03-18 12:24:23', + 'updated' => '2007-03-18 12:26:31' + ))); + $this->assertEquals($expected, $result); + + $data = array('Article' => array('id' => '2'), 'Tag' => array('Tag' => array(2, 3))); + $result = $TestModel->set($data); + $this->assertFalse(empty($result)); + + $result = $TestModel->save(); + $this->assertFalse(empty($result)); + + $TestModel->unbindModel(array( + 'belongsTo' => array('User'), + 'hasMany' => array('Comment') + )); + $result = $TestModel->find('first', array('fields' => array('id', 'user_id', 'title', 'body'), 'conditions' => array('Article.id' => 2))); + $expected = array( + 'Article' => array( + 'id' => '2', + 'user_id' => '3', + 'title' => 'New Second Article', + 'body' => 'Second Article Body' + ), + 'Tag' => array( + array( + 'id' => '2', + 'tag' => 'tag2', + 'created' => '2007-03-18 12:24:23', + 'updated' => '2007-03-18 12:26:31' + ), + array( + 'id' => '3', + 'tag' => 'tag3', + 'created' => '2007-03-18 12:26:23', + 'updated' => '2007-03-18 12:28:31' + ))); + $this->assertEquals($expected, $result); + + $data = array('Tag' => array('Tag' => array(1, 2, 3))); + + $result = $TestModel->set($data); + $this->assertFalse(empty($result)); + + $result = $TestModel->save(); + $this->assertFalse(empty($result)); + + $TestModel->unbindModel(array( + 'belongsTo' => array('User'), + 'hasMany' => array('Comment') + )); + $result = $TestModel->find('first', array('fields' => array('id', 'user_id', 'title', 'body'), 'conditions' => array('Article.id' => 2))); + $expected = array( + 'Article' => array( + 'id' => '2', + 'user_id' => '3', + 'title' => 'New Second Article', + 'body' => 'Second Article Body' + ), + 'Tag' => array( + array( + 'id' => '1', + 'tag' => 'tag1', + 'created' => '2007-03-18 12:22:23', + 'updated' => '2007-03-18 12:24:31' + ), + array( + 'id' => '2', + 'tag' => 'tag2', + 'created' => '2007-03-18 12:24:23', + 'updated' => '2007-03-18 12:26:31' + ), + array( + 'id' => '3', + 'tag' => 'tag3', + 'created' => '2007-03-18 12:26:23', + 'updated' => '2007-03-18 12:28:31' + ))); + $this->assertEquals($expected, $result); + + $data = array('Tag' => array('Tag' => array())); + $result = $TestModel->set($data); + $this->assertFalse(empty($result)); + + $result = $TestModel->save(); + $this->assertFalse(empty($result)); + + $data = array('Tag' => array('Tag' => '')); + $result = $TestModel->set($data); + $this->assertFalse(empty($result)); + + $result = $TestModel->save(); + $this->assertFalse(empty($result)); + + $TestModel->unbindModel(array( + 'belongsTo' => array('User'), + 'hasMany' => array('Comment') + )); + $result = $TestModel->find('first', array('fields' => array('id', 'user_id', 'title', 'body'), 'conditions' => array('Article.id' => 2))); + $expected = array( + 'Article' => array( + 'id' => '2', + 'user_id' => '3', + 'title' => 'New Second Article', + 'body' => 'Second Article Body' + ), + 'Tag' => array() + ); + $this->assertEquals($expected, $result); + + $data = array('Tag' => array('Tag' => array(2, 3))); + $result = $TestModel->set($data); + $this->assertFalse(empty($result)); + + $result = $TestModel->save(); + $this->assertFalse(empty($result)); + + $TestModel->unbindModel(array( + 'belongsTo' => array('User'), + 'hasMany' => array('Comment') + )); + $result = $TestModel->find('first', array('fields' => array('id', 'user_id', 'title', 'body'), 'conditions' => array('Article.id' => 2))); + $expected = array( + 'Article' => array( + 'id' => '2', + 'user_id' => '3', + 'title' => 'New Second Article', + 'body' => 'Second Article Body' + ), + 'Tag' => array( + array( + 'id' => '2', + 'tag' => 'tag2', + 'created' => '2007-03-18 12:24:23', + 'updated' => '2007-03-18 12:26:31' + ), + array( + 'id' => '3', + 'tag' => 'tag3', + 'created' => '2007-03-18 12:26:23', + 'updated' => '2007-03-18 12:28:31' + ))); + $this->assertEquals($expected, $result); + + $data = array( + 'Tag' => array( + 'Tag' => array(1, 2) + ), + 'Article' => array( + 'id' => '2', + 'title' => 'New Second Article' + )); + $result = $TestModel->set($data); + $this->assertFalse(empty($result)); + $result = $TestModel->save(); + $this->assertFalse(empty($result)); + + $TestModel->unbindModel(array( + 'belongsTo' => array('User'), + 'hasMany' => array('Comment') + )); + $result = $TestModel->find('first', array('fields' => array('id', 'user_id', 'title', 'body'), 'conditions' => array('Article.id' => 2))); + $expected = array( + 'Article' => array( + 'id' => '2', + 'user_id' => '3', + 'title' => 'New Second Article', + 'body' => 'Second Article Body' + ), + 'Tag' => array( + array( + 'id' => '1', + 'tag' => 'tag1', + 'created' => '2007-03-18 12:22:23', + 'updated' => '2007-03-18 12:24:31' + ), + array( + 'id' => '2', + 'tag' => 'tag2', + 'created' => '2007-03-18 12:24:23', + 'updated' => '2007-03-18 12:26:31' + ))); + $this->assertEquals($expected, $result); + + $data = array( + 'Tag' => array( + 'Tag' => array(1, 2) + ), + 'Article' => array( + 'id' => '2', + 'title' => 'New Second Article Title' + )); + $result = $TestModel->set($data); + $this->assertFalse(empty($result)); + $result = $TestModel->save(); + $this->assertFalse(empty($result)); + + $TestModel->unbindModel(array( + 'belongsTo' => array('User'), + 'hasMany' => array('Comment') + )); + $result = $TestModel->find('first', array('fields' => array('id', 'user_id', 'title', 'body'), 'conditions' => array('Article.id' => 2))); + $expected = array( + 'Article' => array( + 'id' => '2', + 'user_id' => '3', + 'title' => 'New Second Article Title', + 'body' => 'Second Article Body' + ), + 'Tag' => array( + array( + 'id' => '1', + 'tag' => 'tag1', + 'created' => '2007-03-18 12:22:23', + 'updated' => '2007-03-18 12:24:31' + ), + array( + 'id' => '2', + 'tag' => 'tag2', + 'created' => '2007-03-18 12:24:23', + 'updated' => '2007-03-18 12:26:31' + ) + ) + ); + $this->assertEquals($expected, $result); + + $data = array( + 'Tag' => array( + 'Tag' => array(2, 3) + ), + 'Article' => array( + 'id' => '2', + 'title' => 'Changed Second Article' + )); + $result = $TestModel->set($data); + $this->assertFalse(empty($result)); + $result = $TestModel->save(); + $this->assertFalse(empty($result)); + + $TestModel->unbindModel(array( + 'belongsTo' => array('User'), + 'hasMany' => array('Comment') + )); + $result = $TestModel->find('first', array('fields' => array('id', 'user_id', 'title', 'body'), 'conditions' => array('Article.id' => 2))); + $expected = array( + 'Article' => array( + 'id' => '2', + 'user_id' => '3', + 'title' => 'Changed Second Article', + 'body' => 'Second Article Body' + ), + 'Tag' => array( + array( + 'id' => '2', + 'tag' => 'tag2', + 'created' => '2007-03-18 12:24:23', + 'updated' => '2007-03-18 12:26:31' + ), + array( + 'id' => '3', + 'tag' => 'tag3', + 'created' => '2007-03-18 12:26:23', + 'updated' => '2007-03-18 12:28:31' + ) + ) + ); + $this->assertEquals($expected, $result); + + $data = array( + 'Tag' => array( + 'Tag' => array(1, 3) + ), + 'Article' => array('id' => '2'), + ); + + $result = $TestModel->set($data); + $this->assertFalse(empty($result)); + + $result = $TestModel->save(); + $this->assertFalse(empty($result)); + + $TestModel->unbindModel(array( + 'belongsTo' => array('User'), + 'hasMany' => array('Comment') + )); + $result = $TestModel->find('first', array('fields' => array('id', 'user_id', 'title', 'body'), 'conditions' => array('Article.id' => 2))); + $expected = array( + 'Article' => array( + 'id' => '2', + 'user_id' => '3', + 'title' => 'Changed Second Article', + 'body' => 'Second Article Body' + ), + 'Tag' => array( + array( + 'id' => '1', + 'tag' => 'tag1', + 'created' => '2007-03-18 12:22:23', + 'updated' => '2007-03-18 12:24:31' + ), + array( + 'id' => '3', + 'tag' => 'tag3', + 'created' => '2007-03-18 12:26:23', + 'updated' => '2007-03-18 12:28:31' + ))); + $this->assertEquals($expected, $result); + + $data = array( + 'Article' => array( + 'id' => 10, + 'user_id' => '2', + 'title' => 'New Article With Tags and fieldList', + 'body' => 'New Article Body with Tags and fieldList', + 'created' => '2007-03-18 14:55:23', + 'updated' => '2007-03-18 14:57:31' + ), + 'Tag' => array( + 'Tag' => array(1, 2, 3) + ) + ); + $result = $TestModel->create() + && $TestModel->save($data, true, array('user_id', 'title', 'published')); + $this->assertFalse(empty($result)); + + $TestModel->unbindModel(array( + 'belongsTo' => array('User'), + 'hasMany' => array('Comment') + )); + $result = $TestModel->read(); + $expected = array( + 'Article' => array( + 'id' => 4, + 'user_id' => 2, + 'title' => 'New Article With Tags and fieldList', + 'body' => '', + 'published' => 'N', + 'created' => '', + 'updated' => '' + ), + 'Tag' => array( + 0 => array( + 'id' => 1, + 'tag' => 'tag1', + 'created' => '2007-03-18 12:22:23', + 'updated' => '2007-03-18 12:24:31' + ), + 1 => array( + 'id' => 2, + 'tag' => 'tag2', + 'created' => '2007-03-18 12:24:23', + 'updated' => '2007-03-18 12:26:31' + ), + 2 => array( + 'id' => 3, + 'tag' => 'tag3', + 'created' => '2007-03-18 12:26:23', + 'updated' => '2007-03-18 12:28:31' + ))); + $this->assertEquals($expected, $result); + + $this->loadFixtures('JoinA', 'JoinC', 'JoinAC', 'JoinB', 'JoinAB'); + $TestModel = new JoinA(); + $TestModel->hasBelongsToMany = array('JoinC' => array('unique' => true)); + $data = array( + 'JoinA' => array( + 'id' => 1, + 'name' => 'Join A 1', + 'body' => 'Join A 1 Body', + ), + 'JoinC' => array( + 'JoinC' => array( + array('join_c_id' => 2, 'other' => 'new record'), + array('join_c_id' => 3, 'other' => 'new record') + ) + ) + ); + $TestModel->save($data); + $result = $TestModel->read(null, 1); + $expected = array(4, 5); + $this->assertEquals($expected, Hash::extract($result, 'JoinC.{n}.JoinAsJoinC.id')); + $expected = array('new record', 'new record'); + $this->assertEquals($expected, Hash::extract($result, 'JoinC.{n}.JoinAsJoinC.other')); + } + +/** + * testSaveHabtmNoPrimaryData method + * + * @return void + */ + public function testSaveHabtmNoPrimaryData() { + $this->loadFixtures('Article', 'User', 'Comment', 'Tag', 'ArticlesTag'); + $TestModel = new Article(); + + $TestModel->unbindModel(array('belongsTo' => array('User'), 'hasMany' => array('Comment')), false); + $result = $TestModel->findById(2); + $expected = array( + 'Article' => array( + 'id' => '2', + 'user_id' => '3', + 'title' => 'Second Article', + 'body' => 'Second Article Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:41:23', + 'updated' => '2007-03-18 10:43:31' + ), + 'Tag' => array( + array( + 'id' => '1', + 'tag' => 'tag1', + 'created' => '2007-03-18 12:22:23', + 'updated' => '2007-03-18 12:24:31' + ), + array( + 'id' => '3', + 'tag' => 'tag3', + 'created' => '2007-03-18 12:26:23', + 'updated' => '2007-03-18 12:28:31' + ) + ) + ); + $this->assertEquals($expected, $result); + + $TestModel->id = 2; + $data = array('Tag' => array('Tag' => array(2))); + $TestModel->save($data); + + $result = $TestModel->findById(2); + $expected = array( + 'Article' => array( + 'id' => '2', + 'user_id' => '3', + 'title' => 'Second Article', + 'body' => 'Second Article Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:41:23', + 'updated' => self::date() + ), + 'Tag' => array( + array( + 'id' => '2', + 'tag' => 'tag2', + 'created' => '2007-03-18 12:24:23', + 'updated' => '2007-03-18 12:26:31' + ) + ) + ); + $this->assertEquals($expected, $result); + + $this->loadFixtures('Portfolio', 'Item', 'ItemsPortfolio'); + $TestModel = new Portfolio(); + $result = $TestModel->findById(2); + $expected = array( + 'Portfolio' => array( + 'id' => 2, + 'seller_id' => 1, + 'name' => 'Portfolio 2' + ), + 'Item' => array( + array( + 'id' => 2, + 'syfile_id' => 2, + 'published' => '', + 'name' => 'Item 2', + 'ItemsPortfolio' => array( + 'id' => 2, + 'item_id' => 2, + 'portfolio_id' => 2 + ) + ), + array( + 'id' => 6, + 'syfile_id' => 6, + 'published' => '', + 'name' => 'Item 6', + 'ItemsPortfolio' => array( + 'id' => 6, + 'item_id' => 6, + 'portfolio_id' => 2 + ) + ) + ) + ); + $this->assertEquals($expected, $result); + + $data = array('Item' => array('Item' => array(1, 2))); + $TestModel->id = 2; + $TestModel->save($data); + $result = $TestModel->findById(2); + $result['Item'] = Hash::sort($result['Item'], '{n}.id', 'asc'); + $expected = array( + 'Portfolio' => array( + 'id' => 2, + 'seller_id' => 1, + 'name' => 'Portfolio 2' + ), + 'Item' => array( + array( + 'id' => 1, + 'syfile_id' => 1, + 'published' => '', + 'name' => 'Item 1', + 'ItemsPortfolio' => array( + 'id' => 7, + 'item_id' => 1, + 'portfolio_id' => 2 + ) + ), + array( + 'id' => 2, + 'syfile_id' => 2, + 'published' => '', + 'name' => 'Item 2', + 'ItemsPortfolio' => array( + 'id' => 8, + 'item_id' => 2, + 'portfolio_id' => 2 + ) + ) + ) + ); + $this->assertEquals($expected, $result); + } + +/** + * testSaveHabtmCustomKeys method + * + * @return void + */ + public function testSaveHabtmCustomKeys() { + $this->loadFixtures('Story', 'StoriesTag', 'Tag'); + $Story = new Story(); + + $data = array( + 'Story' => array('story' => '1'), + 'Tag' => array( + 'Tag' => array(2, 3) + )); + $result = $Story->set($data); + $this->assertFalse(empty($result)); + + $result = $Story->save(); + $this->assertFalse(empty($result)); + + $result = $Story->find('all', array('order' => array('Story.story'))); + $expected = array( + array( + 'Story' => array( + 'story' => 1, + 'title' => 'First Story' + ), + 'Tag' => array( + array( + 'id' => 2, + 'tag' => 'tag2', + 'created' => '2007-03-18 12:24:23', + 'updated' => '2007-03-18 12:26:31' + ), + array( + 'id' => 3, + 'tag' => 'tag3', + 'created' => '2007-03-18 12:26:23', + 'updated' => '2007-03-18 12:28:31' + ))), + array( + 'Story' => array( + 'story' => 2, + 'title' => 'Second Story' + ), + 'Tag' => array() + )); + $this->assertEquals($expected, $result); + } + +/** + * test that saving habtm records respects conditions set in the 'conditions' key + * for the association. + * + * @return void + */ + public function testHabtmSaveWithConditionsInAssociation() { + $this->loadFixtures('JoinThing', 'Something', 'SomethingElse'); + $Something = new Something(); + $Something->unbindModel(array('hasAndBelongsToMany' => array('SomethingElse')), false); + + $Something->bindModel(array( + 'hasAndBelongsToMany' => array( + 'DoomedSomethingElse' => array( + 'className' => 'SomethingElse', + 'joinTable' => 'join_things', + 'conditions' => array('JoinThing.doomed' => true), + 'unique' => true + ), + 'NotDoomedSomethingElse' => array( + 'className' => 'SomethingElse', + 'joinTable' => 'join_things', + 'conditions' => array('JoinThing.doomed' => 0), + 'unique' => true + ) + ) + ), false); + $result = $Something->read(null, 1); + $this->assertTrue(empty($result['NotDoomedSomethingElse'])); + $this->assertEquals(1, count($result['DoomedSomethingElse'])); + + $data = array( + 'Something' => array('id' => 1), + 'NotDoomedSomethingElse' => array( + 'NotDoomedSomethingElse' => array( + array('something_else_id' => 2, 'doomed' => 0), + array('something_else_id' => 3, 'doomed' => 0) + ) + ) + ); + $Something->create($data); + $result = $Something->save(); + $this->assertFalse(empty($result)); + + $result = $Something->read(null, 1); + $this->assertEquals(2, count($result['NotDoomedSomethingElse'])); + $this->assertEquals(1, count($result['DoomedSomethingElse'])); + } + +/** + * testHabtmSaveKeyResolution method + * + * @return void + */ + public function testHabtmSaveKeyResolution() { + $this->loadFixtures('Apple', 'Device', 'ThePaperMonkies'); + $ThePaper = new ThePaper(); + + $ThePaper->id = 1; + $ThePaper->save(array('Monkey' => array(2, 3))); + + $result = $ThePaper->findById(1); + $expected = array( + array( + 'id' => '2', + 'device_type_id' => '1', + 'name' => 'Device 2', + 'typ' => '1' + ), + array( + 'id' => '3', + 'device_type_id' => '1', + 'name' => 'Device 3', + 'typ' => '2' + )); + $this->assertEquals($expected, $result['Monkey']); + + $ThePaper->id = 2; + $ThePaper->save(array('Monkey' => array(1, 2, 3))); + + $result = $ThePaper->findById(2); + $expected = array( + array( + 'id' => '1', + 'device_type_id' => '1', + 'name' => 'Device 1', + 'typ' => '1' + ), + array( + 'id' => '2', + 'device_type_id' => '1', + 'name' => 'Device 2', + 'typ' => '1' + ), + array( + 'id' => '3', + 'device_type_id' => '1', + 'name' => 'Device 3', + 'typ' => '2' + )); + $this->assertEquals($expected, $result['Monkey']); + + $ThePaper->id = 2; + $ThePaper->save(array('Monkey' => array(1, 3))); + + $result = $ThePaper->findById(2); + $expected = array( + array( + 'id' => '1', + 'device_type_id' => '1', + 'name' => 'Device 1', + 'typ' => '1' + ), + array( + 'id' => '3', + 'device_type_id' => '1', + 'name' => 'Device 3', + 'typ' => '2' + )); + $this->assertEquals($expected, $result['Monkey']); + + $result = $ThePaper->findById(1); + $expected = array( + array( + 'id' => '2', + 'device_type_id' => '1', + 'name' => 'Device 2', + 'typ' => '1' + ), + array( + 'id' => '3', + 'device_type_id' => '1', + 'name' => 'Device 3', + 'typ' => '2' + )); + $this->assertEquals($expected, $result['Monkey']); + } + +/** + * testCreationOfEmptyRecord method + * + * @return void + */ + public function testCreationOfEmptyRecord() { + $this->loadFixtures('Author'); + $TestModel = new Author(); + $this->assertEquals(4, $TestModel->find('count')); + + $TestModel->deleteAll(true, false, false); + $this->assertEquals(0, $TestModel->find('count')); + + $result = $TestModel->save(); + $this->assertTrue(isset($result['Author']['created'])); + $this->assertTrue(isset($result['Author']['updated'])); + $this->assertEquals(1, $TestModel->find('count')); + } + +/** + * testCreateWithPKFiltering method + * + * @return void + */ + public function testCreateWithPKFiltering() { + $TestModel = new Article(); + $data = array( + 'id' => 5, + 'user_id' => 2, + 'title' => 'My article', + 'body' => 'Some text' + ); + + $result = $TestModel->create($data); + $expected = array( + 'Article' => array( + 'published' => 'N', + 'id' => 5, + 'user_id' => 2, + 'title' => 'My article', + 'body' => 'Some text' + )); + + $this->assertEquals($expected, $result); + $this->assertEquals(5, $TestModel->id); + + $result = $TestModel->create($data, true); + $expected = array( + 'Article' => array( + 'published' => 'N', + 'id' => false, + 'user_id' => 2, + 'title' => 'My article', + 'body' => 'Some text' + )); + + $this->assertEquals($expected, $result); + $this->assertFalse($TestModel->id); + + $result = $TestModel->create(array('Article' => $data), true); + $expected = array( + 'Article' => array( + 'published' => 'N', + 'id' => false, + 'user_id' => 2, + 'title' => 'My article', + 'body' => 'Some text' + )); + + $this->assertEquals($expected, $result); + $this->assertFalse($TestModel->id); + + $data = array( + 'id' => 6, + 'user_id' => 2, + 'title' => 'My article', + 'body' => 'Some text', + 'created' => '1970-01-01 00:00:00', + 'updated' => '1970-01-01 12:00:00', + 'modified' => '1970-01-01 12:00:00' + ); + + $result = $TestModel->create($data); + $expected = array( + 'Article' => array( + 'published' => 'N', + 'id' => 6, + 'user_id' => 2, + 'title' => 'My article', + 'body' => 'Some text', + 'created' => '1970-01-01 00:00:00', + 'updated' => '1970-01-01 12:00:00', + 'modified' => '1970-01-01 12:00:00' + )); + $this->assertEquals($expected, $result); + $this->assertEquals(6, $TestModel->id); + + $result = $TestModel->create(array( + 'Article' => array_diff_key($data, array( + 'created' => true, + 'updated' => true, + 'modified' => true + ))), true); + $expected = array( + 'Article' => array( + 'published' => 'N', + 'id' => false, + 'user_id' => 2, + 'title' => 'My article', + 'body' => 'Some text' + )); + $this->assertEquals($expected, $result); + $this->assertFalse($TestModel->id); + } + +/** + * testCreationWithMultipleData method + * + * @return void + */ + public function testCreationWithMultipleData() { + $this->loadFixtures('Article', 'Comment'); + $Article = new Article(); + $Comment = new Comment(); + + $articles = $Article->find('all', array( + 'fields' => array('id','title'), + 'recursive' => -1, + 'order' => array('Article.id' => 'ASC') + )); + $expected = array( + array('Article' => array( + 'id' => 1, + 'title' => 'First Article' + )), + array('Article' => array( + 'id' => 2, + 'title' => 'Second Article' + )), + array('Article' => array( + 'id' => 3, + 'title' => 'Third Article' + ))); + $this->assertEquals($expected, $articles); + + $comments = $Comment->find('all', array( + 'fields' => array('id','article_id','user_id','comment','published'), + 'recursive' => -1, + 'order' => array('Comment.id' => 'ASC') + )); + $expected = array( + array('Comment' => array( + 'id' => 1, + 'article_id' => 1, + 'user_id' => 2, + 'comment' => 'First Comment for First Article', + 'published' => 'Y' + )), + array('Comment' => array( + 'id' => 2, + 'article_id' => 1, + 'user_id' => 4, + 'comment' => 'Second Comment for First Article', + 'published' => 'Y' + )), + array('Comment' => array( + 'id' => 3, + 'article_id' => 1, + 'user_id' => 1, + 'comment' => 'Third Comment for First Article', + 'published' => 'Y' + )), + array('Comment' => array( + 'id' => 4, + 'article_id' => 1, + 'user_id' => 1, + 'comment' => 'Fourth Comment for First Article', + 'published' => 'N' + )), + array('Comment' => array( + 'id' => 5, + 'article_id' => 2, + 'user_id' => 1, + 'comment' => 'First Comment for Second Article', + 'published' => 'Y' + )), + array('Comment' => array( + 'id' => 6, + 'article_id' => 2, + 'user_id' => 2, + 'comment' => 'Second Comment for Second Article', + 'published' => 'Y' + ))); + $this->assertEquals($expected, $comments); + + $data = array( + 'Comment' => array( + 'article_id' => 2, + 'user_id' => 4, + 'comment' => 'Brand New Comment', + 'published' => 'N' + ), + 'Article' => array( + 'id' => 2, + 'title' => 'Second Article Modified' + )); + $result = $Comment->create($data); + $this->assertFalse(empty($result)); + + $result = $Comment->save(); + $this->assertFalse(empty($result)); + + $articles = $Article->find('all', array( + 'fields' => array('id','title'), + 'recursive' => -1, + 'order' => array('Article.id' => 'ASC') + )); + $expected = array( + array('Article' => array( + 'id' => 1, + 'title' => 'First Article' + )), + array('Article' => array( + 'id' => 2, + 'title' => 'Second Article' + )), + array('Article' => array( + 'id' => 3, + 'title' => 'Third Article' + ))); + $this->assertEquals($expected, $articles); + + $comments = $Comment->find('all', array( + 'fields' => array('id','article_id','user_id','comment','published'), + 'recursive' => -1, + 'order' => array('Comment.id' => 'ASC') + )); + $expected = array( + array('Comment' => array( + 'id' => 1, + 'article_id' => 1, + 'user_id' => 2, + 'comment' => 'First Comment for First Article', + 'published' => 'Y' + )), + array('Comment' => array( + 'id' => 2, + 'article_id' => 1, + 'user_id' => 4, + 'comment' => 'Second Comment for First Article', + 'published' => 'Y' + )), + array('Comment' => array( + 'id' => 3, + 'article_id' => 1, + 'user_id' => 1, + 'comment' => 'Third Comment for First Article', + 'published' => 'Y' + )), + array('Comment' => array( + 'id' => 4, + 'article_id' => 1, + 'user_id' => 1, + 'comment' => 'Fourth Comment for First Article', + 'published' => 'N' + )), + array('Comment' => array( + 'id' => 5, + 'article_id' => 2, + 'user_id' => 1, + 'comment' => 'First Comment for Second Article', + 'published' => 'Y' + )), + array('Comment' => array( + 'id' => 6, + 'article_id' => 2, + 'user_id' => 2, 'comment' => + 'Second Comment for Second Article', + 'published' => 'Y' + )), + array('Comment' => array( + 'id' => 7, + 'article_id' => 2, + 'user_id' => 4, + 'comment' => 'Brand New Comment', + 'published' => 'N' + ))); + $this->assertEquals($expected, $comments); + } + +/** + * testCreationWithMultipleDataSameModel method + * + * @return void + */ + public function testCreationWithMultipleDataSameModel() { + $this->loadFixtures('Article'); + $Article = new Article(); + $SecondaryArticle = new Article(); + + $result = $Article->field('title', array('id' => 1)); + $this->assertEquals('First Article', $result); + + $data = array( + 'Article' => array( + 'user_id' => 2, + 'title' => 'Brand New Article', + 'body' => 'Brand New Article Body', + 'published' => 'Y' + ), + 'SecondaryArticle' => array( + 'id' => 1 + )); + + $Article->create(); + $result = $Article->save($data); + $this->assertFalse(empty($result)); + + $result = $Article->getInsertID(); + $this->assertTrue(!empty($result)); + + $result = $Article->field('title', array('id' => 1)); + $this->assertEquals('First Article', $result); + + $articles = $Article->find('all', array( + 'fields' => array('id','title'), + 'recursive' => -1, + 'order' => array('Article.id' => 'ASC') + )); + $expected = array( + array('Article' => array( + 'id' => 1, + 'title' => 'First Article' + )), + array('Article' => array( + 'id' => 2, + 'title' => 'Second Article' + )), + array('Article' => array( + 'id' => 3, + 'title' => 'Third Article' + )), + array('Article' => array( + 'id' => 4, + 'title' => 'Brand New Article' + ))); + + $this->assertEquals($expected, $articles); + } + +/** + * testCreationWithMultipleDataSameModelManualInstances method + * + * @return void + */ + public function testCreationWithMultipleDataSameModelManualInstances() { + $this->loadFixtures('PrimaryModel'); + $Primary = new PrimaryModel(); + $Secondary = new PrimaryModel(); + + $result = $Primary->field('primary_name', array('id' => 1)); + $this->assertEquals('Primary Name Existing', $result); + + $data = array( + 'PrimaryModel' => array( + 'primary_name' => 'Primary Name New' + ), + 'SecondaryModel' => array( + 'id' => array(1) + )); + + $Primary->create(); + $result = $Primary->save($data); + $this->assertFalse(empty($result)); + + $result = $Primary->field('primary_name', array('id' => 1)); + $this->assertEquals('Primary Name Existing', $result); + + $result = $Primary->getInsertID(); + $this->assertTrue(!empty($result)); + + $result = $Primary->field('primary_name', array('id' => $result)); + $this->assertEquals('Primary Name New', $result); + + $result = $Primary->find('count'); + $this->assertEquals(2, $result); + } + +/** + * testRecordExists method + * + * @return void + */ + public function testRecordExists() { + $this->loadFixtures('User'); + $TestModel = new User(); + + $this->assertFalse($TestModel->exists()); + $TestModel->read(null, 1); + $this->assertTrue($TestModel->exists()); + $TestModel->create(); + $this->assertFalse($TestModel->exists()); + $TestModel->id = 4; + $this->assertTrue($TestModel->exists()); + + $TestModel = new TheVoid(); + $this->assertFalse($TestModel->exists()); + } + +/** + * testRecordExistsMissingTable method + * + * @expectedException PDOException + * @return void + */ + public function testRecordExistsMissingTable() { + $TestModel = new TheVoid(); + $TestModel->id = 5; + $TestModel->exists(); + } + +/** + * testUpdateExisting method + * + * @return void + */ + public function testUpdateExisting() { + $this->loadFixtures('User', 'Article', 'Comment'); + $TestModel = new User(); + $TestModel->create(); + + $TestModel->save(array( + 'User' => array( + 'user' => 'some user', + 'password' => 'some password' + ))); + $this->assertTrue(is_int($TestModel->id) || (intval($TestModel->id) === 5)); + $id = $TestModel->id; + + $TestModel->save(array( + 'User' => array( + 'user' => 'updated user' + ))); + $this->assertEquals($id, $TestModel->id); + + $result = $TestModel->findById($id); + $this->assertEquals('updated user', $result['User']['user']); + $this->assertEquals('some password', $result['User']['password']); + + $Article = new Article(); + $Comment = new Comment(); + $data = array( + 'Comment' => array( + 'id' => 1, + 'comment' => 'First Comment for First Article' + ), + 'Article' => array( + 'id' => 2, + 'title' => 'Second Article' + )); + + $result = $Article->save($data); + $this->assertFalse(empty($result)); + + $result = $Comment->save($data); + $this->assertFalse(empty($result)); + } + +/** + * test updating records and saving blank values. + * + * @return void + */ + public function testUpdateSavingBlankValues() { + $this->loadFixtures('Article'); + $Article = new Article(); + $Article->validate = array(); + $Article->create(); + $result = $Article->save(array( + 'id' => 1, + 'title' => '', + 'body' => '' + )); + $this->assertTrue((bool)$result); + $result = $Article->find('first', array('conditions' => array('Article.id' => 1))); + $this->assertEquals('', $result['Article']['title'], 'Title is not blank'); + $this->assertEquals('', $result['Article']['body'], 'Body is not blank'); + } + +/** + * testUpdateMultiple method + * + * @return void + */ + public function testUpdateMultiple() { + $this->loadFixtures('Comment', 'Article', 'User', 'CategoryThread'); + $TestModel = new Comment(); + $result = Hash::extract($TestModel->find('all'), '{n}.Comment.user_id'); + $expected = array('2', '4', '1', '1', '1', '2'); + $this->assertEquals($expected, $result); + + $TestModel->updateAll(array('Comment.user_id' => 5), array('Comment.user_id' => 2)); + $result = Hash::combine($TestModel->find('all'), '{n}.Comment.id', '{n}.Comment.user_id'); + $expected = array(1 => 5, 2 => 4, 3 => 1, 4 => 1, 5 => 1, 6 => 5); + $this->assertEquals($expected, $result); + + $result = $TestModel->updateAll( + array('Comment.comment' => "'Updated today'"), + array('Comment.user_id' => 5) + ); + $this->assertFalse(empty($result)); + $result = Hash::extract( + $TestModel->find('all', array( + 'conditions' => array( + 'Comment.user_id' => 5 + ))), + '{n}.Comment.comment' + ); + $expected = array_fill(0, 2, 'Updated today'); + $this->assertEquals($expected, $result); + } + +/** + * testHabtmUuidWithUuidId method + * + * @return void + */ + public function testHabtmUuidWithUuidId() { + $this->loadFixtures('Uuidportfolio', 'Uuiditem', 'UuiditemsUuidportfolio', 'UuiditemsUuidportfolioNumericid'); + $TestModel = new Uuidportfolio(); + + $data = array('Uuidportfolio' => array('name' => 'Portfolio 3')); + $data['Uuiditem']['Uuiditem'] = array('483798c8-c7cc-430e-8cf9-4fcc40cf8569'); + $TestModel->create($data); + $TestModel->save(); + $id = $TestModel->id; + $result = $TestModel->read(null, $id); + $this->assertEquals(1, count($result['Uuiditem'])); + $this->assertEquals(36, strlen($result['Uuiditem'][0]['UuiditemsUuidportfolio']['id'])); + } + +/** + * test HABTM saving when join table has no primary key and only 2 columns. + * + * @return void + */ + public function testHabtmSavingWithNoPrimaryKeyUuidJoinTable() { + $this->loadFixtures('UuidTag', 'Fruit', 'FruitsUuidTag'); + $Fruit = new Fruit(); + $data = array( + 'Fruit' => array( + 'color' => 'Red', + 'shape' => 'Heart-shaped', + 'taste' => 'sweet', + 'name' => 'Strawberry', + ), + 'UuidTag' => array( + 'UuidTag' => array( + '481fc6d0-b920-43e0-e50f-6d1740cf8569' + ) + ) + ); + $result = $Fruit->save($data); + $this->assertFalse(empty($result)); + } + +/** + * test HABTM saving when join table has no primary key and only 2 columns, no with model is used. + * + * @return void + */ + public function testHabtmSavingWithNoPrimaryKeyUuidJoinTableNoWith() { + $this->loadFixtures('UuidTag', 'Fruit', 'FruitsUuidTag'); + $Fruit = new FruitNoWith(); + $data = array( + 'Fruit' => array( + 'color' => 'Red', + 'shape' => 'Heart-shaped', + 'taste' => 'sweet', + 'name' => 'Strawberry', + ), + 'UuidTag' => array( + 'UuidTag' => array( + '481fc6d0-b920-43e0-e50f-6d1740cf8569' + ) + ) + ); + $result = $Fruit->save($data); + $this->assertFalse(empty($result)); + } + +/** + * testHabtmUuidWithNumericId method + * + * @return void + */ + public function testHabtmUuidWithNumericId() { + $this->loadFixtures('Uuidportfolio', 'Uuiditem', 'UuiditemsUuidportfolioNumericid'); + $TestModel = new Uuiditem(); + + $data = array('Uuiditem' => array('name' => 'Item 7', 'published' => 0)); + $data['Uuidportfolio']['Uuidportfolio'] = array('480af662-eb8c-47d3-886b-230540cf8569'); + $TestModel->create($data); + $TestModel->save(); + $id = $TestModel->id; + $result = $TestModel->read(null, $id); + $this->assertEquals(1, count($result['Uuidportfolio'])); + } + +/** + * testSaveMultipleHabtm method + * + * @return void + */ + public function testSaveMultipleHabtm() { + $this->loadFixtures('JoinA', 'JoinB', 'JoinC', 'JoinAB', 'JoinAC'); + $TestModel = new JoinA(); + $result = $TestModel->findById(1); + + $expected = array( + 'JoinA' => array( + 'id' => 1, + 'name' => 'Join A 1', + 'body' => 'Join A 1 Body', + 'created' => '2008-01-03 10:54:23', + 'updated' => '2008-01-03 10:54:23' + ), + 'JoinB' => array( + 0 => array( + 'id' => 2, + 'name' => 'Join B 2', + 'created' => '2008-01-03 10:55:02', + 'updated' => '2008-01-03 10:55:02', + 'JoinAsJoinB' => array( + 'id' => 1, + 'join_a_id' => 1, + 'join_b_id' => 2, + 'other' => 'Data for Join A 1 Join B 2', + 'created' => '2008-01-03 10:56:33', + 'updated' => '2008-01-03 10:56:33' + ))), + 'JoinC' => array( + 0 => array( + 'id' => 2, + 'name' => 'Join C 2', + 'created' => '2008-01-03 10:56:12', + 'updated' => '2008-01-03 10:56:12', + 'JoinAsJoinC' => array( + 'id' => 1, + 'join_a_id' => 1, + 'join_c_id' => 2, + 'other' => 'Data for Join A 1 Join C 2', + 'created' => '2008-01-03 10:57:22', + 'updated' => '2008-01-03 10:57:22' + )))); + + $this->assertEquals($expected, $result); + + $TestModel->id = 1; + $data = array( + 'JoinA' => array( + 'id' => '1', + 'name' => 'New name for Join A 1', + 'updated' => self::date() + ), + 'JoinB' => array( + array( + 'id' => 1, + 'join_b_id' => 2, + 'other' => 'New data for Join A 1 Join B 2', + 'created' => self::date(), + 'updated' => self::date() + )), + 'JoinC' => array( + array( + 'id' => 1, + 'join_c_id' => 2, + 'other' => 'New data for Join A 1 Join C 2', + 'created' => self::date(), + 'updated' => self::date() + ))); + + $TestModel->set($data); + $TestModel->save(); + + $result = $TestModel->findById(1); + $expected = array( + 'JoinA' => array( + 'id' => 1, + 'name' => 'New name for Join A 1', + 'body' => 'Join A 1 Body', + 'created' => '2008-01-03 10:54:23', + 'updated' => self::date() + ), + 'JoinB' => array( + 0 => array( + 'id' => 2, + 'name' => 'Join B 2', + 'created' => '2008-01-03 10:55:02', + 'updated' => '2008-01-03 10:55:02', + 'JoinAsJoinB' => array( + 'id' => 1, + 'join_a_id' => 1, + 'join_b_id' => 2, + 'other' => 'New data for Join A 1 Join B 2', + 'created' => self::date(), + 'updated' => self::date() + ))), + 'JoinC' => array( + 0 => array( + 'id' => 2, + 'name' => 'Join C 2', + 'created' => '2008-01-03 10:56:12', + 'updated' => '2008-01-03 10:56:12', + 'JoinAsJoinC' => array( + 'id' => 1, + 'join_a_id' => 1, + 'join_c_id' => 2, + 'other' => 'New data for Join A 1 Join C 2', + 'created' => self::date(), + 'updated' => self::date() + )))); + + $this->assertEquals($expected, $result); + } + +/** + * testSaveAll method + * + * @return void + */ + public function testSaveAll() { + $this->loadFixtures('Post', 'Author', 'Comment', 'Attachment', 'Article', 'User'); + $TestModel = new Post(); + + $result = $TestModel->find('all'); + $this->assertEquals(3, count($result)); + $this->assertFalse(isset($result[3])); + + $TestModel->saveAll(array( + 'Post' => array( + 'title' => 'Post with Author', + 'body' => 'This post will be saved with an author' + ), + 'Author' => array( + 'user' => 'bob', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf90' + ))); + + $result = $TestModel->find('all'); + $expected = array( + 'Post' => array( + 'id' => '4', + 'author_id' => '5', + 'title' => 'Post with Author', + 'body' => 'This post will be saved with an author', + 'published' => 'N' + ), + 'Author' => array( + 'id' => '5', + 'user' => 'bob', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf90', + 'test' => 'working' + )); + $this->assertEquals(self::date(), $result[3]['Post']['created']); + $this->assertEquals(self::date(), $result[3]['Post']['updated']); + $this->assertEquals(self::date(), $result[3]['Author']['created']); + $this->assertEquals(self::date(), $result[3]['Author']['updated']); + unset($result[3]['Post']['created'], $result[3]['Post']['updated']); + unset($result[3]['Author']['created'], $result[3]['Author']['updated']); + $this->assertEquals($expected, $result[3]); + $this->assertEquals(4, count($result)); + + $TestModel->deleteAll(true); + $this->assertEquals(array(), $TestModel->find('all')); + + // SQLite seems to reset the PK counter when that happens, so we need this to make the tests pass + $this->db->truncate($TestModel); + + $TestModel->saveAll(array( + array( + 'title' => 'Multi-record post 1', + 'body' => 'First multi-record post', + 'author_id' => 2 + ), + array( + 'title' => 'Multi-record post 2', + 'body' => 'Second multi-record post', + 'author_id' => 2 + ))); + + $result = $TestModel->find('all', array( + 'recursive' => -1, + 'order' => 'Post.id ASC' + )); + $expected = array( + array( + 'Post' => array( + 'id' => '1', + 'author_id' => '2', + 'title' => 'Multi-record post 1', + 'body' => 'First multi-record post', + 'published' => 'N' + )), + array( + 'Post' => array( + 'id' => '2', + 'author_id' => '2', + 'title' => 'Multi-record post 2', + 'body' => 'Second multi-record post', + 'published' => 'N' + ))); + $this->assertEquals(self::date(), $result[0]['Post']['created']); + $this->assertEquals(self::date(), $result[0]['Post']['updated']); + $this->assertEquals(self::date(), $result[1]['Post']['created']); + $this->assertEquals(self::date(), $result[1]['Post']['updated']); + unset($result[0]['Post']['created'], $result[0]['Post']['updated']); + unset($result[1]['Post']['created'], $result[1]['Post']['updated']); + $this->assertEquals($expected, $result); + + $TestModel = new Comment(); + $result = $TestModel->saveAll(array( + 'Comment' => array( + 'article_id' => 2, + 'user_id' => 2, + 'comment' => 'New comment with attachment', + 'published' => 'Y' + ), + 'Attachment' => array( + 'attachment' => 'some_file.tgz' + ))); + $this->assertFalse(empty($result)); + + $result = $TestModel->find('all'); + $expected = array( + 'id' => '7', + 'article_id' => '2', + 'user_id' => '2', + 'comment' => 'New comment with attachment', + 'published' => 'Y' + ); + $this->assertEquals(self::date(), $result[6]['Comment']['created']); + $this->assertEquals(self::date(), $result[6]['Comment']['updated']); + unset($result[6]['Comment']['created'], $result[6]['Comment']['updated']); + $this->assertEquals($expected, $result[6]['Comment']); + + $expected = array( + 'id' => '2', + 'comment_id' => '7', + 'attachment' => 'some_file.tgz' + ); + $this->assertEquals(self::date(), $result[6]['Attachment']['created']); + $this->assertEquals(self::date(), $result[6]['Attachment']['updated']); + unset($result[6]['Attachment']['created'], $result[6]['Attachment']['updated']); + $this->assertEquals($expected, $result[6]['Attachment']); + } + +/** + * Test SaveAll with Habtm relations + * + * @return void + */ + public function testSaveAllHabtm() { + $this->loadFixtures('Article', 'Tag', 'Comment', 'User', 'ArticlesTag'); + $data = array( + 'Article' => array( + 'user_id' => 1, + 'title' => 'Article Has and belongs to Many Tags' + ), + 'Tag' => array( + 'Tag' => array(1, 2) + ), + 'Comment' => array( + array( + 'comment' => 'Article comment', + 'user_id' => 1 + ))); + $Article = new Article(); + $result = $Article->saveAll($data); + $this->assertFalse(empty($result)); + + $result = $Article->read(); + $this->assertEquals(2, count($result['Tag'])); + $this->assertEquals('tag1', $result['Tag'][0]['tag']); + $this->assertEquals(1, count($result['Comment'])); + $this->assertEquals(1, count($result['Comment'][0]['comment'])); + } + +/** + * Test SaveAll with Habtm relations and extra join table fields + * + * @return void + */ + public function testSaveAllHabtmWithExtraJoinTableFields() { + $this->loadFixtures('Something', 'SomethingElse', 'JoinThing'); + + $data = array( + 'Something' => array( + 'id' => 4, + 'title' => 'Extra Fields', + 'body' => 'Extra Fields Body', + 'published' => '1' + ), + 'SomethingElse' => array( + array('something_else_id' => 1, 'doomed' => '1'), + array('something_else_id' => 2, 'doomed' => '0'), + array('something_else_id' => 3, 'doomed' => '1') + ) + ); + + $Something = new Something(); + $result = $Something->saveAll($data); + $this->assertFalse(empty($result)); + $result = $Something->read(); + + $this->assertEquals(3, count($result['SomethingElse'])); + $this->assertTrue(Set::matches('/Something[id=4]', $result)); + + $this->assertTrue(Set::matches('/SomethingElse[id=1]', $result)); + $this->assertTrue(Set::matches('/SomethingElse[id=1]/JoinThing[something_else_id=1]', $result)); + $this->assertTrue(Set::matches('/SomethingElse[id=1]/JoinThing[doomed=1]', $result)); + + $this->assertTrue(Set::matches('/SomethingElse[id=2]', $result)); + $this->assertTrue(Set::matches('/SomethingElse[id=2]/JoinThing[something_else_id=2]', $result)); + $this->assertTrue(Set::matches('/SomethingElse[id=2]/JoinThing[doomed=0]', $result)); + + $this->assertTrue(Set::matches('/SomethingElse[id=3]', $result)); + $this->assertTrue(Set::matches('/SomethingElse[id=3]/JoinThing[something_else_id=3]', $result)); + $this->assertTrue(Set::matches('/SomethingElse[id=3]/JoinThing[doomed=1]', $result)); + } + +/** + * testSaveAllHasOne method + * + * @return void + */ + public function testSaveAllHasOne() { + $model = new Comment(); + $model->deleteAll(true); + $this->assertEquals(array(), $model->find('all')); + + $model->Attachment->deleteAll(true); + $this->assertEquals(array(), $model->Attachment->find('all')); + + $this->assertTrue($model->saveAll(array( + 'Comment' => array( + 'comment' => 'Comment with attachment', + 'article_id' => 1, + 'user_id' => 1 + ), + 'Attachment' => array( + 'attachment' => 'some_file.zip' + )))); + $result = $model->find('all', array('fields' => array( + 'Comment.id', 'Comment.comment', 'Attachment.id', + 'Attachment.comment_id', 'Attachment.attachment' + ))); + $expected = array(array( + 'Comment' => array( + 'id' => '1', + 'comment' => 'Comment with attachment' + ), + 'Attachment' => array( + 'id' => '1', + 'comment_id' => '1', + 'attachment' => 'some_file.zip' + ))); + $this->assertEquals($expected, $result); + + $model->Attachment->bindModel(array('belongsTo' => array('Comment')), false); + $data = array( + 'Comment' => array( + 'comment' => 'Comment with attachment', + 'article_id' => 1, + 'user_id' => 1 + ), + 'Attachment' => array( + 'attachment' => 'some_file.zip' + )); + $this->assertTrue($model->saveAll($data, array('validate' => 'first'))); + } + +/** + * testSaveAllBelongsTo method + * + * @return void + */ + public function testSaveAllBelongsTo() { + $model = new Comment(); + $model->deleteAll(true); + $this->assertEquals(array(), $model->find('all')); + + $model->Article->deleteAll(true); + $this->assertEquals(array(), $model->Article->find('all')); + + $this->assertTrue($model->saveAll(array( + 'Comment' => array( + 'comment' => 'Article comment', + 'article_id' => 1, + 'user_id' => 1 + ), + 'Article' => array( + 'title' => 'Model Associations 101', + 'user_id' => 1 + )))); + $result = $model->find('all', array('fields' => array( + 'Comment.id', 'Comment.comment', 'Comment.article_id', 'Article.id', 'Article.title' + ))); + $expected = array(array( + 'Comment' => array( + 'id' => '1', + 'article_id' => '1', + 'comment' => 'Article comment' + ), + 'Article' => array( + 'id' => '1', + 'title' => 'Model Associations 101' + ))); + $this->assertEquals($expected, $result); + } + +/** + * testSaveAllHasOneValidation method + * + * @return void + */ + public function testSaveAllHasOneValidation() { + $model = new Comment(); + $model->deleteAll(true); + $this->assertEquals(array(), $model->find('all')); + + $model->Attachment->deleteAll(true); + $this->assertEquals(array(), $model->Attachment->find('all')); + + $model->validate = array('comment' => 'notEmpty'); + $model->Attachment->validate = array('attachment' => 'notEmpty'); + $model->Attachment->bindModel(array('belongsTo' => array('Comment'))); + + $result = $model->saveAll( + array( + 'Comment' => array( + 'comment' => '', + 'article_id' => 1, + 'user_id' => 1 + ), + 'Attachment' => array('attachment' => '') + ), + array('validate' => 'first') + ); + $this->assertEquals(false, $result); + $expected = array( + 'comment' => array('This field cannot be left blank'), + 'Attachment' => array( + 'attachment' => array('This field cannot be left blank') + ) + ); + $this->assertEquals($expected, $model->validationErrors); + $this->assertEquals($expected['Attachment'], $model->Attachment->validationErrors); + } + +/** + * testSaveAllAtomic method + * + * @return void + */ + public function testSaveAllAtomic() { + $this->loadFixtures('Article', 'User', 'Comment'); + $TestModel = new Article(); + + $result = $TestModel->saveAll(array( + 'Article' => array( + 'title' => 'Post with Author', + 'body' => 'This post will be saved with an author', + 'user_id' => 2 + ), + 'Comment' => array( + array('comment' => 'First new comment', 'user_id' => 2)) + ), array('atomic' => false)); + + $this->assertSame($result, array('Article' => true, 'Comment' => array(true))); + + $result = $TestModel->saveAll(array( + array( + 'id' => '1', + 'title' => 'Baleeted First Post', + 'body' => 'Baleeted!', + 'published' => 'N' + ), + array( + 'id' => '2', + 'title' => 'Just update the title' + ), + array( + 'title' => 'Creating a fourth post', + 'body' => 'Fourth post body', + 'user_id' => 2 + ) + ), array('atomic' => false)); + $this->assertSame($result, array(true, true, true)); + + $result = $TestModel->saveAll(array( + 'Article' => array('id' => 2), + 'Comment' => array( + array( + 'comment' => 'First new comment', + 'published' => 'Y', + 'user_id' => 1 + ), + array( + 'comment' => 'Second new comment', + 'published' => 'Y', + 'user_id' => 2 + )) + ), array('validate' => true, 'atomic' => false)); + $this->assertSame($result, array('Article' => true, 'Comment' => array(true, true))); + + $TestModel->validate = array( + 'title' => 'notEmpty', + 'author_id' => 'numeric' + ); + $result = $TestModel->saveAll(array( + array( + 'id' => '1', + 'title' => 'Un-Baleeted First Post', + 'body' => 'Not Baleeted!', + 'published' => 'Y' + ), + array( + 'id' => '2', + 'title' => '', + 'body' => 'Trying to get away with an empty title' + ) + ), array('validate' => true, 'atomic' => false)); + $this->assertSame(array(true, false), $result); + } + +/** + * testSaveAllDeepAssociated method + * + * @return void + */ + public function testSaveAllDeepAssociated() { + $this->loadFixtures('Article', 'Comment', 'User', 'Attachment'); + $TestModel = new Article(); + $TestModel->hasMany['Comment']['order'] = array('Comment.created' => 'ASC'); + $TestModel->hasAndBelongsToMany = array(); + + $result = $TestModel->saveAll(array( + 'Article' => array('id' => 2), + 'Comment' => array( + array('comment' => 'First new comment', 'published' => 'Y', 'User' => array('user' => 'newuser', 'password' => 'newuserpass')), + array('comment' => 'Second new comment', 'published' => 'Y', 'user_id' => 2) + ) + ), array('deep' => true)); + $this->assertTrue($result); + + $result = $TestModel->findById(2); + $expected = array( + 'First Comment for Second Article', + 'Second Comment for Second Article', + 'First new comment', + 'Second new comment' + ); + $result = Hash::extract(Hash::sort($result['Comment'], '{n}.id', 'ASC'), '{n}.comment'); + $this->assertEquals($expected, $result); + + $result = $TestModel->Comment->User->field('id', array('user' => 'newuser', 'password' => 'newuserpass')); + $this->assertEquals(5, $result); + $result = $TestModel->saveAll(array( + 'Article' => array('id' => 2), + 'Comment' => array( + array('comment' => 'Third new comment', 'published' => 'Y', 'user_id' => 5), + array('comment' => 'Fourth new comment', 'published' => 'Y', 'user_id' => 2, 'Attachment' => array('attachment' => 'deepsaved')) + ) + ), array('deep' => true)); + $this->assertTrue($result); + + $result = $TestModel->findById(2); + $expected = array( + 'First Comment for Second Article', + 'Second Comment for Second Article', + 'First new comment', + 'Second new comment', + 'Third new comment', + 'Fourth new comment' + ); + $result = Hash::extract(Hash::sort($result['Comment'], '{n}.id', 'ASC'), '{n}.comment'); + $this->assertEquals($expected, $result); + + $result = $TestModel->Comment->Attachment->field('id', array('attachment' => 'deepsaved')); + $this->assertEquals(2, $result); + $data = array( + 'Attachment' => array( + 'attachment' => 'deepsave insert', + ), + 'Comment' => array( + 'comment' => 'First comment deepsave insert', + 'published' => 'Y', + 'user_id' => 5, + 'Article' => array( + 'title' => 'First Article deepsave insert', + 'body' => 'First Article Body deepsave insert', + 'User' => array( + 'user' => '', + 'password' => 'magic' + ), + ), + ) + ); + + $TestModel->Comment->Attachment->create(); + $result = $TestModel->Comment->Attachment->saveAll($data, array('deep' => true)); + $this->assertFalse($result); + + $expected = array('User' => array('user' => array('This field cannot be left blank'))); + $this->assertEquals($expected, $TestModel->validationErrors); + + $data['Comment']['Article']['User']['user'] = 'deepsave'; + $TestModel->Comment->Attachment->create(); + $result = $TestModel->Comment->Attachment->saveAll($data, array('deep' => true)); + $this->assertTrue($result); + + $result = $TestModel->Comment->Attachment->findById($TestModel->Comment->Attachment->id); + $expected = array( + 'Attachment' => array( + 'id' => '3', + 'comment_id' => '11', + 'attachment' => 'deepsave insert', + ), + 'Comment' => array( + 'id' => '11', + 'article_id' => '4', + 'user_id' => '5', + 'comment' => 'First comment deepsave insert', + 'published' => 'Y', + ) + ); + unset($result['Attachment']['created'], $result['Attachment']['updated']); + $this->assertEquals($expected['Attachment'], $result['Attachment']); + + unset($result['Comment']['created'], $result['Comment']['updated']); + $this->assertEquals($expected['Comment'], $result['Comment']); + + $result = $TestModel->findById($result['Comment']['article_id']); + $expected = array( + 'Article' => array( + 'id' => '4', + 'user_id' => '6', + 'title' => 'First Article deepsave insert', + 'body' => 'First Article Body deepsave insert', + 'published' => 'N', + ), + 'User' => array( + 'id' => '6', + 'user' => 'deepsave', + 'password' => 'magic', + ), + 'Comment' => array( + array( + 'id' => '11', + 'article_id' => '4', + 'user_id' => '5', + 'comment' => 'First comment deepsave insert', + 'published' => 'Y', + ) + ) + ); + unset( + $result['Article']['created'], $result['Article']['updated'], + $result['User']['created'], $result['User']['updated'], + $result['Comment'][0]['created'], $result['Comment'][0]['updated'] + ); + $this->assertEquals($expected, $result); + } + +/** + * testSaveAllDeepMany + * tests the validate methods with deeper recursive data + * + * @return void + */ + public function testSaveAllDeepMany() { + $this->loadFixtures('Article', 'Comment', 'User', 'Attachment'); + $TestModel = new Article(); + $TestModel->hasMany['Comment']['order'] = array('Comment.created' => 'ASC'); + $TestModel->hasAndBelongsToMany = array(); + + $data = array( + array( + 'Article' => array('id' => 1), + 'Comment' => array( + array('comment' => 'First comment deepsaved article 1', 'published' => 'Y', 'User' => array('user' => 'savemany', 'password' => 'manysaved')), + array('comment' => 'Second comment deepsaved article 1', 'published' => 'Y', 'user_id' => 2) + ) + ), + array( + 'Article' => array('id' => 2), + 'Comment' => array( + array('comment' => 'First comment deepsaved article 2', 'published' => 'Y', 'User' => array('user' => 'savemore', 'password' => 'moresaved')), + array('comment' => 'Second comment deepsaved article 2', 'published' => 'Y', 'user_id' => 2) + ) + ) + ); + $result = $TestModel->saveAll($data, array('deep' => true)); + $this->assertTrue($result); + + $data = array( + array( + 'id' => 1, 'body' => '', + 'Comment' => array( + array('comment' => '', 'published' => 'Y', 'User' => array('user' => '', 'password' => 'manysaved')), + array('comment' => 'Second comment deepsaved article 1', 'published' => 'Y', 'user_id' => 2) + ) + ), + array( + 'Article' => array('id' => 2), + 'Comment' => array( + array('comment' => 'First comment deepsaved article 2', 'published' => 'Y', 'User' => array('user' => 'savemore', 'password' => '')), + array('comment' => '', 'published' => 'Y', 'user_id' => 2) + ) + ) + ); + $TestModel->Comment->validate['comment'] = 'notEmpty'; + $result = $TestModel->saveAll($data, array('deep' => true)); + $this->assertFalse($result); + + $expected = array( + 0 => array( + 'body' => array('This field cannot be left blank'), + 'Comment' => array( + 0 => array( + 'comment' => array('This field cannot be left blank'), + 'User' => array( + 'user' => array('This field cannot be left blank') + ) + ) + ) + ), + 1 => array( + 'body' => array('This field cannot be left blank'), + 'Comment' => array( + 0 => array( + 'User' => array( + 'password' => array('This field cannot be left blank') + ) + ), + 1 => array( + 'comment' => array('This field cannot be left blank') + ) + ) + ) + ); + $result = $TestModel->validationErrors; + $this->assertSame($expected, $result); + } +/** + * testSaveAllDeepValidateOnly + * tests the validate methods with deeper recursive data + * + * @return void + */ + public function testSaveAllDeepValidateOnly() { + $this->loadFixtures('Article', 'Comment', 'User', 'Attachment'); + $TestModel = new Article(); + $TestModel->hasMany['Comment']['order'] = array('Comment.created' => 'ASC'); + $TestModel->hasAndBelongsToMany = array(); + $TestModel->Comment->Attachment->validate['attachment'] = 'notEmpty'; + $TestModel->Comment->validate['comment'] = 'notEmpty'; + + $result = $TestModel->saveAll( + array( + 'Article' => array('id' => 2), + 'Comment' => array( + array('comment' => 'First new comment', 'published' => 'Y', 'User' => array('user' => 'newuser', 'password' => 'newuserpass')), + array('comment' => 'Second new comment', 'published' => 'Y', 'user_id' => 2) + ) + ), + array('validate' => 'only', 'deep' => true) + ); + $this->assertTrue($result); + + $result = $TestModel->saveAll( + array( + 'Article' => array('id' => 2), + 'Comment' => array( + array('comment' => 'First new comment', 'published' => 'Y', 'User' => array('user' => '', 'password' => 'newuserpass')), + array('comment' => 'Second new comment', 'published' => 'Y', 'user_id' => 2) + ) + ), + array('validate' => 'only', 'deep' => true) + ); + $this->assertFalse($result); + + $result = $TestModel->saveAll( + array( + 'Article' => array('id' => 2), + 'Comment' => array( + array('comment' => 'First new comment', 'published' => 'Y', 'User' => array('user' => 'newuser', 'password' => 'newuserpass')), + array('comment' => 'Second new comment', 'published' => 'Y', 'user_id' => 2) + ) + ), + array('validate' => 'only', 'atomic' => false, 'deep' => true) + ); + $expected = array( + 'Article' => true, + 'Comment' => array( + true, + true + ) + ); + $this->assertSame($expected, $result); + + $result = $TestModel->saveAll( + array( + 'Article' => array('id' => 2), + 'Comment' => array( + array('comment' => 'First new comment', 'published' => 'Y', 'User' => array('user' => '', 'password' => 'newuserpass')), + array('comment' => 'Second new comment', 'published' => 'Y', 'user_id' => 2) + ) + ), + array('validate' => 'only', 'atomic' => false, 'deep' => true) + ); + $expected = array( + 'Article' => true, + 'Comment' => array( + false, + true + ) + ); + $this->assertSame($expected, $result); + + $result = $TestModel->saveAll(array( + 'Article' => array('id' => 2), + 'Comment' => array( + array('comment' => 'Third new comment', 'published' => 'Y', 'user_id' => 5), + array('comment' => 'Fourth new comment', 'published' => 'Y', 'user_id' => 2, 'Attachment' => array('attachment' => 'deepsaved')) + ) + ), + array('validate' => 'only', 'deep' => true) + ); + $this->assertTrue($result); + + $result = $TestModel->saveAll(array( + 'Article' => array('id' => 2), + 'Comment' => array( + array('comment' => 'Third new comment', 'published' => 'Y', 'user_id' => 5), + array('comment' => 'Fourth new comment', 'published' => 'Y', 'user_id' => 2, 'Attachment' => array('attachment' => '')) + ) + ), + array('validate' => 'only', 'deep' => true) + ); + $this->assertFalse($result); + + $result = $TestModel->saveAll(array( + 'Article' => array('id' => 2), + 'Comment' => array( + array('comment' => 'Third new comment', 'published' => 'Y', 'user_id' => 5), + array('comment' => 'Fourth new comment', 'published' => 'Y', 'user_id' => 2, 'Attachment' => array('attachment' => 'deepsave')) + ) + ), + array('validate' => 'only', 'atomic' => false, 'deep' => true) + ); + $expected = array( + 'Article' => true, + 'Comment' => array( + true, + true + ) + ); + $this->assertSame($expected, $result); + + $result = $TestModel->saveAll(array( + 'Article' => array('id' => 2), + 'Comment' => array( + array('comment' => 'Third new comment', 'published' => 'Y', 'user_id' => 5), + array('comment' => 'Fourth new comment', 'published' => 'Y', 'user_id' => 2, 'Attachment' => array('attachment' => '')) + ) + ), + array('validate' => 'only', 'atomic' => false, 'deep' => true) + ); + $expected = array( + 'Article' => true, + 'Comment' => array( + true, + false + ) + ); + $this->assertSame($expected, $result); + + $expected = array( + 'Comment' => array( + 1 => array( + 'Attachment' => array( + 'attachment' => array('This field cannot be left blank') + ) + ) + ) + ); + $result = $TestModel->validationErrors; + $this->assertSame($expected, $result); + + $data = array( + 'Attachment' => array( + 'attachment' => 'deepsave insert', + ), + 'Comment' => array( + 'comment' => 'First comment deepsave insert', + 'published' => 'Y', + 'user_id' => 5, + 'Article' => array( + 'title' => 'First Article deepsave insert', + 'body' => 'First Article Body deepsave insert', + 'User' => array( + 'user' => 'deepsave', + 'password' => 'magic' + ), + ), + ) + ); + + $result = $TestModel->Comment->Attachment->saveAll($data, array('validate' => 'only', 'deep' => true)); + $this->assertTrue($result); + + $result = $TestModel->Comment->Attachment->saveAll($data, array('validate' => 'only', 'atomic' => false, 'deep' => true)); + $expected = array( + 'Attachment' => true, + 'Comment' => true + ); + $this->assertSame($expected, $result); + + $data = array( + 'Attachment' => array( + 'attachment' => 'deepsave insert', + ), + 'Comment' => array( + 'comment' => 'First comment deepsave insert', + 'published' => 'Y', + 'user_id' => 5, + 'Article' => array( + 'title' => 'First Article deepsave insert', + 'body' => 'First Article Body deepsave insert', + 'User' => array( + 'user' => '', + 'password' => 'magic' + ), + ), + ) + ); + + $result = $TestModel->Comment->Attachment->saveAll($data, array('validate' => 'only', 'deep' => true)); + $this->assertFalse($result); + + $result = $TestModel->Comment->Attachment->validationErrors; + $expected = array( + 'Comment' => array( + 'Article' => array( + 'User' => array( + 'user' => array('This field cannot be left blank') + ) + ) + ) + ); + $this->assertSame($expected, $result); + + $result = $TestModel->Comment->Attachment->saveAll($data, array('validate' => 'only', 'atomic' => false, 'deep' => true)); + $expected = array( + 'Attachment' => true, + 'Comment' => false + ); + $this->assertEquals($expected, $result); + + $data['Comment']['Article']['body'] = ''; + $result = $TestModel->Comment->Attachment->saveAll($data, array('validate' => 'only', 'deep' => true)); + $this->assertFalse($result); + + $result = $TestModel->Comment->Attachment->validationErrors; + $expected = array( + 'Comment' => array( + 'Article' => array( + 'body' => array('This field cannot be left blank'), + 'User' => array( + 'user' => array('This field cannot be left blank') + ) + ) + ) + ); + $this->assertSame($expected, $result); + + $result = $TestModel->Comment->Attachment->saveAll($data, array('validate' => 'only', 'atomic' => false, 'deep' => true)); + $expected = array( + 'Attachment' => true, + 'Comment' => false + ); + $this->assertEquals($expected, $result); + + $data['Comment']['comment'] = ''; + $result = $TestModel->Comment->Attachment->saveAll($data, array('validate' => 'only', 'deep' => true)); + $this->assertFalse($result); + + $result = $TestModel->Comment->Attachment->validationErrors; + $expected = array( + 'Comment' => array( + 'comment' => array('This field cannot be left blank'), + 'Article' => array( + 'body' => array('This field cannot be left blank'), + 'User' => array( + 'user' => array('This field cannot be left blank') + ) + ) + ) + ); + $this->assertSame($expected, $result); + + $result = $TestModel->Comment->Attachment->saveAll($data, array('validate' => 'only', 'atomic' => false, 'deep' => true)); + $expected = array( + 'Attachment' => true, + 'Comment' => false + ); + $this->assertEquals($expected, $result); + + $data['Attachment']['attachment'] = ''; + $result = $TestModel->Comment->Attachment->saveAll($data, array('validate' => 'only', 'deep' => true)); + $this->assertFalse($result); + + $result = $TestModel->Comment->Attachment->validationErrors; + $expected = array( + 'attachment' => array('This field cannot be left blank'), + 'Comment' => array( + 'comment' => array('This field cannot be left blank'), + 'Article' => array( + 'body' => array('This field cannot be left blank'), + 'User' => array( + 'user' => array('This field cannot be left blank') + ) + ) + ) + ); + $this->assertSame($expected, $result); + + $result = $TestModel->Comment->validationErrors; + $expected = array( + 'comment' => array('This field cannot be left blank'), + 'Article' => array( + 'body' => array('This field cannot be left blank'), + 'User' => array( + 'user' => array('This field cannot be left blank') + ) + ) + ); + $this->assertSame($expected, $result); + + $result = $TestModel->Comment->Attachment->saveAll($data, array('validate' => 'only', 'atomic' => false, 'deep' => true)); + $expected = array( + 'Attachment' => false, + 'Comment' => false + ); + $this->assertEquals($expected, $result); + } + +/** + * testSaveAllNotDeepAssociated method + * test that only directly associated data gets saved + * + * @return void + */ + public function testSaveAllNotDeepAssociated() { + $this->loadFixtures('Article', 'Comment', 'User', 'Attachment'); + $TestModel = new Article(); + $TestModel->hasMany['Comment']['order'] = array('Comment.created' => 'ASC'); + $TestModel->hasAndBelongsToMany = array(); + + $result = $TestModel->saveAll(array( + 'Article' => array('id' => 2), + 'Comment' => array( + array( + 'comment' => 'First new comment', 'published' => 'Y', 'user_id' => 2, + 'User' => array('user' => 'newuser', 'password' => 'newuserpass') + ), + array('comment' => 'Second new comment', 'published' => 'Y', 'user_id' => 2) + ) + ), array('deep' => false)); + $this->assertTrue($result); + + $result = $TestModel->Comment->User->field('id', array('user' => 'newuser', 'password' => 'newuserpass')); + $this->assertFalse($result); + + $result = $TestModel->saveAll(array( + 'Article' => array('id' => 2), + 'Comment' => array( + array('comment' => 'Third new comment', 'published' => 'Y', 'user_id' => 4), + array('comment' => 'Fourth new comment', 'published' => 'Y', 'user_id' => 2, 'Attachment' => array('attachment' => 'deepsaved')) + ) + ), array('deep' => false)); + $this->assertTrue($result); + + $result = $TestModel->Comment->Attachment->field('id', array('attachment' => 'deepsaved')); + $this->assertFalse($result); + + $data = array( + 'Attachment' => array( + 'attachment' => 'deepsave insert', + ), + 'Comment' => array( + 'comment' => 'First comment deepsave insert', + 'published' => 'Y', + 'user_id' => 4, + 'article_id' => 1, + 'Article' => array( + 'title' => 'First Article deepsave insert', + 'body' => 'First Article Body deepsave insert', + 'User' => array( + 'user' => 'deepsave', + 'password' => 'magic' + ), + ), + ) + ); + $expected = $TestModel->User->find('count'); + + $TestModel->Comment->Attachment->create(); + $result = $TestModel->Comment->Attachment->saveAll($data, array('deep' => false)); + $this->assertTrue($result); + + $result = $TestModel->User->find('count'); + $this->assertEquals($expected, $result); + + $result = $TestModel->Comment->Attachment->findById($TestModel->Comment->Attachment->id); + $expected = array( + 'Attachment' => array( + 'id' => '2', + 'comment_id' => '11', + 'attachment' => 'deepsave insert', + ), + 'Comment' => array( + 'id' => '11', + 'article_id' => 1, + 'user_id' => '4', + 'comment' => 'First comment deepsave insert', + 'published' => 'Y', + ) + ); + unset($result['Attachment']['created'], $result['Attachment']['updated']); + $this->assertEquals($expected['Attachment'], $result['Attachment']); + + unset($result['Comment']['created'], $result['Comment']['updated']); + $this->assertEquals($expected['Comment'], $result['Comment']); + } + +/** + * testSaveAllNotDeepMany + * tests the save methods to not save deeper recursive data + * + * @return void + */ + public function testSaveAllNotDeepMany() { + $this->loadFixtures('Article', 'Comment', 'User', 'Attachment'); + $TestModel = new Article(); + $TestModel->hasMany['Comment']['order'] = array('Comment.created' => 'ASC'); + $TestModel->hasAndBelongsToMany = array(); + + $data = array( + array( + 'id' => 1, + 'body' => '', + 'Comment' => array( + array('comment' => '', 'published' => 'Y', 'User' => array('user' => '', 'password' => 'manysaved')), + array('comment' => 'Second comment deepsaved article 1', 'published' => 'Y', 'user_id' => 2) + ) + ), + array( + 'Article' => array('id' => 2), + 'Comment' => array( + array('comment' => 'First comment deepsaved article 2', 'published' => 'Y', 'User' => array('user' => 'savemore', 'password' => '')), + array('comment' => '', 'published' => 'Y', 'user_id' => 2) + ) + ) + ); + $TestModel->Comment->validate['comment'] = 'notEmpty'; + $result = $TestModel->saveAll($data, array('deep' => false)); + $this->assertFalse($result); + + $expected = array( + 0 => array( + 'body' => array('This field cannot be left blank') + ), + 1 => array( + 'body' => array('This field cannot be left blank') + ) + ); + $result = $TestModel->validationErrors; + $this->assertSame($expected, $result); + + $data = array( + array( + 'Article' => array('id' => 1, 'body' => 'Ignore invalid comment'), + 'Comment' => array( + array('comment' => '', 'published' => 'Y', 'user_id' => 2) + ) + ), + array( + 'Article' => array('id' => 2, 'body' => 'Same here'), + 'Comment' => array( + array('comment' => '', 'published' => 'Y', 'user_id' => 2) + ) + ) + ); + $result = $TestModel->saveAll($data, array('deep' => false)); + $this->assertTrue($result); + } +/** + * testSaveAllNotDeepValidateOnly + * tests the validate methods to not validate deeper recursive data + * + * @return void + */ + public function testSaveAllNotDeepValidateOnly() { + $this->loadFixtures('Article', 'Comment', 'User', 'Attachment'); + $TestModel = new Article(); + $TestModel->hasMany['Comment']['order'] = array('Comment.created' => 'ASC'); + $TestModel->hasAndBelongsToMany = array(); + $TestModel->Comment->Attachment->validate['attachment'] = 'notEmpty'; + $TestModel->Comment->validate['comment'] = 'notEmpty'; + + $result = $TestModel->saveAll( + array( + 'Article' => array('id' => 2, 'body' => ''), + 'Comment' => array( + array('comment' => 'First new comment', 'published' => 'Y', 'User' => array('user' => '', 'password' => 'newuserpass')), + array('comment' => 'Second new comment', 'published' => 'Y', 'user_id' => 2) + ) + ), + array('validate' => 'only', 'deep' => false) + ); + $this->assertFalse($result); + + $expected = array('body' => array('This field cannot be left blank')); + $result = $TestModel->validationErrors; + $this->assertSame($expected, $result); + + $result = $TestModel->saveAll( + array( + 'Article' => array('id' => 2, 'body' => 'Ignore invalid user data'), + 'Comment' => array( + array('comment' => 'First new comment', 'published' => 'Y', 'User' => array('user' => '', 'password' => 'newuserpass')), + array('comment' => 'Second new comment', 'published' => 'Y', 'user_id' => 2) + ) + ), + array('validate' => 'only', 'deep' => false) + ); + $this->assertTrue($result); + + $result = $TestModel->saveAll( + array( + 'Article' => array('id' => 2, 'body' => 'Ignore invalid user data'), + 'Comment' => array( + array('comment' => 'First new comment', 'published' => 'Y', 'User' => array('user' => '', 'password' => 'newuserpass')), + array('comment' => 'Second new comment', 'published' => 'Y', 'user_id' => 2) + ) + ), + array('validate' => 'only', 'atomic' => false, 'deep' => false) + ); + $expected = array( + 'Article' => true, + 'Comment' => array( + true, + true + ) + ); + $this->assertSame($expected, $result); + + $result = $TestModel->saveAll(array( + 'Article' => array('id' => 2, 'body' => 'Ignore invalid attachment data'), + 'Comment' => array( + array('comment' => 'Third new comment', 'published' => 'Y', 'user_id' => 5), + array('comment' => 'Fourth new comment', 'published' => 'Y', 'user_id' => 2, 'Attachment' => array('attachment' => '')) + ) + ), + array('validate' => 'only', 'deep' => false) + ); + $this->assertTrue($result); + + $result = $TestModel->saveAll(array( + 'Article' => array('id' => 2, 'body' => 'Ignore invalid attachment data'), + 'Comment' => array( + array('comment' => 'Third new comment', 'published' => 'Y', 'user_id' => 5), + array('comment' => 'Fourth new comment', 'published' => 'Y', 'user_id' => 2, 'Attachment' => array('attachment' => '')) + ) + ), + array('validate' => 'only', 'atomic' => false, 'deep' => false) + ); + $expected = array( + 'Article' => true, + 'Comment' => array( + true, + true + ) + ); + $this->assertSame($expected, $result); + + $expected = array(); + $result = $TestModel->validationErrors; + $this->assertSame($expected, $result); + + $data = array( + 'Attachment' => array( + 'attachment' => 'deepsave insert', + ), + 'Comment' => array( + 'comment' => 'First comment deepsave insert', + 'published' => 'Y', + 'user_id' => 5, + 'Article' => array( + 'title' => 'First Article deepsave insert ignored', + 'body' => 'First Article Body deepsave insert', + 'User' => array( + 'user' => '', + 'password' => 'magic' + ), + ), + ) + ); + + $result = $TestModel->Comment->Attachment->saveAll($data, array('validate' => 'only', 'deep' => false)); + $this->assertTrue($result); + + $result = $TestModel->Comment->Attachment->validationErrors; + $expected = array(); + $this->assertSame($expected, $result); + + $result = $TestModel->Comment->Attachment->saveAll($data, array('validate' => 'only', 'atomic' => false, 'deep' => false)); + $expected = array( + 'Attachment' => true, + 'Comment' => true + ); + $this->assertEquals($expected, $result); + + $data['Comment']['Article']['body'] = ''; + $result = $TestModel->Comment->Attachment->saveAll($data, array('validate' => 'only', 'deep' => false)); + $this->assertTrue($result); + + $result = $TestModel->Comment->Attachment->validationErrors; + $expected = array(); + $this->assertSame($expected, $result); + + $result = $TestModel->Comment->Attachment->saveAll($data, array('validate' => 'only', 'atomic' => false, 'deep' => false)); + $expected = array( + 'Attachment' => true, + 'Comment' => true + ); + $this->assertEquals($expected, $result); + } + +/** + * testSaveAllHasMany method + * + * @return void + */ + public function testSaveAllHasMany() { + $this->loadFixtures('Article', 'Comment'); + $TestModel = new Article(); + $TestModel->hasMany['Comment']['order'] = array('Comment.created' => 'ASC'); + $TestModel->belongsTo = $TestModel->hasAndBelongsToMany = array(); + + $result = $TestModel->saveAll(array( + 'Article' => array('id' => 2), + 'Comment' => array( + array('comment' => 'First new comment', 'published' => 'Y', 'user_id' => 1), + array('comment' => 'Second new comment', 'published' => 'Y', 'user_id' => 2) + ) + )); + $this->assertFalse(empty($result)); + + $result = $TestModel->findById(2); + $expected = array( + 'First Comment for Second Article', + 'Second Comment for Second Article', + 'First new comment', + 'Second new comment' + ); + $result = Hash::extract(Hash::sort($result['Comment'], '{n}.id', 'ASC'), '{n}.comment'); + $this->assertEquals($expected, $result); + + $result = $TestModel->saveAll( + array( + 'Article' => array('id' => 2), + 'Comment' => array( + array( + 'comment' => 'Third new comment', + 'published' => 'Y', + 'user_id' => 1 + ))), + array('atomic' => false) + ); + $this->assertFalse(empty($result)); + + $result = $TestModel->findById(2); + $expected = array( + 'First Comment for Second Article', + 'Second Comment for Second Article', + 'First new comment', + 'Second new comment', + 'Third new comment' + ); + $result = Hash::extract(Hash::sort($result['Comment'], '{n}.id', 'ASC'), '{n}.comment'); + $this->assertEquals($expected, $result); + + $TestModel->beforeSaveReturn = false; + $result = $TestModel->saveAll( + array( + 'Article' => array('id' => 2), + 'Comment' => array( + array( + 'comment' => 'Fourth new comment', + 'published' => 'Y', + 'user_id' => 1 + ))), + array('atomic' => false) + ); + $this->assertEquals(array('Article' => false), $result); + + $result = $TestModel->findById(2); + $expected = array( + 'First Comment for Second Article', + 'Second Comment for Second Article', + 'First new comment', + 'Second new comment', + 'Third new comment' + ); + $result = Hash::extract(Hash::sort($result['Comment'], '{n}.id', 'ASC'), '{n}.comment'); + $this->assertEquals($expected, $result); + } + +/** + * testSaveAllHasManyValidation method + * + * @return void + */ + public function testSaveAllHasManyValidation() { + $this->loadFixtures('Article', 'Comment'); + $TestModel = new Article(); + $TestModel->belongsTo = $TestModel->hasAndBelongsToMany = array(); + $TestModel->Comment->validate = array('comment' => 'notEmpty'); + + $result = $TestModel->saveAll(array( + 'Article' => array('id' => 2), + 'Comment' => array( + array('comment' => '', 'published' => 'Y', 'user_id' => 1), + ) + ), array('validate' => true)); + $this->assertFalse($result); + + $expected = array('Comment' => array( + array('comment' => array('This field cannot be left blank')) + )); + $this->assertEquals($expected, $TestModel->validationErrors); + $expected = array( + array('comment' => array('This field cannot be left blank')) + ); + $this->assertEquals($expected, $TestModel->Comment->validationErrors); + + $result = $TestModel->saveAll(array( + 'Article' => array('id' => 2), + 'Comment' => array( + array( + 'comment' => '', + 'published' => 'Y', + 'user_id' => 1 + )) + ), array('validate' => 'first')); + $this->assertFalse($result); + } + +/** + * test saveAll with transactions and ensure there is no missing rollback. + * + * @return void + */ + public function testSaveAllManyRowsTransactionNoRollback() { + $this->loadFixtures('Post'); + + $this->getMock('DboSource', array('connect', 'rollback', 'describe'), array(), 'MockTransactionDboSource'); + $db = ConnectionManager::create('mock_transaction', array( + 'datasource' => 'MockTransactionDboSource', + )); + + $db->expects($this->once()) + ->method('describe') + ->will($this->returnValue(array())); + $db->expects($this->once())->method('rollback'); + + $Post = new Post('mock_transaction'); + + $Post->validate = array( + 'title' => array('rule' => array('notEmpty')) + ); + + $data = array( + array('author_id' => 1, 'title' => 'New Fourth Post'), + array('author_id' => 1, 'title' => '') + ); + $Post->saveAll($data, array('atomic' => true)); + } + +/** + * test saveAll with transactions and ensure there is no missing rollback. + * + * @return void + */ + public function testSaveAllAssociatedTransactionNoRollback() { + $testDb = ConnectionManager::getDataSource('test'); + + $mock = $this->getMock( + 'DboSource', + array('connect', 'rollback', 'describe', 'create', 'update', 'begin'), + array(), + 'MockTransactionAssociatedDboSource' + ); + $db = ConnectionManager::create('mock_transaction_assoc', array( + 'datasource' => 'MockTransactionAssociatedDboSource', + )); + $this->mockObjects[] = $db; + $db->columns = $testDb->columns; + + $db->expects($this->once())->method('rollback'); + $db->expects($this->any())->method('describe') + ->will($this->returnValue(array( + 'id' => array('type' => 'integer', 'length' => 11), + 'title' => array('type' => 'string'), + 'body' => array('type' => 'text'), + 'published' => array('type' => 'string') + ))); + + $Post = new Post(); + $Post->useDbConfig = 'mock_transaction_assoc'; + $Post->Author->useDbConfig = 'mock_transaction_assoc'; + + $Post->Author->validate = array( + 'user' => array('rule' => array('notEmpty')) + ); + + $data = array( + 'Post' => array( + 'title' => 'New post', + 'body' => 'Content', + 'published' => 'Y' + ), + 'Author' => array( + 'user' => '', + 'password' => "sekret" + ) + ); + $Post->saveAll($data, array('validate' => true)); + } + +/** + * test saveAll with nested saveAll call. + * + * @return void + */ + public function testSaveAllNestedSaveAll() { + $this->loadFixtures('Sample'); + $TransactionTestModel = new TransactionTestModel(); + + $data = array( + array('apple_id' => 1, 'name' => 'sample5'), + ); + + $this->assertTrue($TransactionTestModel->saveAll($data, array('atomic' => true))); + } + +/** + * testSaveAllTransaction method + * + * @return void + */ + public function testSaveAllTransaction() { + $this->loadFixtures('Post', 'Author', 'Comment', 'Attachment'); + $TestModel = new Post(); + + $TestModel->validate = array('title' => 'notEmpty'); + $data = array( + array('author_id' => 1, 'title' => 'New Fourth Post'), + array('author_id' => 1, 'title' => 'New Fifth Post'), + array('author_id' => 1, 'title' => '') + ); + $this->assertFalse($TestModel->saveAll($data)); + + $result = $TestModel->find('all', array('recursive' => -1)); + $expected = array( + array('Post' => array( + 'id' => '1', + 'author_id' => 1, + 'title' => 'First Post', + 'body' => 'First Post Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:39:23', + 'updated' => '2007-03-18 10:41:31' + )), + array('Post' => array( + 'id' => '2', + 'author_id' => 3, + 'title' => 'Second Post', + 'body' => 'Second Post Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:41:23', + 'updated' => '2007-03-18 10:43:31' + )), + array('Post' => array( + 'id' => '3', + 'author_id' => 1, + 'title' => 'Third Post', + 'body' => 'Third Post Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:43:23', + 'updated' => '2007-03-18 10:45:31' + ))); + + if (count($result) != 3) { + // Database doesn't support transactions + $expected[] = array( + 'Post' => array( + 'id' => '4', + 'author_id' => 1, + 'title' => 'New Fourth Post', + 'body' => null, + 'published' => 'N', + 'created' => self::date(), + 'updated' => self::date() + )); + + $expected[] = array( + 'Post' => array( + 'id' => '5', + 'author_id' => 1, + 'title' => 'New Fifth Post', + 'body' => null, + 'published' => 'N', + 'created' => self::date(), + 'updated' => self::date() + )); + + $this->assertEquals($expected, $result); + // Skip the rest of the transactional tests + return; + } + + $this->assertEquals($expected, $result); + + $data = array( + array('author_id' => 1, 'title' => 'New Fourth Post'), + array('author_id' => 1, 'title' => ''), + array('author_id' => 1, 'title' => 'New Sixth Post') + ); + $this->assertFalse($TestModel->saveAll($data)); + + $result = $TestModel->find('all', array('recursive' => -1)); + $expected = array( + array('Post' => array( + 'id' => '1', + 'author_id' => 1, + 'title' => 'First Post', + 'body' => 'First Post Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:39:23', + 'updated' => '2007-03-18 10:41:31' + )), + array('Post' => array( + 'id' => '2', + 'author_id' => 3, + 'title' => 'Second Post', + 'body' => 'Second Post Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:41:23', + 'updated' => '2007-03-18 10:43:31' + )), + array('Post' => array( + 'id' => '3', + 'author_id' => 1, + 'title' => 'Third Post', + 'body' => 'Third Post Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:43:23', + 'updated' => '2007-03-18 10:45:31' + ))); + + if (count($result) != 3) { + // Database doesn't support transactions + $expected[] = array( + 'Post' => array( + 'id' => '4', + 'author_id' => 1, + 'title' => 'New Fourth Post', + 'body' => 'Third Post Body', + 'published' => 'N', + 'created' => self::date(), + 'updated' => self::date() + )); + + $expected[] = array( + 'Post' => array( + 'id' => '5', + 'author_id' => 1, + 'title' => 'Third Post', + 'body' => 'Third Post Body', + 'published' => 'N', + 'created' => self::date(), + 'updated' => self::date() + )); + } + $this->assertEquals($expected, $result); + + $TestModel->validate = array('title' => 'notEmpty'); + $data = array( + array('author_id' => 1, 'title' => 'New Fourth Post'), + array('author_id' => 1, 'title' => 'New Fifth Post'), + array('author_id' => 1, 'title' => 'New Sixth Post') + ); + $this->assertTrue($TestModel->saveAll($data)); + + $result = $TestModel->find('all', array( + 'recursive' => -1, + 'fields' => array('author_id', 'title','body','published'), + 'order' => array('Post.created' => 'ASC') + )); + + $expected = array( + array('Post' => array( + 'author_id' => 1, + 'title' => 'First Post', + 'body' => 'First Post Body', + 'published' => 'Y' + )), + array('Post' => array( + 'author_id' => 3, + 'title' => 'Second Post', + 'body' => 'Second Post Body', + 'published' => 'Y' + )), + array('Post' => array( + 'author_id' => 1, + 'title' => 'Third Post', + 'body' => 'Third Post Body', + 'published' => 'Y' + )), + array('Post' => array( + 'author_id' => 1, + 'title' => 'New Fourth Post', + 'body' => '', + 'published' => 'N' + )), + array('Post' => array( + 'author_id' => 1, + 'title' => 'New Fifth Post', + 'body' => '', + 'published' => 'N' + )), + array('Post' => array( + 'author_id' => 1, + 'title' => 'New Sixth Post', + 'body' => '', + 'published' => 'N' + ))); + $this->assertEquals($expected, $result); + } + +/** + * testSaveAllValidation method + * + * @return void + */ + public function testSaveAllValidation() { + $this->loadFixtures('Post', 'Author', 'Comment', 'Attachment'); + $TestModel = new Post(); + + $data = array( + array( + 'id' => '1', + 'title' => 'Baleeted First Post', + 'body' => 'Baleeted!', + 'published' => 'N' + ), + array( + 'id' => '2', + 'title' => 'Just update the title' + ), + array( + 'title' => 'Creating a fourth post', + 'body' => 'Fourth post body', + 'author_id' => 2 + )); + + $this->assertTrue($TestModel->saveAll($data)); + + $result = $TestModel->find('all', array('recursive' => -1, 'order' => 'Post.id ASC')); + $expected = array( + array( + 'Post' => array( + 'id' => '1', + 'author_id' => '1', + 'title' => 'Baleeted First Post', + 'body' => 'Baleeted!', + 'published' => 'N', + 'created' => '2007-03-18 10:39:23' + )), + array( + 'Post' => array( + 'id' => '2', + 'author_id' => '3', + 'title' => 'Just update the title', + 'body' => 'Second Post Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:41:23' + )), + array( + 'Post' => array( + 'id' => '3', + 'author_id' => '1', + 'title' => 'Third Post', + 'body' => 'Third Post Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:43:23', + 'updated' => '2007-03-18 10:45:31' + )), + array( + 'Post' => array( + 'id' => '4', + 'author_id' => '2', + 'title' => 'Creating a fourth post', + 'body' => 'Fourth post body', + 'published' => 'N' + ))); + $this->assertEquals(self::date(), $result[0]['Post']['updated']); + $this->assertEquals(self::date(), $result[1]['Post']['updated']); + $this->assertEquals(self::date(), $result[3]['Post']['created']); + $this->assertEquals(self::date(), $result[3]['Post']['updated']); + unset($result[0]['Post']['updated'], $result[1]['Post']['updated']); + unset($result[3]['Post']['created'], $result[3]['Post']['updated']); + $this->assertEquals($expected, $result); + + $TestModel->validate = array('title' => 'notEmpty', 'author_id' => 'numeric'); + $data = array( + array( + 'id' => '1', + 'title' => 'Un-Baleeted First Post', + 'body' => 'Not Baleeted!', + 'published' => 'Y' + ), + array( + 'id' => '2', + 'title' => '', + 'body' => 'Trying to get away with an empty title' + )); + $result = $TestModel->saveAll($data); + $this->assertFalse($result); + + $result = $TestModel->find('all', array('recursive' => -1, 'order' => 'Post.id ASC')); + $errors = array(1 => array('title' => array('This field cannot be left blank'))); + $transactionWorked = Set::matches('/Post[1][title=Baleeted First Post]', $result); + if (!$transactionWorked) { + $this->assertTrue(Set::matches('/Post[1][title=Un-Baleeted First Post]', $result)); + $this->assertTrue(Set::matches('/Post[2][title=Just update the title]', $result)); + } + + $this->assertEquals($errors, $TestModel->validationErrors); + + $TestModel->validate = array('title' => 'notEmpty', 'author_id' => 'numeric'); + $data = array( + array( + 'id' => '1', + 'title' => 'Un-Baleeted First Post', + 'body' => 'Not Baleeted!', + 'published' => 'Y' + ), + array( + 'id' => '2', + 'title' => '', + 'body' => 'Trying to get away with an empty title' + )); + $result = $TestModel->saveAll($data, array('validate' => true, 'atomic' => false)); + $this->assertEquals(array(true, false), $result); + $result = $TestModel->find('all', array('recursive' => -1, 'order' => 'Post.id ASC')); + $errors = array(1 => array('title' => array('This field cannot be left blank'))); + $expected = array( + array( + 'Post' => array( + 'id' => '1', + 'author_id' => '1', + 'title' => 'Un-Baleeted First Post', + 'body' => 'Not Baleeted!', + 'published' => 'Y', + 'created' => '2007-03-18 10:39:23' + ) + ), + array( + 'Post' => array( + 'id' => '2', + 'author_id' => '3', + 'title' => 'Just update the title', + 'body' => 'Second Post Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:41:23' + ) + ), + array( + 'Post' => array( + 'id' => '3', + 'author_id' => '1', + 'title' => 'Third Post', + 'body' => 'Third Post Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:43:23', + 'updated' => '2007-03-18 10:45:31' + ) + ), + array( + 'Post' => array( + 'id' => '4', + 'author_id' => '2', + 'title' => 'Creating a fourth post', + 'body' => 'Fourth post body', + 'published' => 'N' + ) + ) + ); + + $this->assertEquals(self::date(), $result[0]['Post']['updated']); + $this->assertEquals(self::date(), $result[1]['Post']['updated']); + $this->assertEquals(self::date(), $result[3]['Post']['updated']); + $this->assertEquals(self::date(), $result[3]['Post']['created']); + unset( + $result[0]['Post']['updated'], $result[1]['Post']['updated'], + $result[3]['Post']['updated'], $result[3]['Post']['created'] + ); + $this->assertEquals($expected, $result); + $this->assertEquals($errors, $TestModel->validationErrors); + + $data = array( + array( + 'id' => '1', + 'title' => 'Re-Baleeted First Post', + 'body' => 'Baleeted!', + 'published' => 'N' + ), + array( + 'id' => '2', + 'title' => '', + 'body' => 'Trying to get away with an empty title' + )); + $this->assertFalse($TestModel->saveAll($data, array('validate' => 'first'))); + + $result = $TestModel->find('all', array('recursive' => -1, 'order' => 'Post.id ASC')); + unset( + $result[0]['Post']['updated'], $result[1]['Post']['updated'], + $result[3]['Post']['updated'], $result[3]['Post']['created'] + ); + $this->assertEquals($expected, $result); + $this->assertEquals($errors, $TestModel->validationErrors); + } + +/** + * testSaveAllValidationOnly method + * + * @return void + */ + public function testSaveAllValidationOnly() { + $this->loadFixtures('Comment', 'Attachment'); + $TestModel = new Comment(); + $TestModel->Attachment->validate = array('attachment' => 'notEmpty'); + + $data = array( + 'Comment' => array( + 'comment' => 'This is the comment' + ), + 'Attachment' => array( + 'attachment' => '' + ) + ); + + $result = $TestModel->saveAll($data, array('validate' => 'only')); + $this->assertFalse($result); + + $TestModel = new Article(); + $TestModel->validate = array('title' => 'notEmpty'); + $result = $TestModel->saveAll( + array( + 0 => array('title' => ''), + 1 => array('title' => 'title 1'), + 2 => array('title' => 'title 2'), + ), + array('validate' => 'only') + ); + $this->assertFalse($result); + $expected = array( + 0 => array('title' => array('This field cannot be left blank')), + ); + $this->assertEquals($expected, $TestModel->validationErrors); + + $result = $TestModel->saveAll( + array( + 0 => array('title' => 'title 0'), + 1 => array('title' => ''), + 2 => array('title' => 'title 2'), + ), + array('validate' => 'only') + ); + $this->assertFalse($result); + $expected = array( + 1 => array('title' => array('This field cannot be left blank')), + ); + $this->assertEquals($expected, $TestModel->validationErrors); + } + +/** + * testSaveAllValidateFirst method + * + * @return void + */ + public function testSaveAllValidateFirst() { + $this->loadFixtures('Article', 'Comment', 'Attachment', 'User', 'ArticlesTag', 'Tag'); + $model = new Article(); + $model->deleteAll(true); + + $model->Comment->validate = array('comment' => 'notEmpty'); + $result = $model->saveAll(array( + 'Article' => array( + 'title' => 'Post with Author', + 'body' => 'This post will be saved author' + ), + 'Comment' => array( + array('comment' => 'First new comment'), + array('comment' => '') + ) + ), array('validate' => 'first')); + + $this->assertFalse($result); + + $result = $model->find('all'); + $this->assertEquals(array(), $result); + $expected = array('Comment' => array( + 1 => array('comment' => array('This field cannot be left blank')) + )); + + $this->assertEquals($expected['Comment'], $model->Comment->validationErrors); + + $this->assertSame($model->Comment->find('count'), 0); + + $result = $model->saveAll( + array( + 'Article' => array( + 'title' => 'Post with Author', + 'body' => 'This post will be saved with an author', + 'user_id' => 2 + ), + 'Comment' => array( + array( + 'comment' => 'Only new comment', + 'user_id' => 2 + ))), + array('validate' => 'first') + ); + + $this->assertSame($result, true); + + $result = $model->Comment->find('all'); + $this->assertSame(count($result), 1); + $result = Hash::extract($result, '{n}.Comment.article_id'); + $this->assertEquals(4, $result[0]); + + $model->deleteAll(true); + $data = array( + 'Article' => array( + 'title' => 'Post with Author saveAlled from comment', + 'body' => 'This post will be saved with an author', + 'user_id' => 2 + ), + 'Comment' => array( + 'comment' => 'Only new comment', 'user_id' => 2 + )); + + $result = $model->Comment->saveAll($data, array('validate' => 'first')); + $this->assertFalse(empty($result)); + + $result = $model->find('all'); + $this->assertEquals( + $result[0]['Article']['title'], + 'Post with Author saveAlled from comment' + ); + $this->assertEquals('Only new comment', $result[0]['Comment'][0]['comment']); + } + +/** + * test saveAll()'s return is correct when using atomic = false and validate = first. + * + * @return void + */ + public function testSaveAllValidateFirstAtomicFalse() { + $this->loadFixtures('Something'); + $Something = new Something(); + $invalidData = array( + array( + 'title' => 'foo', + 'body' => 'bar', + 'published' => 'baz', + ), + array( + 'body' => 3, + 'published' => 'sd', + ), + ); + $Something->create(); + $Something->validate = array( + 'title' => array( + 'rule' => 'alphaNumeric', + 'required' => true, + ), + 'body' => array( + 'rule' => 'alphaNumeric', + 'required' => true, + 'allowEmpty' => true, + ), + ); + $result = $Something->saveAll($invalidData, array( + 'atomic' => false, + 'validate' => 'first', + )); + $expected = array(true, false); + $this->assertEquals($expected, $result); + + $Something = new Something(); + $validData = array( + array( + 'title' => 'title value', + 'body' => 'body value', + 'published' => 'baz', + ), + array( + 'title' => 'valid', + 'body' => 'this body', + 'published' => 'sd', + ), + ); + $Something->create(); + $result = $Something->saveAll($validData, array( + 'atomic' => false, + 'validate' => 'first', + )); + $expected = array(true, true); + $this->assertEquals($expected, $result); + } + +/** + * testSaveAllHasManyValidationOnly method + * + * @return void + */ + public function testSaveAllHasManyValidationOnly() { + $this->loadFixtures('Article', 'Comment', 'Attachment'); + $TestModel = new Article(); + $TestModel->belongsTo = $TestModel->hasAndBelongsToMany = array(); + $TestModel->Comment->validate = array('comment' => 'notEmpty'); + + $result = $TestModel->saveAll( + array( + 'Article' => array('id' => 2), + 'Comment' => array( + array( + 'id' => 1, + 'comment' => '', + 'published' => 'Y', + 'user_id' => 1), + array( + 'id' => 2, + 'comment' => + 'comment', + 'published' => 'Y', + 'user_id' => 1 + ))), + array('validate' => 'only') + ); + $this->assertFalse($result); + + $result = $TestModel->saveAll( + array( + 'Article' => array('id' => 2), + 'Comment' => array( + array( + 'id' => 1, + 'comment' => '', + 'published' => 'Y', + 'user_id' => 1 + ), + array( + 'id' => 2, + 'comment' => 'comment', + 'published' => 'Y', + 'user_id' => 1 + ), + array( + 'id' => 3, + 'comment' => '', + 'published' => 'Y', + 'user_id' => 1 + ))), + array( + 'validate' => 'only', + 'atomic' => false + )); + $expected = array( + 'Article' => true, + 'Comment' => array(false, true, false) + ); + $this->assertSame($expected, $result); + + $expected = array('Comment' => array( + 0 => array('comment' => array('This field cannot be left blank')), + 2 => array('comment' => array('This field cannot be left blank')) + )); + $this->assertEquals($expected, $TestModel->validationErrors); + + $expected = array( + 0 => array('comment' => array('This field cannot be left blank')), + 2 => array('comment' => array('This field cannot be left blank')) + ); + $this->assertEquals($expected, $TestModel->Comment->validationErrors); + } + +/** + * test that saveAll behaves like plain save() when supplied empty data + * + * @link http://cakephp.lighthouseapp.com/projects/42648/tickets/277-test-saveall-with-validation-returns-incorrect-boolean-when-saving-empty-data + * @return void + */ + public function testSaveAllEmptyData() { + $this->skipIf($this->db instanceof Sqlserver, 'This test is not compatible with SQL Server.'); + + $this->loadFixtures('Article', 'ProductUpdateAll', 'Comment', 'Attachment'); + $model = new Article(); + $result = $model->saveAll(array(), array('validate' => 'first')); + $this->assertFalse(empty($result)); + + $model = new ProductUpdateAll(); + $result = $model->saveAll(array()); + $this->assertFalse($result); + } + +/** + * testSaveAssociated method + * + * @return void + */ + public function testSaveAssociated() { + $this->loadFixtures('Post', 'Author', 'Comment', 'Attachment', 'Article', 'User'); + $TestModel = new Post(); + + $result = $TestModel->find('all'); + $this->assertEquals(3, count($result)); + $this->assertFalse(isset($result[3])); + + $TestModel->saveAssociated(array( + 'Post' => array( + 'title' => 'Post with Author', + 'body' => 'This post will be saved with an author' + ), + 'Author' => array( + 'user' => 'bob', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf90' + ))); + + $result = $TestModel->find('all', array('order' => array('Post.id ' => 'ASC'))); + $expected = array( + 'Post' => array( + 'id' => '4', + 'author_id' => '5', + 'title' => 'Post with Author', + 'body' => 'This post will be saved with an author', + 'published' => 'N' + ), + 'Author' => array( + 'id' => '5', + 'user' => 'bob', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf90', + 'test' => 'working' + )); + $this->assertEquals(self::date(), $result[3]['Post']['updated']); + $this->assertEquals(self::date(), $result[3]['Post']['created']); + $this->assertEquals(self::date(), $result[3]['Author']['created']); + $this->assertEquals(self::date(), $result[3]['Author']['updated']); + unset( + $result[3]['Post']['updated'], $result[3]['Post']['created'], + $result[3]['Author']['updated'], $result[3]['Author']['created'] + ); + $this->assertEquals($expected, $result[3]); + $this->assertEquals(4, count($result)); + + $TestModel = new Comment(); + $result = $TestModel->saveAssociated(array( + 'Comment' => array( + 'article_id' => 2, + 'user_id' => 2, + 'comment' => 'New comment with attachment', + 'published' => 'Y' + ), + 'Attachment' => array( + 'attachment' => 'some_file.tgz' + ))); + $this->assertFalse(empty($result)); + + $result = $TestModel->find('all'); + $expected = array( + 'id' => '7', + 'article_id' => '2', + 'user_id' => '2', + 'comment' => 'New comment with attachment', + 'published' => 'Y' + ); + $this->assertEquals(self::date(), $result[6]['Comment']['updated']); + $this->assertEquals(self::date(), $result[6]['Comment']['created']); + unset($result[6]['Comment']['updated'], $result[6]['Comment']['created']); + $this->assertEquals($expected, $result[6]['Comment']); + + $expected = array( + 'id' => '2', + 'comment_id' => '7', + 'attachment' => 'some_file.tgz' + ); + $this->assertEquals(self::date(), $result[6]['Attachment']['updated']); + $this->assertEquals(self::date(), $result[6]['Attachment']['created']); + unset($result[6]['Attachment']['updated'], $result[6]['Attachment']['created']); + $this->assertEquals($expected, $result[6]['Attachment']); + } + +/** + * testSaveMany method + * + * @return void + */ + public function testSaveMany() { + $this->loadFixtures('Post'); + $TestModel = new Post(); + $TestModel->deleteAll(true); + $this->assertEquals(array(), $TestModel->find('all')); + + // SQLite seems to reset the PK counter when that happens, so we need this to make the tests pass + $this->db->truncate($TestModel); + + $TestModel->saveMany(array( + array( + 'title' => 'Multi-record post 1', + 'body' => 'First multi-record post', + 'author_id' => 2 + ), + array( + 'title' => 'Multi-record post 2', + 'body' => 'Second multi-record post', + 'author_id' => 2 + ))); + + $result = $TestModel->find('all', array( + 'recursive' => -1, + 'order' => 'Post.id ASC' + )); + $expected = array( + array( + 'Post' => array( + 'id' => '1', + 'author_id' => '2', + 'title' => 'Multi-record post 1', + 'body' => 'First multi-record post', + 'published' => 'N' + ) + ), + array( + 'Post' => array( + 'id' => '2', + 'author_id' => '2', + 'title' => 'Multi-record post 2', + 'body' => 'Second multi-record post', + 'published' => 'N' + ) + ) + ); + $this->assertEquals(self::date(), $result[0]['Post']['updated']); + $this->assertEquals(self::date(), $result[0]['Post']['created']); + $this->assertEquals(self::date(), $result[1]['Post']['updated']); + $this->assertEquals(self::date(), $result[1]['Post']['created']); + unset($result[0]['Post']['updated'], $result[0]['Post']['created']); + unset($result[1]['Post']['updated'], $result[1]['Post']['created']); + $this->assertEquals($expected, $result); + } + +/** + * Test SaveAssociated with Habtm relations + * + * @return void + */ + public function testSaveAssociatedHabtm() { + $this->loadFixtures('Article', 'Tag', 'Comment', 'User', 'ArticlesTag'); + $data = array( + 'Article' => array( + 'user_id' => 1, + 'title' => 'Article Has and belongs to Many Tags' + ), + 'Tag' => array( + 'Tag' => array(1, 2) + ), + 'Comment' => array( + array( + 'comment' => 'Article comment', + 'user_id' => 1 + ))); + $Article = new Article(); + $result = $Article->saveAssociated($data); + $this->assertFalse(empty($result)); + + $result = $Article->read(); + $this->assertEquals(2, count($result['Tag'])); + $this->assertEquals('tag1', $result['Tag'][0]['tag']); + $this->assertEquals(1, count($result['Comment'])); + $this->assertEquals(1, count($result['Comment'][0]['comment'])); + } + +/** + * Test SaveAssociated with Habtm relations and extra join table fields + * + * @return void + */ + public function testSaveAssociatedHabtmWithExtraJoinTableFields() { + $this->loadFixtures('Something', 'SomethingElse', 'JoinThing'); + + $data = array( + 'Something' => array( + 'id' => 4, + 'title' => 'Extra Fields', + 'body' => 'Extra Fields Body', + 'published' => '1' + ), + 'SomethingElse' => array( + array('something_else_id' => 1, 'doomed' => '1'), + array('something_else_id' => 2, 'doomed' => '0'), + array('something_else_id' => 3, 'doomed' => '1') + ) + ); + + $Something = new Something(); + $result = $Something->saveAssociated($data); + $this->assertFalse(empty($result)); + $result = $Something->read(); + + $this->assertEquals(3, count($result['SomethingElse'])); + $this->assertTrue(Set::matches('/Something[id=4]', $result)); + + $this->assertTrue(Set::matches('/SomethingElse[id=1]', $result)); + $this->assertTrue(Set::matches('/SomethingElse[id=1]/JoinThing[something_else_id=1]', $result)); + $this->assertTrue(Set::matches('/SomethingElse[id=1]/JoinThing[doomed=1]', $result)); + + $this->assertTrue(Set::matches('/SomethingElse[id=2]', $result)); + $this->assertTrue(Set::matches('/SomethingElse[id=2]/JoinThing[something_else_id=2]', $result)); + $this->assertTrue(Set::matches('/SomethingElse[id=2]/JoinThing[doomed=0]', $result)); + + $this->assertTrue(Set::matches('/SomethingElse[id=3]', $result)); + $this->assertTrue(Set::matches('/SomethingElse[id=3]/JoinThing[something_else_id=3]', $result)); + $this->assertTrue(Set::matches('/SomethingElse[id=3]/JoinThing[doomed=1]', $result)); + } + +/** + * testSaveAssociatedHasOne method + * + * @return void + */ + public function testSaveAssociatedHasOne() { + $model = new Comment(); + $model->deleteAll(true); + $this->assertEquals(array(), $model->find('all')); + + $model->Attachment->deleteAll(true); + $this->assertEquals(array(), $model->Attachment->find('all')); + + $this->assertTrue($model->saveAssociated(array( + 'Comment' => array( + 'comment' => 'Comment with attachment', + 'article_id' => 1, + 'user_id' => 1 + ), + 'Attachment' => array( + 'attachment' => 'some_file.zip' + )))); + $result = $model->find('all', array('fields' => array( + 'Comment.id', 'Comment.comment', 'Attachment.id', + 'Attachment.comment_id', 'Attachment.attachment' + ))); + $expected = array(array( + 'Comment' => array( + 'id' => '1', + 'comment' => 'Comment with attachment' + ), + 'Attachment' => array( + 'id' => '1', + 'comment_id' => '1', + 'attachment' => 'some_file.zip' + ))); + $this->assertEquals($expected, $result); + + $model->Attachment->bindModel(array('belongsTo' => array('Comment')), false); + $data = array( + 'Comment' => array( + 'comment' => 'Comment with attachment', + 'article_id' => 1, + 'user_id' => 1 + ), + 'Attachment' => array( + 'attachment' => 'some_file.zip' + )); + $this->assertTrue($model->saveAssociated($data, array('validate' => 'first'))); + } + +/** + * testSaveAssociatedBelongsTo method + * + * @return void + */ + public function testSaveAssociatedBelongsTo() { + $model = new Comment(); + $model->deleteAll(true); + $this->assertEquals(array(), $model->find('all')); + + $model->Article->deleteAll(true); + $this->assertEquals(array(), $model->Article->find('all')); + + $this->assertTrue($model->saveAssociated(array( + 'Comment' => array( + 'comment' => 'Article comment', + 'article_id' => 1, + 'user_id' => 1 + ), + 'Article' => array( + 'title' => 'Model Associations 101', + 'user_id' => 1 + )))); + $result = $model->find('all', array('fields' => array( + 'Comment.id', 'Comment.comment', 'Comment.article_id', 'Article.id', 'Article.title' + ))); + $expected = array(array( + 'Comment' => array( + 'id' => '1', + 'article_id' => '1', + 'comment' => 'Article comment' + ), + 'Article' => array( + 'id' => '1', + 'title' => 'Model Associations 101' + ))); + $this->assertEquals($expected, $result); + } + +/** + * testSaveAssociatedHasOneValidation method + * + * @return void + */ + public function testSaveAssociatedHasOneValidation() { + $model = new Comment(); + $model->deleteAll(true); + $this->assertEquals(array(), $model->find('all')); + + $model->Attachment->deleteAll(true); + $this->assertEquals(array(), $model->Attachment->find('all')); + + $model->validate = array('comment' => 'notEmpty'); + $model->Attachment->validate = array('attachment' => 'notEmpty'); + $model->Attachment->bindModel(array('belongsTo' => array('Comment'))); + + $result = $model->saveAssociated( + array( + 'Comment' => array( + 'comment' => '', + 'article_id' => 1, + 'user_id' => 1 + ), + 'Attachment' => array('attachment' => '') + ) + ); + $this->assertFalse($result); + $expected = array( + 'comment' => array( + 'This field cannot be left blank' + ), + 'Attachment' => array( + 'attachment' => array( + 'This field cannot be left blank' + ) + ) + ); + $this->assertEquals($expected, $model->validationErrors); + $this->assertEquals($expected['Attachment'], $model->Attachment->validationErrors); + } + +/** + * testSaveAssociatedAtomic method + * + * @return void + */ + public function testSaveAssociatedAtomic() { + $this->loadFixtures('Article', 'User'); + $TestModel = new Article(); + + $result = $TestModel->saveAssociated(array( + 'Article' => array( + 'title' => 'Post with Author', + 'body' => 'This post will be saved with an author', + 'user_id' => 2 + ), + 'Comment' => array( + array('comment' => 'First new comment', 'user_id' => 2)) + ), array('atomic' => false)); + + $this->assertSame($result, array('Article' => true, 'Comment' => array(true))); + + $result = $TestModel->saveAssociated(array( + 'Article' => array('id' => 2), + 'Comment' => array( + array( + 'comment' => 'First new comment', + 'published' => 'Y', + 'user_id' => 1 + ), + array( + 'comment' => 'Second new comment', + 'published' => 'Y', + 'user_id' => 2 + )) + ), array('validate' => true, 'atomic' => false)); + $this->assertSame($result, array('Article' => true, 'Comment' => array(true, true))); + } + +/** + * testSaveManyAtomic method + * + * @return void + */ + public function testSaveManyAtomic() { + $this->loadFixtures('Article', 'User'); + $TestModel = new Article(); + + $result = $TestModel->saveMany(array( + array( + 'id' => '1', + 'title' => 'Baleeted First Post', + 'body' => 'Baleeted!', + 'published' => 'N' + ), + array( + 'id' => '2', + 'title' => 'Just update the title' + ), + array( + 'title' => 'Creating a fourth post', + 'body' => 'Fourth post body', + 'user_id' => 2 + ) + ), array('atomic' => false)); + $this->assertSame($result, array(true, true, true)); + + $TestModel->validate = array('title' => 'notEmpty', 'author_id' => 'numeric'); + $result = $TestModel->saveMany(array( + array( + 'id' => '1', + 'title' => 'Un-Baleeted First Post', + 'body' => 'Not Baleeted!', + 'published' => 'Y' + ), + array( + 'id' => '2', + 'title' => '', + 'body' => 'Trying to get away with an empty title' + ) + ), array('validate' => true, 'atomic' => false)); + + $this->assertSame(array(true, false), $result); + } + +/** + * testSaveAssociatedHasMany method + * + * @return void + */ + public function testSaveAssociatedHasMany() { + $this->loadFixtures('Article', 'Comment'); + $TestModel = new Article(); + $TestModel->belongsTo = $TestModel->hasAndBelongsToMany = array(); + + $result = $TestModel->saveAssociated(array( + 'Article' => array('id' => 2), + 'Comment' => array( + array('comment' => 'First new comment', 'published' => 'Y', 'user_id' => 1), + array('comment' => 'Second new comment', 'published' => 'Y', 'user_id' => 2) + ) + )); + $this->assertFalse(empty($result)); + + $result = $TestModel->findById(2); + $expected = array( + 'First Comment for Second Article', + 'Second Comment for Second Article', + 'First new comment', + 'Second new comment' + ); + $this->assertEquals($expected, Hash::extract($result['Comment'], '{n}.comment')); + + $result = $TestModel->saveAssociated( + array( + 'Article' => array('id' => 2), + 'Comment' => array( + array( + 'comment' => 'Third new comment', + 'published' => 'Y', + 'user_id' => 1 + ))), + array('atomic' => false) + ); + $this->assertFalse(empty($result)); + + $result = $TestModel->findById(2); + $expected = array( + 'First Comment for Second Article', + 'Second Comment for Second Article', + 'First new comment', + 'Second new comment', + 'Third new comment' + ); + $this->assertEquals($expected, Hash::extract($result['Comment'], '{n}.comment')); + + $TestModel->beforeSaveReturn = false; + $result = $TestModel->saveAssociated( + array( + 'Article' => array('id' => 2), + 'Comment' => array( + array( + 'comment' => 'Fourth new comment', + 'published' => 'Y', + 'user_id' => 1 + ))), + array('atomic' => false) + ); + $this->assertEquals(array('Article' => false), $result); + + $result = $TestModel->findById(2); + $expected = array( + 'First Comment for Second Article', + 'Second Comment for Second Article', + 'First new comment', + 'Second new comment', + 'Third new comment' + ); + $this->assertEquals($expected, Hash::extract($result['Comment'], '{n}.comment')); + } + +/** + * testSaveAssociatedHasManyEmpty method + * + * @return void + */ + public function testSaveAssociatedHasManyEmpty() { + $this->loadFixtures('Article', 'Comment'); + $TestModel = new Article(); + $TestModel->belongsTo = $TestModel->hasAndBelongsToMany = array(); + $TestModel->validate = $TestModel->Comment->validate = array('user_id' => array('notEmpty' => array('rule' => 'notEmpty', 'required' => true))); + + //empty hasMany data is ignored in save + $result = $TestModel->saveAssociated(array( + 'Article' => array('title' => 'title', 'user_id' => 1), + 'Comment' => array() + ), array('validate' => true)); + $this->assertTrue($result); + + $result = $TestModel->saveAssociated(array( + 'Article' => array('title' => 'title', 'user_id' => 1), + 'Comment' => array() + ), array('validate' => true, 'atomic' => false)); + $this->assertEquals(array('Article' => true), $result); + + //empty primary data is not ignored + $result = $TestModel->saveAssociated(array('Article' => array()), array('validate' => true)); + $this->assertFalse($result); + + $result = $TestModel->saveAssociated(array('Article' => array()), array('validate' => true, 'atomic' => false)); + $this->assertEquals(array('Article' => false), $result); + } + +/** + * testSaveAssociatedHasManyValidation method + * + * @return void + */ + public function testSaveAssociatedHasManyValidation() { + $this->loadFixtures('Article', 'Comment'); + $TestModel = new Article(); + $TestModel->belongsTo = $TestModel->hasAndBelongsToMany = array(); + $TestModel->Comment->validate = array('comment' => 'notEmpty'); + + $result = $TestModel->saveAssociated(array( + 'Article' => array('id' => 2), + 'Comment' => array( + array('comment' => '', 'published' => 'Y', 'user_id' => 1), + ) + ), array('validate' => true)); + $this->assertFalse($result); + + $expected = array('Comment' => array( + array('comment' => array('This field cannot be left blank')) + )); + $this->assertEquals($expected, $TestModel->validationErrors); + $expected = array( + array('comment' => array('This field cannot be left blank')) + ); + $this->assertEquals($expected, $TestModel->Comment->validationErrors); + + $result = $TestModel->saveAssociated(array( + 'Article' => array('id' => 2), + 'Comment' => array( + array( + 'comment' => '', + 'published' => 'Y', + 'user_id' => 1 + )) + ), array('validate' => 'first')); + $this->assertFalse($result); + } + +/** + * test saveMany with transactions and ensure there is no missing rollback. + * + * @return void + */ + public function testSaveManyTransactionNoRollback() { + $this->loadFixtures('Post'); + + $this->getMock('DboSource', array('connect', 'rollback', 'describe'), array(), 'MockManyTransactionDboSource'); + $db = ConnectionManager::create('mock_many_transaction', array( + 'datasource' => 'MockManyTransactionDboSource', + )); + + $db->expects($this->once()) + ->method('describe') + ->will($this->returnValue(array())); + $db->expects($this->once())->method('rollback'); + + $Post = new Post('mock_many_transaction'); + + $Post->validate = array( + 'title' => array('rule' => array('notEmpty')) + ); + + $data = array( + array('author_id' => 1, 'title' => 'New Fourth Post'), + array('author_id' => 1, 'title' => '') + ); + $Post->saveMany($data); + } + +/** + * test saveAssociated with transactions and ensure there is no missing rollback. + * + * @return void + */ + public function testSaveAssociatedTransactionNoRollback() { + $testDb = ConnectionManager::getDataSource('test'); + + $mock = $this->getMock( + 'DboSource', + array('connect', 'rollback', 'describe', 'create', 'begin'), + array(), + 'MockAssociatedTransactionDboSource', + false + ); + $db = ConnectionManager::create('mock_assoc_transaction', array( + 'datasource' => 'MockAssociatedTransactionDboSource', + )); + $this->mockObjects[] = $db; + $db->columns = $testDb->columns; + + $db->expects($this->once())->method('rollback'); + $db->expects($this->any())->method('describe') + ->will($this->returnValue(array( + 'id' => array('type' => 'integer', 'length' => 11), + 'title' => array('type' => 'string'), + 'body' => array('type' => 'text'), + 'published' => array('type' => 'string') + ))); + + $Post = new Post(); + $Post->useDbConfig = 'mock_assoc_transaction'; + $Post->Author->useDbConfig = 'mock_assoc_transaction'; + + $Post->Author->validate = array( + 'user' => array('rule' => array('notEmpty')) + ); + + $data = array( + 'Post' => array( + 'title' => 'New post', + 'body' => 'Content', + 'published' => 'Y' + ), + 'Author' => array( + 'user' => '', + 'password' => "sekret" + ) + ); + $Post->saveAssociated($data, array('validate' => true, 'atomic' => true)); + } + +/** + * test saveMany with nested saveMany call. + * + * @return void + */ + public function testSaveManyNestedSaveMany() { + $this->loadFixtures('Sample'); + $TransactionManyTestModel = new TransactionManyTestModel(); + + $data = array( + array('apple_id' => 1, 'name' => 'sample5'), + ); + + $this->assertTrue($TransactionManyTestModel->saveMany($data, array('atomic' => true))); + } + +/** + * testSaveManyTransaction method + * + * @return void + */ + public function testSaveManyTransaction() { + $this->loadFixtures('Post', 'Author', 'Comment', 'Attachment'); + $TestModel = new Post(); + + $TestModel->validate = array('title' => 'notEmpty'); + $data = array( + array('author_id' => 1, 'title' => 'New Fourth Post'), + array('author_id' => 1, 'title' => 'New Fifth Post'), + array('author_id' => 1, 'title' => '') + ); + $this->assertFalse($TestModel->saveMany($data)); + + $result = $TestModel->find('all', array('recursive' => -1)); + $expected = array( + array('Post' => array( + 'id' => '1', + 'author_id' => 1, + 'title' => 'First Post', + 'body' => 'First Post Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:39:23', + 'updated' => '2007-03-18 10:41:31' + )), + array('Post' => array( + 'id' => '2', + 'author_id' => 3, + 'title' => 'Second Post', + 'body' => 'Second Post Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:41:23', + 'updated' => '2007-03-18 10:43:31' + )), + array('Post' => array( + 'id' => '3', + 'author_id' => 1, + 'title' => 'Third Post', + 'body' => 'Third Post Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:43:23', + 'updated' => '2007-03-18 10:45:31' + ))); + + if (count($result) != 3) { + // Database doesn't support transactions + $expected[] = array( + 'Post' => array( + 'id' => '4', + 'author_id' => 1, + 'title' => 'New Fourth Post', + 'body' => null, + 'published' => 'N' + )); + + $expected[] = array( + 'Post' => array( + 'id' => '5', + 'author_id' => 1, + 'title' => 'New Fifth Post', + 'body' => null, + 'published' => 'N', + )); + + $this->assertEquals(self::date(), $result[3]['Post']['created']); + $this->assertEquals(self::date(), $result[3]['Post']['updated']); + $this->assertEquals(self::date(), $result[4]['Post']['created']); + $this->assertEquals(self::date(), $result[4]['Post']['updated']); + unset($result[3]['Post']['created'], $result[3]['Post']['updated']); + unset($result[4]['Post']['created'], $result[4]['Post']['updated']); + $this->assertEquals($expected, $result); + // Skip the rest of the transactional tests + return; + } + + $this->assertEquals($expected, $result); + + $data = array( + array('author_id' => 1, 'title' => 'New Fourth Post'), + array('author_id' => 1, 'title' => ''), + array('author_id' => 1, 'title' => 'New Sixth Post') + ); + $this->assertFalse($TestModel->saveMany($data)); + + $result = $TestModel->find('all', array('recursive' => -1)); + $expected = array( + array('Post' => array( + 'id' => '1', + 'author_id' => 1, + 'title' => 'First Post', + 'body' => 'First Post Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:39:23', + 'updated' => '2007-03-18 10:41:31' + )), + array('Post' => array( + 'id' => '2', + 'author_id' => 3, + 'title' => 'Second Post', + 'body' => 'Second Post Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:41:23', + 'updated' => '2007-03-18 10:43:31' + )), + array('Post' => array( + 'id' => '3', + 'author_id' => 1, + 'title' => 'Third Post', + 'body' => 'Third Post Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:43:23', + 'updated' => '2007-03-18 10:45:31' + ))); + + if (count($result) != 3) { + // Database doesn't support transactions + $expected[] = array( + 'Post' => array( + 'id' => '4', + 'author_id' => 1, + 'title' => 'New Fourth Post', + 'body' => 'Third Post Body', + 'published' => 'N' + )); + + $expected[] = array( + 'Post' => array( + 'id' => '5', + 'author_id' => 1, + 'title' => 'Third Post', + 'body' => 'Third Post Body', + 'published' => 'N' + )); + $this->assertEquals(self::date(), $result[3]['Post']['created']); + $this->assertEquals(self::date(), $result[3]['Post']['updated']); + $this->assertEquals(self::date(), $result[4]['Post']['created']); + $this->assertEquals(self::date(), $result[4]['Post']['updated']); + unset($result[3]['Post']['created'], $result[3]['Post']['updated']); + unset($result[4]['Post']['created'], $result[4]['Post']['updated']); + } + $this->assertEquals($expected, $result); + + $TestModel->validate = array('title' => 'notEmpty'); + $data = array( + array('author_id' => 1, 'title' => 'New Fourth Post'), + array('author_id' => 1, 'title' => 'New Fifth Post'), + array('author_id' => 1, 'title' => 'New Sixth Post') + ); + $this->assertTrue($TestModel->saveMany($data)); + + $result = $TestModel->find('all', array( + 'recursive' => -1, + 'fields' => array('author_id', 'title','body','published'), + 'order' => array('Post.created' => 'ASC') + )); + + $expected = array( + array('Post' => array( + 'author_id' => 1, + 'title' => 'First Post', + 'body' => 'First Post Body', + 'published' => 'Y' + )), + array('Post' => array( + 'author_id' => 3, + 'title' => 'Second Post', + 'body' => 'Second Post Body', + 'published' => 'Y' + )), + array('Post' => array( + 'author_id' => 1, + 'title' => 'Third Post', + 'body' => 'Third Post Body', + 'published' => 'Y' + )), + array('Post' => array( + 'author_id' => 1, + 'title' => 'New Fourth Post', + 'body' => '', + 'published' => 'N' + )), + array('Post' => array( + 'author_id' => 1, + 'title' => 'New Fifth Post', + 'body' => '', + 'published' => 'N' + )), + array('Post' => array( + 'author_id' => 1, + 'title' => 'New Sixth Post', + 'body' => '', + 'published' => 'N' + ))); + $this->assertEquals($expected, $result); + } + +/** + * testSaveManyValidation method + * + * @return void + */ + public function testSaveManyValidation() { + $this->loadFixtures('Post', 'Author', 'Comment', 'Attachment'); + $TestModel = new Post(); + + $data = array( + array( + 'id' => '1', + 'title' => 'Baleeted First Post', + 'body' => 'Baleeted!', + 'published' => 'N' + ), + array( + 'id' => '2', + 'title' => 'Just update the title' + ), + array( + 'title' => 'Creating a fourth post', + 'body' => 'Fourth post body', + 'author_id' => 2 + )); + + $this->assertTrue($TestModel->saveMany($data)); + + $result = $TestModel->find('all', array('recursive' => -1, 'order' => 'Post.id ASC')); + $expected = array( + array( + 'Post' => array( + 'id' => '1', + 'author_id' => '1', + 'title' => 'Baleeted First Post', + 'body' => 'Baleeted!', + 'published' => 'N', + 'created' => '2007-03-18 10:39:23' + ) + ), + array( + 'Post' => array( + 'id' => '2', + 'author_id' => '3', + 'title' => 'Just update the title', + 'body' => 'Second Post Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:41:23' + ) + ), + array( + 'Post' => array( + 'id' => '3', + 'author_id' => '1', + 'title' => 'Third Post', + 'body' => 'Third Post Body', + 'published' => 'Y', + 'created' => '2007-03-18 10:43:23', + 'updated' => '2007-03-18 10:45:31' + )), + array( + 'Post' => array( + 'id' => '4', + 'author_id' => '2', + 'title' => 'Creating a fourth post', + 'body' => 'Fourth post body', + 'published' => 'N' + ) + ) + ); + + $this->assertEquals(self::date(), $result[0]['Post']['updated']); + $this->assertEquals(self::date(), $result[1]['Post']['updated']); + $this->assertEquals(self::date(), $result[3]['Post']['created']); + $this->assertEquals(self::date(), $result[3]['Post']['updated']); + unset($result[0]['Post']['updated'], $result[1]['Post']['updated']); + unset($result[3]['Post']['created'], $result[3]['Post']['updated']); + $this->assertEquals($expected, $result); + + $TestModel->validate = array('title' => 'notEmpty', 'author_id' => 'numeric'); + $data = array( + array( + 'id' => '1', + 'title' => 'Un-Baleeted First Post', + 'body' => 'Not Baleeted!', + 'published' => 'Y' + ), + array( + 'id' => '2', + 'title' => '', + 'body' => 'Trying to get away with an empty title' + )); + $result = $TestModel->saveMany($data); + $this->assertFalse($result); + + $result = $TestModel->find('all', array('recursive' => -1, 'order' => 'Post.id ASC')); + $errors = array(1 => array('title' => array('This field cannot be left blank'))); + $transactionWorked = Set::matches('/Post[1][title=Baleeted First Post]', $result); + if (!$transactionWorked) { + $this->assertTrue(Set::matches('/Post[1][title=Un-Baleeted First Post]', $result)); + $this->assertTrue(Set::matches('/Post[2][title=Just update the title]', $result)); + } + + $this->assertEquals($errors, $TestModel->validationErrors); + + $TestModel->validate = array('title' => 'notEmpty', 'author_id' => 'numeric'); + $data = array( + array( + 'id' => '1', + 'title' => 'Un-Baleeted First Post', + 'body' => 'Not Baleeted!', + 'published' => 'Y' + ), + array( + 'id' => '2', + 'title' => '', + 'body' => 'Trying to get away with an empty title' + )); + $result = $TestModel->saveMany($data, array('validate' => true, 'atomic' => false)); + $this->assertEquals(array(true, false), $result); + + $result = $TestModel->find('all', array( + 'fields' => array('id', 'author_id', 'title', 'body', 'published'), + 'recursive' => -1, + 'order' => 'Post.id ASC' + )); + $errors = array(1 => array('title' => array('This field cannot be left blank'))); + $expected = array( + array( + 'Post' => array( + 'id' => '1', + 'author_id' => '1', + 'title' => 'Un-Baleeted First Post', + 'body' => 'Not Baleeted!', + 'published' => 'Y', + )), + array( + 'Post' => array( + 'id' => '2', + 'author_id' => '3', + 'title' => 'Just update the title', + 'body' => 'Second Post Body', + 'published' => 'Y', + )), + array( + 'Post' => array( + 'id' => '3', + 'author_id' => '1', + 'title' => 'Third Post', + 'body' => 'Third Post Body', + 'published' => 'Y', + )), + array( + 'Post' => array( + 'id' => '4', + 'author_id' => '2', + 'title' => 'Creating a fourth post', + 'body' => 'Fourth post body', + 'published' => 'N', + ))); + $this->assertEquals($expected, $result); + $this->assertEquals($errors, $TestModel->validationErrors); + + $data = array( + array( + 'id' => '1', + 'title' => 'Re-Baleeted First Post', + 'body' => 'Baleeted!', + 'published' => 'N' + ), + array( + 'id' => '2', + 'title' => '', + 'body' => 'Trying to get away with an empty title' + )); + $this->assertFalse($TestModel->saveMany($data, array('validate' => 'first'))); + + $result = $TestModel->find('all', array( + 'fields' => array('id', 'author_id', 'title', 'body', 'published'), + 'recursive' => -1, + 'order' => 'Post.id ASC' + )); + $this->assertEquals($expected, $result); + $this->assertEquals($errors, $TestModel->validationErrors); + } + +/** + * testValidateMany method + * + * @return void + */ + public function testValidateMany() { + $TestModel = new Article(); + $TestModel->validate = array('title' => 'notEmpty'); + $data = array( + 0 => array('title' => ''), + 1 => array('title' => 'title 1'), + 2 => array('title' => 'title 2'), + ); + $result = $TestModel->validateMany($data); + $this->assertFalse($result); + $expected = array( + 0 => array('title' => array('This field cannot be left blank')), + ); + $this->assertEquals($expected, $TestModel->validationErrors); + + $data = array( + 0 => array('title' => 'title 0'), + 1 => array('title' => ''), + 2 => array('title' => 'title 2'), + ); + $result = $TestModel->validateMany($data); + $this->assertFalse($result); + $expected = array( + 1 => array('title' => array('This field cannot be left blank')), + ); + $this->assertEquals($expected, $TestModel->validationErrors); + } + +/** + * testSaveAssociatedValidateFirst method + * + * @return void + */ + public function testSaveAssociatedValidateFirst() { + $this->loadFixtures('Article', 'Comment', 'Attachment'); + $model = new Article(); + $model->deleteAll(true); + + $model->Comment->validate = array('comment' => 'notEmpty'); + $result = $model->saveAssociated(array( + 'Article' => array( + 'title' => 'Post with Author', + 'body' => 'This post will be saved author' + ), + 'Comment' => array( + array('comment' => 'First new comment'), + array('comment' => '') + ) + ), array('validate' => 'first')); + + $this->assertFalse($result); + + $result = $model->find('all'); + $this->assertEquals(array(), $result); + $expected = array('Comment' => array( + 1 => array('comment' => array('This field cannot be left blank')) + )); + + $this->assertEquals($expected['Comment'], $model->Comment->validationErrors); + + $this->assertSame($model->Comment->find('count'), 0); + + $result = $model->saveAssociated( + array( + 'Article' => array( + 'title' => 'Post with Author', + 'body' => 'This post will be saved with an author', + 'user_id' => 2 + ), + 'Comment' => array( + array( + 'comment' => 'Only new comment', + 'user_id' => 2 + ))), + array('validate' => 'first') + ); + + $this->assertSame($result, true); + + $result = $model->Comment->find('all'); + $this->assertSame(count($result), 1); + $result = Hash::extract($result, '{n}.Comment.article_id'); + $this->assertEquals(4, $result[0]); + + $model->deleteAll(true); + $data = array( + 'Article' => array( + 'title' => 'Post with Author saveAlled from comment', + 'body' => 'This post will be saved with an author', + 'user_id' => 2 + ), + 'Comment' => array( + 'comment' => 'Only new comment', 'user_id' => 2 + )); + + $result = $model->Comment->saveAssociated($data, array('validate' => 'first')); + $this->assertFalse(empty($result)); + + $result = $model->find('all'); + $this->assertEquals( + 'Post with Author saveAlled from comment', + $result[0]['Article']['title'] + ); + $this->assertEquals('Only new comment', $result[0]['Comment'][0]['comment']); + } + +/** + * test saveMany()'s return is correct when using atomic = false and validate = first. + * + * @return void + */ + public function testSaveManyValidateFirstAtomicFalse() { + $Something = new Something(); + $invalidData = array( + array( + 'title' => 'foo', + 'body' => 'bar', + 'published' => 'baz', + ), + array( + 'body' => 3, + 'published' => 'sd', + ), + ); + $Something->create(); + $Something->validate = array( + 'title' => array( + 'rule' => 'alphaNumeric', + 'required' => true, + ), + 'body' => array( + 'rule' => 'alphaNumeric', + 'required' => true, + 'allowEmpty' => true, + ), + ); + $result = $Something->saveMany($invalidData, array( + 'atomic' => false, + 'validate' => 'first', + )); + $expected = array(true, false); + $this->assertEquals($expected, $result); + + $Something = new Something(); + $validData = array( + array( + 'title' => 'title value', + 'body' => 'body value', + 'published' => 'baz', + ), + array( + 'title' => 'valid', + 'body' => 'this body', + 'published' => 'sd', + ), + ); + $Something->create(); + $result = $Something->saveMany($validData, array( + 'atomic' => false, + 'validate' => 'first', + )); + $expected = array(true, true); + $this->assertEquals($expected, $result); + } + +/** + * testValidateAssociated method + * + * @return void + */ + public function testValidateAssociated() { + $this->loadFixtures('Attachment', 'Article', 'Comment'); + $TestModel = new Comment(); + $TestModel->Attachment->validate = array('attachment' => 'notEmpty'); + + $data = array( + 'Comment' => array( + 'comment' => 'This is the comment' + ), + 'Attachment' => array( + 'attachment' => '' + ) + ); + + $result = $TestModel->validateAssociated($data); + $this->assertFalse($result); + + $TestModel = new Article(); + $TestModel->belongsTo = $TestModel->hasAndBelongsToMany = array(); + $TestModel->Comment->validate = array('comment' => 'notEmpty'); + + $data = array( + 'Article' => array('id' => 2), + 'Comment' => array( + array( + 'id' => 1, + 'comment' => '', + 'published' => 'Y', + 'user_id' => 1), + array( + 'id' => 2, + 'comment' => + 'comment', + 'published' => 'Y', + 'user_id' => 1 + ))); + $result = $TestModel->validateAssociated($data); + $this->assertFalse($result); + + $data = array( + 'Article' => array('id' => 2), + 'Comment' => array( + array( + 'id' => 1, + 'comment' => '', + 'published' => 'Y', + 'user_id' => 1 + ), + array( + 'id' => 2, + 'comment' => 'comment', + 'published' => 'Y', + 'user_id' => 1 + ), + array( + 'id' => 3, + 'comment' => '', + 'published' => 'Y', + 'user_id' => 1 + ))); + $result = $TestModel->validateAssociated($data, array( + 'atomic' => false + )); + $expected = array( + 'Article' => true, + 'Comment' => array(false, true, false) + ); + $this->assertSame($expected, $result); + + $expected = array('Comment' => array( + 0 => array('comment' => array('This field cannot be left blank')), + 2 => array('comment' => array('This field cannot be left blank')) + )); + $this->assertEquals($expected, $TestModel->validationErrors); + + $expected = array( + 0 => array('comment' => array('This field cannot be left blank')), + 2 => array('comment' => array('This field cannot be left blank')) + ); + $this->assertEquals($expected, $TestModel->Comment->validationErrors); + } + +/** + * test that saveMany behaves like plain save() when suplied empty data + * + * @link http://cakephp.lighthouseapp.com/projects/42648/tickets/277-test-saveall-with-validation-returns-incorrect-boolean-when-saving-empty-data + * @return void + */ + public function testSaveManyEmptyData() { + $this->skipIf($this->db instanceof Sqlserver, 'This test is not compatible with SQL Server.'); + + $this->loadFixtures('Article', 'ProductUpdateAll', 'Comment', 'Attachment'); + $model = new Article(); + $result = $model->saveMany(array(), array('validate' => true)); + $this->assertFalse(empty($result)); + + $model = new ProductUpdateAll(); + $result = $model->saveMany(array()); + $this->assertFalse($result); + } + +/** + * test that saveAssociated behaves like plain save() when supplied empty data + * + * @link http://cakephp.lighthouseapp.com/projects/42648/tickets/277-test-saveall-with-validation-returns-incorrect-boolean-when-saving-empty-data + * @return void + */ + public function testSaveAssociatedEmptyData() { + $this->skipIf($this->db instanceof Sqlserver, 'This test is not compatible with SQL Server.'); + + $this->loadFixtures('Article', 'ProductUpdateAll', 'Comment', 'Attachment'); + $model = new Article(); + $result = $model->saveAssociated(array(), array('validate' => true)); + $this->assertFalse(empty($result)); + + $model = new ProductUpdateAll(); + $result = $model->saveAssociated(array()); + $this->assertFalse($result); + } + +/** + * testUpdateWithCalculation method + * + * @return void + */ + public function testUpdateWithCalculation() { + $this->loadFixtures('DataTest'); + $model = new DataTest(); + $model->deleteAll(true); + $result = $model->saveMany(array( + array('count' => 5, 'float' => 1.1), + array('count' => 3, 'float' => 1.2), + array('count' => 4, 'float' => 1.3), + array('count' => 1, 'float' => 2.0), + )); + $this->assertFalse(empty($result)); + + $result = Hash::extract($model->find('all', array('fields' => 'count')), '{n}.DataTest.count'); + $this->assertEquals(array(5, 3, 4, 1), $result); + + $this->assertTrue($model->updateAll(array('count' => 'count + 2'))); + $result = Hash::extract($model->find('all', array('fields' => 'count')), '{n}.DataTest.count'); + $this->assertEquals(array(7, 5, 6, 3), $result); + + $this->assertTrue($model->updateAll(array('DataTest.count' => 'DataTest.count - 1'))); + $result = Hash::extract($model->find('all', array('fields' => 'count')), '{n}.DataTest.count'); + $this->assertEquals(array(6, 4, 5, 2), $result); + } + + public function testToggleBoolFields() { + $this->loadFixtures('CounterCacheUser', 'CounterCachePost'); + $Post = new CounterCachePost(); + $Post->unbindModel(array('belongsTo' => array('User')), true); + + $true = array('Post' => array('published' => true, 'id' => 2)); + $false = array('Post' => array('published' => false, 'id' => 2)); + $fields = array('Post.published', 'Post.id'); + $updateConditions = array('Post.id' => 2); + + // check its true + $result = $Post->find('first', array('conditions' => $updateConditions, 'fields' => $fields)); + $this->assertEquals($true, $result); + + // Testing without the alias + $this->assertTrue($Post->updateAll(array('published' => 'NOT published'), $updateConditions)); + $result = $Post->find('first', array('conditions' => $updateConditions, 'fields' => $fields)); + $this->assertEquals($false, $result); + + $this->assertTrue($Post->updateAll(array('published' => 'NOT published'), $updateConditions)); + $result = $Post->find('first', array('conditions' => $updateConditions, 'fields' => $fields)); + $this->assertEquals($true, $result); + + $db = ConnectionManager::getDataSource('test'); + $alias = $db->name('Post.published'); + + // Testing with the alias + $this->assertTrue($Post->updateAll(array('Post.published' => "NOT $alias"), $updateConditions)); + $result = $Post->find('first', array('conditions' => $updateConditions, 'fields' => $fields)); + $this->assertEquals($false, $result); + + $this->assertTrue($Post->updateAll(array('Post.published' => "NOT $alias"), $updateConditions)); + $result = $Post->find('first', array('conditions' => $updateConditions, 'fields' => $fields)); + $this->assertEquals($true, $result); + } + +/** + * TestFindAllWithoutForeignKey + * + * @return void + */ + public function testFindAllForeignKey() { + $this->loadFixtures('ProductUpdateAll', 'GroupUpdateAll'); + $ProductUpdateAll = new ProductUpdateAll(); + + $conditions = array('Group.name' => 'group one'); + + $ProductUpdateAll->bindModel(array( + 'belongsTo' => array( + 'Group' => array('className' => 'GroupUpdateAll') + ) + )); + + $ProductUpdateAll->belongsTo = array( + 'Group' => array('className' => 'GroupUpdateAll', 'foreignKey' => 'group_id') + ); + + $results = $ProductUpdateAll->find('all', compact('conditions')); + $this->assertTrue(!empty($results)); + + $ProductUpdateAll->bindModel(array('belongsTo' => array('Group'))); + $ProductUpdateAll->belongsTo = array( + 'Group' => array( + 'className' => 'GroupUpdateAll', + 'foreignKey' => false, + 'conditions' => 'ProductUpdateAll.groupcode = Group.code' + )); + + $resultsFkFalse = $ProductUpdateAll->find('all', compact('conditions')); + $this->assertTrue(!empty($resultsFkFalse)); + $expected = array( + '0' => array( + 'ProductUpdateAll' => array( + 'id' => 1, + 'name' => 'product one', + 'groupcode' => 120, + 'group_id' => 1), + 'Group' => array( + 'id' => 1, + 'name' => 'group one', + 'code' => 120) + ), + '1' => array( + 'ProductUpdateAll' => array( + 'id' => 2, + 'name' => 'product two', + 'groupcode' => 120, + 'group_id' => 1), + 'Group' => array( + 'id' => 1, + 'name' => 'group one', + 'code' => 120) + ) + + ); + $this->assertEquals($expected, $results); + $this->assertEquals($expected, $resultsFkFalse); + } + +/** + * test updateAll with empty values. + * + * @return void + */ + public function testUpdateAllEmptyValues() { + $this->skipIf($this->db instanceof Sqlserver || $this->db instanceof Postgres, 'This test is not compatible with Postgres or SQL Server.'); + + $this->loadFixtures('Author', 'Post'); + $model = new Author(); + $result = $model->updateAll(array('user' => '""')); + $this->assertTrue($result); + } + +/** + * testUpdateAllWithJoins + * + * @return void + */ + public function testUpdateAllWithJoins() { + $this->skipIf(!$this->db instanceof Mysql, 'Currently, there is no way of doing joins in an update statement in postgresql or sqlite'); + + $this->loadFixtures('ProductUpdateAll', 'GroupUpdateAll'); + $ProductUpdateAll = new ProductUpdateAll(); + + $conditions = array('Group.name' => 'group one'); + + $ProductUpdateAll->bindModel(array('belongsTo' => array( + 'Group' => array('className' => 'GroupUpdateAll'))) + ); + + $ProductUpdateAll->updateAll(array('name' => "'new product'"), $conditions); + $results = $ProductUpdateAll->find('all', array( + 'conditions' => array('ProductUpdateAll.name' => 'new product') + )); + $expected = array( + '0' => array( + 'ProductUpdateAll' => array( + 'id' => 1, + 'name' => 'new product', + 'groupcode' => 120, + 'group_id' => 1), + 'Group' => array( + 'id' => 1, + 'name' => 'group one', + 'code' => 120) + ), + '1' => array( + 'ProductUpdateAll' => array( + 'id' => 2, + 'name' => 'new product', + 'groupcode' => 120, + 'group_id' => 1), + 'Group' => array( + 'id' => 1, + 'name' => 'group one', + 'code' => 120))); + + $this->assertEquals($expected, $results); + } + +/** + * testUpdateAllWithoutForeignKey + * + * @return void + */ + public function testUpdateAllWithoutForeignKey() { + $this->skipIf(!$this->db instanceof Mysql, 'Currently, there is no way of doing joins in an update statement in postgresql'); + + $this->loadFixtures('ProductUpdateAll', 'GroupUpdateAll'); + $ProductUpdateAll = new ProductUpdateAll(); + + $conditions = array('Group.name' => 'group one'); + + $ProductUpdateAll->bindModel(array('belongsTo' => array( + 'Group' => array('className' => 'GroupUpdateAll') + ))); + + $ProductUpdateAll->belongsTo = array( + 'Group' => array( + 'className' => 'GroupUpdateAll', + 'foreignKey' => false, + 'conditions' => 'ProductUpdateAll.groupcode = Group.code' + ) + ); + + $ProductUpdateAll->updateAll(array('name' => "'new product'"), $conditions); + $resultsFkFalse = $ProductUpdateAll->find('all', array('conditions' => array('ProductUpdateAll.name' => 'new product'))); + $expected = array( + '0' => array( + 'ProductUpdateAll' => array( + 'id' => 1, + 'name' => 'new product', + 'groupcode' => 120, + 'group_id' => 1), + 'Group' => array( + 'id' => 1, + 'name' => 'group one', + 'code' => 120) + ), + '1' => array( + 'ProductUpdateAll' => array( + 'id' => 2, + 'name' => 'new product', + 'groupcode' => 120, + 'group_id' => 1), + 'Group' => array( + 'id' => 1, + 'name' => 'group one', + 'code' => 120))); + $this->assertEquals($expected, $resultsFkFalse); + } + +/** + * test writing floats in german locale. + * + * @return void + */ + public function testWriteFloatAsGerman() { + $restore = setlocale(LC_NUMERIC, 0); + setlocale(LC_NUMERIC, 'de_DE'); + + $model = new DataTest(); + $result = $model->save(array( + 'count' => 1, + 'float' => 3.14593 + )); + $this->assertTrue((bool)$result); + setlocale(LC_NUMERIC, $restore); + } + +/** + * Test returned array contains primary key when save creates a new record + * + * @return void + */ + public function testPkInReturnArrayForCreate() { + $this->loadFixtures('Article'); + $TestModel = new Article(); + + $data = array('Article' => array( + 'user_id' => '1', + 'title' => 'Fourth Article', + 'body' => 'Fourth Article Body', + 'published' => 'Y' + )); + $result = $TestModel->save($data); + $this->assertSame($result['Article']['id'], $TestModel->id); + } + +/** + * testSaveAllFieldListValidateBelongsTo + * + * @return void + */ + public function testSaveAllFieldListValidateBelongsTo() { + $this->loadFixtures('Post', 'Author', 'Comment', 'Attachment'); + $TestModel = new Post(); + + $result = $TestModel->find('all'); + $this->assertEquals(3, count($result)); + $this->assertFalse(isset($result[3])); + + // test belongsTo + $fieldList = array( + 'Post' => array('title', 'author_id'), + 'Author' => array('user') + ); + $TestModel->saveAll(array( + 'Post' => array( + 'title' => 'Post without body', + 'body' => 'This will not be saved', + ), + 'Author' => array( + 'user' => 'bob', + 'test' => 'This will not be saved', + + )), array('fieldList' => $fieldList)); + + $result = $TestModel->find('all'); + $expected = array( + 'Post' => array ( + 'id' => '4', + 'author_id' => '5', + 'title' => 'Post without body', + 'body' => null, + 'published' => 'N', + 'created' => self::date(), + 'updated' => self::date(), + ), + 'Author' => array ( + 'id' => '5', + 'user' => 'bob', + 'password' => null, + 'created' => self::date(), + 'updated' => self::date(), + 'test' => 'working', + ), + ); + $this->assertEquals($expected, $result[3]); + $this->assertEquals(4, count($result)); + $this->assertEquals('', $result[3]['Post']['body']); + $this->assertEquals('working', $result[3]['Author']['test']); + + // test multirecord + $this->db->truncate($TestModel); + + $fieldList = array('title', 'author_id'); + $TestModel->saveAll(array( + array( + 'title' => 'Multi-record post 1', + 'body' => 'First multi-record post', + 'author_id' => 2 + ), + array( + 'title' => 'Multi-record post 2', + 'body' => 'Second multi-record post', + 'author_id' => 2 + )), array('fieldList' => $fieldList)); + + $result = $TestModel->find('all', array( + 'recursive' => -1, + 'order' => 'Post.id ASC' + )); + $expected = array( + array( + 'Post' => array( + 'id' => '1', + 'author_id' => '2', + 'title' => 'Multi-record post 1', + 'body' => '', + 'published' => 'N', + 'created' => self::date(), + 'updated' => self::date() + ) + ), + array( + 'Post' => array( + 'id' => '2', + 'author_id' => '2', + 'title' => 'Multi-record post 2', + 'body' => '', + 'published' => 'N', + 'created' => self::date(), + 'updated' => self::date() + ) + ) + ); + $this->assertEquals($expected, $result); + } + +/** + * testSaveAllFieldListHasMany method + * + * return @void + */ + public function testSaveAllFieldListHasMany() { + $this->loadFixtures('Article', 'Comment'); + $TestModel = new Article(); + $TestModel->belongsTo = $TestModel->hasAndBelongsToMany = array(); + + $this->db->truncate($TestModel); + $this->db->truncate(new Comment()); + + $fieldList = array( + 'Article' => array('id'), + 'Comment' => array('article_id', 'user_id') + ); + $result = $TestModel->saveAll(array( + 'Article' => array('id' => 2, 'title' => 'I will not save'), + 'Comment' => array( + array('comment' => 'First new comment', 'published' => 'Y', 'user_id' => 1), + array('comment' => 'Second new comment', 'published' => 'Y', 'user_id' => 2) + ) + ), array('fieldList' => $fieldList)); + + $result = $TestModel->find('all'); + $this->assertEquals('', $result[0]['Article']['title']); + $this->assertEquals('', $result[0]['Comment'][0]['comment']); + $this->assertEquals('', $result[0]['Comment'][1]['comment']); + } + +/** + * testSaveAllFieldListHasOne method + * + * @return void + */ + public function testSaveAllFieldListHasOne() { + $this->loadFixtures('Attachment', 'Comment', 'Article', 'User'); + $TestModel = new Comment(); + + $TestModel->validate = array('comment' => 'notEmpty'); + $TestModel->Attachment->validate = array('attachment' => 'notEmpty'); + + $record = array( + 'Comment' => array( + 'user_id' => 1, + 'article_id' => 1, + 'comment' => '', + ), + 'Attachment' => array( + 'attachment' => '' + ) + ); + $result = $TestModel->saveAll($record, array('validate' => 'only')); + $this->assertFalse($result); + + $fieldList = array( + 'Comment' => array('id', 'article_id', 'user_id'), + 'Attachment' => array('comment_id') + ); + $result = $TestModel->saveAll($record, array( + 'fieldList' => $fieldList, 'validate' => 'only' + )); + $this->assertTrue($result); + $this->assertEmpty($TestModel->validationErrors); + } + +/** + * testSaveAllDeepFieldListValidateBelongsTo + * + * @return void + */ + public function testSaveAllDeepFieldListValidateBelongsTo() { + $this->loadFixtures('Post', 'Author', 'Comment', 'Attachment', 'Article', 'User'); + $TestModel = new Post(); + $TestModel->Author->bindModel(array('hasMany' => array('Comment' => array('foreignKey' => 'user_id'))), false); + $TestModel->recursive = 2; + + $result = $TestModel->find('all'); + $this->assertEquals(3, count($result)); + $this->assertFalse(isset($result[3])); + + // test belongsTo + $fieldList = array( + 'Post' => array('title', 'author_id'), + 'Author' => array('user'), + 'Comment' => array('comment') + ); + $TestModel->saveAll(array( + 'Post' => array( + 'title' => 'Post without body', + 'body' => 'This will not be saved', + ), + 'Author' => array( + 'user' => 'bob', + 'test' => 'This will not be saved', + 'Comment' => array( + array('id' => 5, 'comment' => 'I am still published', 'published' => 'N')) + + )), array('fieldList' => $fieldList, 'deep' => true)); + + $result = $TestModel->Author->Comment->find('first', array( + 'conditions' => array('Comment.id' => 5), + 'fields' => array('comment', 'published') + )); + $expected = array( + 'Comment' => array( + 'comment' => 'I am still published', + 'published' => 'Y' + ) + ); + $this->assertEquals($expected, $result); + } + +/** + * testSaveAllDeepFieldListHasMany method + * + * return @void + */ + public function testSaveAllDeepFieldListHasMany() { + $this->loadFixtures('Article', 'Comment', 'User'); + $TestModel = new Article(); + $TestModel->belongsTo = $TestModel->hasAndBelongsToMany = array(); + + $this->db->truncate($TestModel); + $this->db->truncate(new Comment()); + + $fieldList = array( + 'Article' => array('id'), + 'Comment' => array('article_id', 'user_id'), + 'User' => array('user') + ); + + $result = $TestModel->saveAll(array( + 'Article' => array('id' => 2, 'title' => 'I will not save'), + 'Comment' => array( + array('comment' => 'First new comment', 'published' => 'Y', 'user_id' => 1), + array( + 'comment' => 'Second new comment', 'published' => 'Y', 'user_id' => 2, + 'User' => array('user' => 'nopassword', 'password' => 'not saved') + ) + ) + ), array('fieldList' => $fieldList, 'deep' => true)); + + $result = $TestModel->Comment->User->find('first', array( + 'conditions' => array('User.user' => 'nopassword'), + 'fields' => array('user', 'password') + )); + $expected = array( + 'User' => array( + 'user' => 'nopassword', + 'password' => '' + ) + ); + $this->assertEquals($expected, $result); + } + +/** + * testSaveAllDeepHasManyBelongsTo method + * + * return @void + */ + public function testSaveAllDeepHasManyBelongsTo() { + $this->loadFixtures('Article', 'Comment', 'User'); + $TestModel = new Article(); + $TestModel->belongsTo = $TestModel->hasAndBelongsToMany = array(); + + $this->db->truncate($TestModel); + $this->db->truncate(new Comment()); + + $result = $TestModel->saveAll(array( + 'Article' => array('id' => 2, 'title' => 'The title'), + 'Comment' => array( + array('comment' => 'First new comment', 'published' => 'Y', 'user_id' => 1), + array( + 'comment' => 'belongsto', 'published' => 'Y', + 'User' => array('user' => 'findme', 'password' => 'somepass') + ) + ) + ), array('deep' => true)); + + $result = $TestModel->Comment->User->find('first', array( + 'conditions' => array('User.user' => 'findme'), + 'fields' => array('id', 'user', 'password') + )); + $expected = array( + 'User' => array( + 'id' => 5, + 'user' => 'findme', + 'password' => 'somepass', + ) + ); + $this->assertEquals($expected, $result); + + $result = $TestModel->Comment->find('first', array( + 'conditions' => array('Comment.user_id' => 5), + 'fields' => array('id', 'comment', 'published', 'user_id') + )); + $expected = array( + 'Comment' => array( + 'id' => 2, + 'comment' => 'belongsto', + 'published' => 'Y', + 'user_id' => 5 + ) + ); + $this->assertEquals($expected, $result); + } + +/** + * testSaveAllDeepHasManyhasMany method + * + * return @void + */ + public function testSaveAllDeepHasManyHasMany() { + $this->loadFixtures('Article', 'Comment', 'User', 'Attachment'); + $TestModel = new Article(); + $TestModel->belongsTo = $TestModel->hasAndBelongsToMany = $TestModel->Comment->belongsTo = array(); + $TestModel->Comment->unbindModel(array('hasOne' => array('Attachment')), false); + $TestModel->Comment->bindModel(array('hasMany' => array('Attachment')), false); + + $this->db->truncate($TestModel); + $this->db->truncate(new Comment()); + $this->db->truncate(new Attachment()); + + $result = $TestModel->saveAll(array( + 'Article' => array('id' => 2, 'title' => 'The title'), + 'Comment' => array( + array('comment' => 'First new comment', 'published' => 'Y', 'user_id' => 1), + array( + 'comment' => 'hasmany', 'published' => 'Y', 'user_id' => 5, + 'Attachment' => array( + array('attachment' => 'first deep attachment'), + array('attachment' => 'second deep attachment'), + ) + ) + ) + ), array('deep' => true)); + + $result = $TestModel->Comment->find('first', array( + 'conditions' => array('Comment.comment' => 'hasmany'), + 'fields' => array('id', 'comment', 'published', 'user_id'), + 'recursive' => -1 + )); + $expected = array( + 'Comment' => array( + 'id' => 2, + 'comment' => 'hasmany', + 'published' => 'Y', + 'user_id' => 5 + ) + ); + $this->assertEquals($expected, $result); + + $result = $TestModel->Comment->Attachment->find('all', array( + 'fields' => array('attachment', 'comment_id'), + 'order' => array('Attachment.id' => 'ASC') + )); + $expected = array( + array('Attachment' => array('attachment' => 'first deep attachment', 'comment_id' => 2)), + array('Attachment' => array('attachment' => 'second deep attachment', 'comment_id' => 2)), + ); + $this->assertEquals($expected, $result); + } + +/** + * testSaveAllDeepOrderHasManyHasMany method + * + * return @void + */ + public function testSaveAllDeepOrderHasManyHasMany() { + $this->loadFixtures('Article', 'Comment', 'User', 'Attachment'); + $TestModel = new Article(); + $TestModel->belongsTo = $TestModel->hasAndBelongsToMany = $TestModel->Comment->belongsTo = array(); + $TestModel->Comment->unbindModel(array('hasOne' => array('Attachment')), false); + $TestModel->Comment->bindModel(array('hasMany' => array('Attachment')), false); + + $this->db->truncate($TestModel); + $this->db->truncate(new Comment()); + $this->db->truncate(new Attachment()); + + $result = $TestModel->saveAll(array( + 'Article' => array('id' => 2, 'title' => 'Comment has its data after Attachment'), + 'Comment' => array( + array( + 'Attachment' => array( + array('attachment' => 'attachment should be created with comment_id'), + array('attachment' => 'comment should be created with article_id'), + ), + 'comment' => 'after associated data', + 'user_id' => 1 + ) + ) + ), array('deep' => true)); + $result = $TestModel->Comment->find('first', array( + 'conditions' => array('Comment.article_id' => 2), + )); + + $this->assertEquals(2, $result['Comment']['article_id']); + $this->assertEquals(2, count($result['Attachment'])); + } + +/** + * testSaveAllDeepEmptyHasManyHasMany method + * + * return @void + */ + public function testSaveAllDeepEmptyHasManyHasMany() { + $this->skipIf(!$this->db instanceof Mysql, 'This test is only compatible with Mysql.'); + $this->loadFixtures('Article', 'Comment', 'User', 'Attachment'); + $TestModel = new Article(); + $TestModel->belongsTo = $TestModel->hasAndBelongsToMany = $TestModel->Comment->belongsTo = array(); + $TestModel->Comment->unbindModel(array('hasOne' => array('Attachment')), false); + $TestModel->Comment->bindModel(array('hasMany' => array('Attachment')), false); + + $this->db->truncate($TestModel); + $this->db->truncate(new Comment()); + $this->db->truncate(new Attachment()); + + $result = $TestModel->saveAll(array( + 'Article' => array('id' => 3, 'title' => 'Comment has no data'), + 'Comment' => array( + array( + 'Attachment' => array( + array('attachment' => 'attachment should be created with comment_id'), + array('attachment' => 'comment should be created with article_id'), + ), + ) + ) + ), array('deep' => true)); + $result = $TestModel->Comment->find('first', array( + 'conditions' => array('Comment.article_id' => 3), + )); + + $this->assertEquals(3, $result['Comment']['article_id']); + $this->assertEquals(2, count($result['Attachment'])); + } + +/** + * testUpdateAllBoolean + * + * return @void + */ + public function testUpdateAllBoolean() { + $this->loadFixtures('Item', 'Syfile', 'Portfolio', 'Image', 'ItemsPortfolio'); + $TestModel = new Item(); + $result = $TestModel->updateAll(array('published' => true)); + $this->assertTrue($result); + + $result = $TestModel->find('first', array('fields' => array('id', 'published'))); + $this->assertEquals(true, $result['Item']['published']); + } + +/** + * testUpdateAllBooleanConditions + * + * return @void + */ + public function testUpdateAllBooleanConditions() { + $this->loadFixtures('Item', 'Syfile', 'Portfolio', 'Image', 'ItemsPortfolio'); + $TestModel = new Item(); + + $result = $TestModel->updateAll(array('published' => true), array('Item.id' => 1)); + $this->assertTrue($result); + $result = $TestModel->find('first', array( + 'fields' => array('id', 'published'), + 'conditions' => array('Item.id' => 1))); + $this->assertEquals(true, $result['Item']['published']); + } + +/** + * testUpdateBoolean + * + * return @void + */ + public function testUpdateBoolean() { + $this->loadFixtures('Item', 'Syfile', 'Portfolio', 'Image', 'ItemsPortfolio'); + $TestModel = new Item(); + + $result = $TestModel->save(array('published' => true, 'id' => 1)); + $this->assertTrue((boolean)$result); + $result = $TestModel->find('first', array( + 'fields' => array('id', 'published'), + 'conditions' => array('Item.id' => 1))); + $this->assertEquals(true, $result['Item']['published']); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Validator/CakeValidationRuleTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Validator/CakeValidationRuleTest.php new file mode 100644 index 0000000..31caf5f --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Validator/CakeValidationRuleTest.php @@ -0,0 +1,155 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/view/1196/Testing CakePHP(tm) Tests + * @package Cake.Test.Case.Model.Validator + * @since CakePHP(tm) v 2.2.0 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ + +App::uses('CakeValidationRule', 'Model/Validator'); + +/** + * CakeValidationRuleTest + * + * @package Cake.Test.Case.Model.Validator + */ +class CakeValidationRuleTest extends CakeTestCase { + +/** + * Auxiliary method to test custom validators + * + * @return boolean + **/ + public function myTestRule() { + return false; + } + +/** + * Auxiliary method to test custom validators + * + * @return boolean + **/ + public function myTestRule2() { + return true; + } + +/** + * Auxiliary method to test custom validators + * + * @return string + **/ + public function myTestRule3() { + return 'string'; + } + +/** + * Test isValid method + * + * @return void + */ + public function testIsValid() { + $def = array('rule' => 'notEmpty', 'message' => 'Can not be empty'); + $data = array( + 'fieldName' => '' + ); + $methods = array(); + + $Rule = new CakeValidationRule($def); + $Rule->process('fieldName', $data, $methods); + $this->assertFalse($Rule->isValid()); + + $data = array('fieldName' => 'not empty'); + $Rule->process('fieldName', $data, $methods); + $this->assertTrue($Rule->isValid()); + } +/** + * tests that passing custom validation methods work + * + * @return void + */ + public function testCustomMethods() { + $def = array('rule' => 'myTestRule'); + $data = array( + 'fieldName' => 'some data' + ); + $methods = array('mytestrule' => array($this, 'myTestRule')); + + $Rule = new CakeValidationRule($def); + $Rule->process('fieldName', $data, $methods); + $this->assertFalse($Rule->isValid()); + + $methods = array('mytestrule' => array($this, 'myTestRule2')); + $Rule->process('fieldName', $data, $methods); + $this->assertTrue($Rule->isValid()); + + $methods = array('mytestrule' => array($this, 'myTestRule3')); + $Rule->process('fieldName', $data, $methods); + $this->assertFalse($Rule->isValid()); + } + +/** + * Test isRequired method + * + * @return void + */ + public function testIsRequired() { + $def = array('rule' => 'notEmpty', 'required' => true); + $Rule = new CakeValidationRule($def); + $this->assertTrue($Rule->isRequired()); + + $def = array('rule' => 'notEmpty', 'required' => false); + $Rule = new CakeValidationRule($def); + $this->assertFalse($Rule->isRequired()); + + $def = array('rule' => 'notEmpty', 'required' => 'create'); + $Rule = new CakeValidationRule($def); + $this->assertTrue($Rule->isRequired()); + + $def = array('rule' => 'notEmpty', 'required' => 'update'); + $Rule = new CakeValidationRule($def); + $this->assertFalse($Rule->isRequired()); + + $Rule->isUpdate(true); + $this->assertTrue($Rule->isRequired()); + } + +/** + * Test isEmptyAllowed method + * + * @return void + */ + public function testIsEmptyAllowed() { + $def = array('rule' => 'aRule', 'allowEmpty' => true); + $Rule = new CakeValidationRule($def); + $this->assertTrue($Rule->isEmptyAllowed()); + + $def = array('rule' => 'aRule', 'allowEmpty' => false); + $Rule = new CakeValidationRule($def); + $this->assertFalse($Rule->isEmptyAllowed()); + + $def = array('rule' => 'notEmpty', 'allowEmpty' => false, 'on' => 'update'); + $Rule = new CakeValidationRule($def); + $this->assertTrue($Rule->isEmptyAllowed()); + + $Rule->isUpdate(true); + $this->assertFalse($Rule->isEmptyAllowed()); + + $def = array('rule' => 'notEmpty', 'allowEmpty' => false, 'on' => 'create'); + $Rule = new CakeValidationRule($def); + $this->assertFalse($Rule->isEmptyAllowed()); + + $Rule->isUpdate(true); + $this->assertTrue($Rule->isEmptyAllowed()); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Validator/CakeValidationSetTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Validator/CakeValidationSetTest.php new file mode 100644 index 0000000..10fa6fd --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/Validator/CakeValidationSetTest.php @@ -0,0 +1,321 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/view/1196/Testing CakePHP(tm) Tests + * @package Cake.Test.Case.Model.Validator + * @since CakePHP(tm) v 2.2.0 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ + +App::uses('CakeValidationSet', 'Model/Validator'); + +/** + * CakeValidationSetTest + * + * @package Cake.Test.Case.Model.Validator + */ +class CakeValidationSetTest extends CakeTestCase { + +/** + * testValidate method + * + * @return void + */ + public function testValidate() { + $Field = new CakeValidationSet('title', 'notEmpty'); + $data = array( + 'title' => '', + 'body' => 'a body' + ); + + $result = $Field->validate($data); + $expected = array('This field cannot be left blank'); + $this->assertEquals($expected, $result); + + $Field = new CakeValidationSet('body', 'notEmpty'); + + $result = $Field->validate($data); + $this->assertEmpty($result); + + $Field = new CakeValidationSet('nothere', array( + 'notEmpty' => array( + 'rule' => 'notEmpty', + 'required' => true + ) + )); + + $result = $Field->validate($data); + $expected = array('notEmpty'); + $this->assertEquals($expected, $result); + + $Field = new CakeValidationSet('body', array( + 'inList' => array( + 'rule' => array('inList', array('test')) + ) + )); + $result = $Field->validate($data); + $expected = array('inList'); + $this->assertEquals($expected, $result); + } + +/** + * testGetRule method + * + * @return void + */ + public function testGetRule() { + $rules = array('notEmpty' => array('rule' => 'notEmpty', 'message' => 'Can not be empty')); + $Field = new CakeValidationSet('title', $rules); + $data = array( + 'title' => '', + 'body' => 'a body' + ); + + $result = $Field->getRule('notEmpty'); + $this->assertInstanceOf('CakeValidationRule', $result); + $this->assertEquals('notEmpty', $result->rule); + $this->assertEquals(null, $result->required); + $this->assertEquals(false, $result->allowEmpty); + $this->assertEquals(null, $result->on); + $this->assertEquals(true, $result->last); + $this->assertEquals('Can not be empty', $result->message); + } + +/** + * testGetRules method + * + * @return void + */ + public function testGetRules() { + $rules = array('notEmpty' => array('rule' => 'notEmpty', 'message' => 'Can not be empty')); + $Field = new CakeValidationSet('title', $rules); + + $result = $Field->getRules(); + $this->assertEquals(array('notEmpty'), array_keys($result)); + $this->assertInstanceOf('CakeValidationRule', $result['notEmpty']); + } + +/** + * testSetRule method + * + * @return void + */ + public function testSetRule() { + $rules = array('notEmpty' => array('rule' => 'notEmpty', 'message' => 'Can not be empty')); + $Field = new CakeValidationSet('title', $rules); + $Rule = new CakeValidationRule($rules['notEmpty']); + + $this->assertEquals($Rule, $Field->getRule('notEmpty')); + + $rules = array('validEmail' => array('rule' => 'email', 'message' => 'Invalid email')); + $Rule = new CakeValidationRule($rules['validEmail']); + $Field->setRule('validEmail', $Rule); + $result = $Field->getRules(); + $this->assertEquals(array('notEmpty', 'validEmail'), array_keys($result)); + + $rules = array('validEmail' => array('rule' => 'email', 'message' => 'Other message')); + $Rule = new CakeValidationRule($rules['validEmail']); + $Field->setRule('validEmail', $Rule); + $result = $Field->getRules(); + $this->assertEquals(array('notEmpty', 'validEmail'), array_keys($result)); + $result = $Field->getRule('validEmail'); + $this->assertInstanceOf('CakeValidationRule', $result); + $this->assertEquals('email', $result->rule); + $this->assertEquals(null, $result->required); + $this->assertEquals(false, $result->allowEmpty); + $this->assertEquals(null, $result->on); + $this->assertEquals(true, $result->last); + $this->assertEquals('Other message', $result->message); + } + +/** + * testSetRules method + * + * @return void + */ + public function testSetRules() { + $rule = array('notEmpty' => array('rule' => 'notEmpty', 'message' => 'Can not be empty')); + $Field = new CakeValidationSet('title', $rule); + $RuleEmpty = new CakeValidationRule($rule['notEmpty']); + + $rule = array('validEmail' => array('rule' => 'email', 'message' => 'Invalid email')); + $RuleEmail = new CakeValidationRule($rule['validEmail']); + + $rules = array('validEmail' => $RuleEmail); + $Field->setRules($rules, false); + $result = $Field->getRules(); + $this->assertEquals(array('validEmail'), array_keys($result)); + + $rules = array('notEmpty' => $RuleEmpty); + $Field->setRules($rules, true); + $result = $Field->getRules(); + $this->assertEquals(array('validEmail', 'notEmpty'), array_keys($result)); + } + +/** + * Tests getting a rule from the set using array access + * + * @return void + */ + public function testArrayAccessGet() { + $Set = new CakeValidationSet('title', array( + 'notEmpty' => array('rule' => 'notEmpty', 'required' => true), + 'numeric' => array('rule' => 'numeric'), + 'other' => array('rule' => array('other', 1)), + )); + + $rule = $Set['notEmpty']; + $this->assertInstanceOf('CakeValidationRule', $rule); + $this->assertEquals('notEmpty', $rule->rule); + + $rule = $Set['numeric']; + $this->assertInstanceOf('CakeValidationRule', $rule); + $this->assertEquals('numeric', $rule->rule); + + $rule = $Set['other']; + $this->assertInstanceOf('CakeValidationRule', $rule); + $this->assertEquals(array('other', 1), $rule->rule); + } + +/** + * Tests checking a rule from the set using array access + * + * @return void + */ + public function testArrayAccessExists() { + $Set = new CakeValidationSet('title', array( + 'notEmpty' => array('rule' => 'notEmpty', 'required' => true), + 'numeric' => array('rule' => 'numeric'), + 'other' => array('rule' => array('other', 1)), + )); + + $this->assertTrue(isset($Set['notEmpty'])); + $this->assertTrue(isset($Set['numeric'])); + $this->assertTrue(isset($Set['other'])); + $this->assertFalse(isset($Set['fail'])); + } + +/** + * Tests setting a rule in the set using array access + * + * @return void + */ + public function testArrayAccessSet() { + $Set = new CakeValidationSet('title', array( + 'notEmpty' => array('rule' => 'notEmpty', 'required' => true), + )); + + $this->assertFalse(isset($Set['other'])); + $Set['other'] = array('rule' => array('other', 1)); + $rule = $Set['other']; + $this->assertInstanceOf('CakeValidationRule', $rule); + $this->assertEquals(array('other', 1), $rule->rule); + + $this->assertFalse(isset($Set['numeric'])); + $Set['numeric'] = new CakeValidationRule(array('rule' => 'numeric')); + $rule = $Set['numeric']; + $this->assertInstanceOf('CakeValidationRule', $rule); + $this->assertEquals('numeric', $rule->rule); + } + +/** + * Tests unseting a rule from the set using array access + * + * @return void + */ + public function testArrayAccessUnset() { + $Set = new CakeValidationSet('title', array( + 'notEmpty' => array('rule' => 'notEmpty', 'required' => true), + 'numeric' => array('rule' => 'numeric'), + 'other' => array('rule' => array('other', 1)), + )); + + unset($Set['notEmpty']); + $this->assertFalse(isset($Set['notEmpty'])); + + unset($Set['numeric']); + $this->assertFalse(isset($Set['notEmpty'])); + + unset($Set['other']); + $this->assertFalse(isset($Set['notEmpty'])); + } + +/** + * Tests it is possible to iterate a validation set object + * + * @return void + */ + public function testIterator() { + $Set = new CakeValidationSet('title', array( + 'notEmpty' => array('rule' => 'notEmpty', 'required' => true), + 'numeric' => array('rule' => 'numeric'), + 'other' => array('rule' => array('other', 1)), + )); + + $i = 0; + foreach ($Set as $name => $rule) { + if ($i === 0) { + $this->assertEquals('notEmpty', $name); + } + if ($i === 1) { + $this->assertEquals('numeric', $name); + } + if ($i === 2) { + $this->assertEquals('other', $name); + } + $this->assertInstanceOf('CakeValidationRule', $rule); + $i++; + } + $this->assertEquals(3, $i); + } + +/** + * Tests countable interface + * + * @return void + */ + public function testCount() { + $Set = new CakeValidationSet('title', array( + 'notEmpty' => array('rule' => 'notEmpty', 'required' => true), + 'numeric' => array('rule' => 'numeric'), + 'other' => array('rule' => array('other', 1)), + )); + $this->assertCount(3, $Set); + + unset($Set['other']); + $this->assertCount(2, $Set); + } + +/** + * Test removeRule method + * + * @return void + */ + public function testRemoveRule() { + $Set = new CakeValidationSet('title', array( + 'notEmpty' => array('rule' => 'notEmpty', 'required' => true), + 'numeric' => array('rule' => 'numeric'), + 'other' => array('rule' => array('other', 1)), + )); + + $Set->removeRule('notEmpty'); + $this->assertFalse(isset($Set['notEmpty'])); + + $Set->removeRule('numeric'); + $this->assertFalse(isset($Set['numeric'])); + + $Set->removeRule('other'); + $this->assertFalse(isset($Set['other'])); + } + +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/models.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/models.php new file mode 100644 index 0000000..b550a0a --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Model/models.php @@ -0,0 +1,4989 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Model + * @since CakePHP(tm) v 1.2.0.6464 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ +App::uses('Model', 'Model'); +/** + * AppModel class + * + * @package Cake.Test.Case.Model + */ +class AppModel extends Model { + +/** + * findMethods property + * + * @var array + */ + public $findMethods = array('published' => true); + +/** + * useDbConfig property + * + * @var array + */ + public $useDbConfig = 'test'; + +/** + * _findPublished custom find + * + * @return array + */ + protected function _findPublished($state, $query, $results = array()) { + if ($state === 'before') { + $query['conditions']['published'] = 'Y'; + return $query; + } + return $results; + } + +} + +/** + * Test class + * + * @package Cake.Test.Case.Model + */ +class Test extends CakeTestModel { + +/** + * useTable property + * + * @var bool false + */ + public $useTable = false; + +/** + * name property + * + * @var string 'Test' + */ + public $name = 'Test'; + +/** + * schema property + * + * @var array + */ + protected $_schema = array( + 'id' => array('type' => 'integer', 'null' => '', 'default' => '1', 'length' => '8', 'key' => 'primary'), + 'name' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'), + 'email' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'), + 'notes' => array('type' => 'text', 'null' => '1', 'default' => 'write some notes here', 'length' => ''), + 'created' => array('type' => 'date', 'null' => '1', 'default' => '', 'length' => ''), + 'updated' => array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => null) + ); + +} + +/** + * TestAlias class + * + * @package Cake.Test.Case.Model + */ +class TestAlias extends CakeTestModel { + +/** + * useTable property + * + * @var bool false + */ + public $useTable = false; + +/** + * name property + * + * @var string 'TestAlias' + */ + public $name = 'TestAlias'; + +/** + * alias property + * + * @var string 'TestAlias' + */ + public $alias = 'TestAlias'; + +/** + * schema property + * + * @var array + */ + protected $_schema = array( + 'id' => array('type' => 'integer', 'null' => '', 'default' => '1', 'length' => '8', 'key' => 'primary'), + 'name' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'), + 'email' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'), + 'notes' => array('type' => 'text', 'null' => '1', 'default' => 'write some notes here', 'length' => ''), + 'created' => array('type' => 'date', 'null' => '1', 'default' => '', 'length' => ''), + 'updated' => array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => null) + ); +} + +/** + * TestValidate class + * + * @package Cake.Test.Case.Model + */ +class TestValidate extends CakeTestModel { + +/** + * useTable property + * + * @var bool false + */ + public $useTable = false; + +/** + * name property + * + * @var string 'TestValidate' + */ + public $name = 'TestValidate'; + +/** + * schema property + * + * @var array + */ + protected $_schema = array( + 'id' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => '8'), + 'title' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'), + 'body' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => ''), + 'number' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => '8'), + 'created' => array('type' => 'date', 'null' => '1', 'default' => '', 'length' => ''), + 'modified' => array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => null) + ); + +/** + * validateNumber method + * + * @param mixed $value + * @param mixed $options + * @return void + */ + public function validateNumber($value, $options) { + $options = array_merge(array('min' => 0, 'max' => 100), $options); + $valid = ($value['number'] >= $options['min'] && $value['number'] <= $options['max']); + return $valid; + } + +/** + * validateTitle method + * + * @param mixed $value + * @return void + */ + public function validateTitle($value) { + return (!empty($value) && strpos(strtolower($value['title']), 'title-') === 0); + } + +} + +/** + * User class + * + * @package Cake.Test.Case.Model + */ +class User extends CakeTestModel { + +/** + * name property + * + * @var string 'User' + */ + public $name = 'User'; + +/** + * validate property + * + * @var array + */ + public $validate = array('user' => 'notEmpty', 'password' => 'notEmpty'); + +/** + * beforeFind() callback used to run ContainableBehaviorTest::testLazyLoad() + * + * @return bool + * @throws Exception + */ + public function beforeFind($queryData) { + if (!empty($queryData['lazyLoad'])) { + if (!isset($this->Article, $this->Comment, $this->ArticleFeatured)) { + throw new Exception('Unavailable associations'); + } + } + return true; + } + +} + +/** + * Article class + * + * @package Cake.Test.Case.Model + */ +class Article extends CakeTestModel { + +/** + * name property + * + * @var string 'Article' + */ + public $name = 'Article'; + +/** + * belongsTo property + * + * @var array + */ + public $belongsTo = array('User'); + +/** + * hasMany property + * + * @var array + */ + public $hasMany = array('Comment' => array('dependent' => true)); + +/** + * hasAndBelongsToMany property + * + * @var array + */ + public $hasAndBelongsToMany = array('Tag'); + +/** + * validate property + * + * @var array + */ + public $validate = array( + 'user_id' => 'numeric', + 'title' => array('required' => false, 'rule' => 'notEmpty'), + 'body' => 'notEmpty', + ); + +/** + * beforeSaveReturn property + * + * @var bool true + */ + public $beforeSaveReturn = true; + +/** + * beforeSave method + * + * @return void + */ + public function beforeSave($options = array()) { + return $this->beforeSaveReturn; + } + +/** + * titleDuplicate method + * + * @param string $title + * @return void + */ + public static function titleDuplicate($title) { + if ($title === 'My Article Title') { + return false; + } + return true; + } + +} + +/** + * Model stub for beforeDelete testing + * + * @see #250 + * @package Cake.Test.Case.Model + */ +class BeforeDeleteComment extends CakeTestModel { + + public $name = 'BeforeDeleteComment'; + + public $useTable = 'comments'; + + public function beforeDelete($cascade = true) { + $db = $this->getDataSource(); + $db->delete($this, array($this->alias . '.' . $this->primaryKey => array(1, 3))); + return true; + } + +} + +/** + * NumericArticle class + * + * @package Cake.Test.Case.Model + */ +class NumericArticle extends CakeTestModel { + +/** + * name property + * + * @var string 'NumericArticle' + */ + public $name = 'NumericArticle'; + +/** + * useTable property + * + * @var string 'numeric_articles' + */ + public $useTable = 'numeric_articles'; + +} + +/** + * Article10 class + * + * @package Cake.Test.Case.Model + */ +class Article10 extends CakeTestModel { + +/** + * name property + * + * @var string 'Article10' + */ + public $name = 'Article10'; + +/** + * useTable property + * + * @var string 'articles' + */ + public $useTable = 'articles'; + +/** + * hasMany property + * + * @var array + */ + public $hasMany = array('Comment' => array('dependent' => true, 'exclusive' => true)); + +} + +/** + * ArticleFeatured class + * + * @package Cake.Test.Case.Model + */ +class ArticleFeatured extends CakeTestModel { + +/** + * name property + * + * @var string 'ArticleFeatured' + */ + public $name = 'ArticleFeatured'; + +/** + * belongsTo property + * + * @var array + */ + public $belongsTo = array('User', 'Category'); + +/** + * hasOne property + * + * @var array + */ + public $hasOne = array('Featured'); + +/** + * hasMany property + * + * @var array + */ + public $hasMany = array('Comment' => array('className' => 'Comment', 'dependent' => true)); + +/** + * hasAndBelongsToMany property + * + * @var array + */ + public $hasAndBelongsToMany = array('Tag'); + +/** + * validate property + * + * @var array + */ + public $validate = array('user_id' => 'numeric', 'title' => 'notEmpty', 'body' => 'notEmpty'); + +} + +/** + * Featured class + * + * @package Cake.Test.Case.Model + */ +class Featured extends CakeTestModel { + +/** + * name property + * + * @var string 'Featured' + */ + public $name = 'Featured'; + +/** + * belongsTo property + * + * @var array + */ + public $belongsTo = array('ArticleFeatured', 'Category'); +} + +/** + * Tag class + * + * @package Cake.Test.Case.Model + */ +class Tag extends CakeTestModel { + +/** + * name property + * + * @var string 'Tag' + */ + public $name = 'Tag'; +} + +/** + * ArticlesTag class + * + * @package Cake.Test.Case.Model + */ +class ArticlesTag extends CakeTestModel { + +/** + * name property + * + * @var string 'ArticlesTag' + */ + public $name = 'ArticlesTag'; +} + +/** + * ArticleFeaturedsTag class + * + * @package Cake.Test.Case.Model + */ +class ArticleFeaturedsTag extends CakeTestModel { + +/** + * name property + * + * @var string 'ArticleFeaturedsTag' + */ + public $name = 'ArticleFeaturedsTag'; +} + +/** + * Comment class + * + * @package Cake.Test.Case.Model + */ +class Comment extends CakeTestModel { + +/** + * name property + * + * @var string 'Comment' + */ + public $name = 'Comment'; + +/** + * belongsTo property + * + * @var array + */ + public $belongsTo = array('Article', 'User'); + +/** + * hasOne property + * + * @var array + */ + public $hasOne = array('Attachment' => array('dependent' => true)); +} + +/** + * Modified Comment Class has afterFind Callback + * + * @package Cake.Test.Case.Model + */ +class ModifiedComment extends CakeTestModel { + +/** + * name property + * + * @var string 'Comment' + */ + public $name = 'Comment'; + +/** + * useTable property + * + * @var string 'comments' + */ + public $useTable = 'comments'; + +/** + * belongsTo property + * + * @var array + */ + public $belongsTo = array('Article'); + +/** + * afterFind callback + * + * @return void + */ + public function afterFind($results, $primary = false) { + if (isset($results[0])) { + $results[0]['Comment']['callback'] = 'Fire'; + } + return $results; + } + +} + +/** + * Modified Comment Class has afterFind Callback + * + * @package Cake.Test.Case.Model + */ +class AgainModifiedComment extends CakeTestModel { + +/** + * name property + * + * @var string 'Comment' + */ + public $name = 'Comment'; + +/** + * useTable property + * + * @var string 'comments' + */ + public $useTable = 'comments'; + +/** + * belongsTo property + * + * @var array + */ + public $belongsTo = array('Article'); + +/** + * afterFind callback + * + * @return void + */ + public function afterFind($results, $primary = false) { + if (isset($results[0])) { + $results[0]['Comment']['querytype'] = $this->findQueryType; + } + return $results; + } + +} + +/** + * MergeVarPluginAppModel class + * + * @package Cake.Test.Case.Model + */ +class MergeVarPluginAppModel extends AppModel { + +/** + * actsAs parameter + * + * @var array + */ + public $actsAs = array( + 'Containable' + ); +} + +/** + * MergeVarPluginPost class + * + * @package Cake.Test.Case.Model + */ +class MergeVarPluginPost extends MergeVarPluginAppModel { + +/** + * actsAs parameter + * + * @var array + */ + public $actsAs = array( + 'Tree' + ); + +/** + * useTable parameter + * + * @var string + */ + public $useTable = 'posts'; +} + +/** + * MergeVarPluginComment class + * + * @package Cake.Test.Case.Model + */ +class MergeVarPluginComment extends MergeVarPluginAppModel { + +/** + * actsAs parameter + * + * @var array + */ + public $actsAs = array( + 'Containable' => array('some_settings') + ); + +/** + * useTable parameter + * + * @var string + */ + public $useTable = 'comments'; +} + +/** + * Attachment class + * + * @package Cake.Test.Case.Model + */ +class Attachment extends CakeTestModel { + +/** + * name property + * + * @var string 'Attachment' + */ + public $name = 'Attachment'; + +/** + * belongsTo property + * + * @var array + */ + public $belongsTo = array('Comment'); +} + +/** + * ModifiedAttachment class + * + * @package Cake.Test.Case.Model + */ +class ModifiedAttachment extends CakeTestModel { + +/** + * name property + * + * @var string 'ModifiedAttachment' + */ + public $name = 'ModifiedAttachment'; + +/** + * useTable property + * + * @var string 'attachments' + */ + public $useTable = 'attachments'; + +/** + * afterFind callback + * + * @return void + */ + public function afterFind($results, $primary = false) { + if (isset($results['id'])) { + $results['callback'] = 'Fired'; + } + return $results; + } + +} + +/** + * Category class + * + * @package Cake.Test.Case.Model + */ +class Category extends CakeTestModel { + +/** + * name property + * + * @var string 'Category' + */ + public $name = 'Category'; +} + +/** + * CategoryThread class + * + * @package Cake.Test.Case.Model + */ +class CategoryThread extends CakeTestModel { + +/** + * name property + * + * @var string 'CategoryThread' + */ + public $name = 'CategoryThread'; + +/** + * belongsTo property + * + * @var array + */ + public $belongsTo = array('ParentCategory' => array('className' => 'CategoryThread', 'foreignKey' => 'parent_id')); +} + +/** + * Apple class + * + * @package Cake.Test.Case.Model + */ +class Apple extends CakeTestModel { + +/** + * name property + * + * @var string 'Apple' + */ + public $name = 'Apple'; + +/** + * validate property + * + * @var array + */ + public $validate = array('name' => 'notEmpty'); + +/** + * hasOne property + * + * @var array + */ + public $hasOne = array('Sample'); + +/** + * hasMany property + * + * @var array + */ + public $hasMany = array('Child' => array('className' => 'Apple', 'dependent' => true)); + +/** + * belongsTo property + * + * @var array + */ + public $belongsTo = array('Parent' => array('className' => 'Apple', 'foreignKey' => 'apple_id')); +} + +/** + * Sample class + * + * @package Cake.Test.Case.Model + */ +class Sample extends CakeTestModel { + +/** + * name property + * + * @var string 'Sample' + */ + public $name = 'Sample'; + +/** + * belongsTo property + * + * @var string 'Apple' + */ + public $belongsTo = 'Apple'; +} + +/** + * AnotherArticle class + * + * @package Cake.Test.Case.Model + */ +class AnotherArticle extends CakeTestModel { + +/** + * name property + * + * @var string 'AnotherArticle' + */ + public $name = 'AnotherArticle'; + +/** + * hasMany property + * + * @var string 'Home' + */ + public $hasMany = 'Home'; +} + +/** + * Advertisement class + * + * @package Cake.Test.Case.Model + */ +class Advertisement extends CakeTestModel { + +/** + * name property + * + * @var string 'Advertisement' + */ + public $name = 'Advertisement'; + +/** + * hasMany property + * + * @var string 'Home' + */ + public $hasMany = 'Home'; +} + +/** + * Home class + * + * @package Cake.Test.Case.Model + */ +class Home extends CakeTestModel { + +/** + * name property + * + * @var string 'Home' + */ + public $name = 'Home'; + +/** + * belongsTo property + * + * @var array + */ + public $belongsTo = array('AnotherArticle', 'Advertisement'); +} + +/** + * Post class + * + * @package Cake.Test.Case.Model + */ +class Post extends CakeTestModel { + +/** + * name property + * + * @var string 'Post' + */ + public $name = 'Post'; + +/** + * belongsTo property + * + * @var array + */ + public $belongsTo = array('Author'); + + public function beforeFind($queryData) { + if (isset($queryData['connection'])) { + $this->useDbConfig = $queryData['connection']; + } + return true; + } + + public function afterFind($results, $primary = false) { + $this->useDbConfig = 'test'; + return $results; + } + +} + +/** + * Author class + * + * @package Cake.Test.Case.Model + */ +class Author extends CakeTestModel { + +/** + * name property + * + * @var string 'Author' + */ + public $name = 'Author'; + +/** + * hasMany property + * + * @var array + */ + public $hasMany = array('Post'); + +/** + * afterFind method + * + * @param array $results + * @return void + */ + public function afterFind($results, $primary = false) { + $results[0]['Author']['test'] = 'working'; + return $results; + } + +} + +/** + * ModifiedAuthor class + * + * @package Cake.Test.Case.Model + */ +class ModifiedAuthor extends Author { + +/** + * name property + * + * @var string 'Author' + */ + public $name = 'Author'; + +/** + * afterFind method + * + * @param array $results + * @return void + */ + public function afterFind($results, $primary = false) { + foreach ($results as $index => $result) { + $results[$index]['Author']['user'] .= ' (CakePHP)'; + } + return $results; + } + +} + +/** + * Project class + * + * @package Cake.Test.Case.Model + */ +class Project extends CakeTestModel { + +/** + * name property + * + * @var string 'Project' + */ + public $name = 'Project'; + +/** + * hasMany property + * + * @var array + */ + public $hasMany = array('Thread'); +} + +/** + * Thread class + * + * @package Cake.Test.Case.Model + */ +class Thread extends CakeTestModel { + +/** + * name property + * + * @var string 'Thread' + */ + public $name = 'Thread'; + +/** + * hasMany property + * + * @var array + */ + public $belongsTo = array('Project'); + +/** + * hasMany property + * + * @var array + */ + public $hasMany = array('Message'); +} + +/** + * Message class + * + * @package Cake.Test.Case.Model + */ +class Message extends CakeTestModel { + +/** + * name property + * + * @var string 'Message' + */ + public $name = 'Message'; + +/** + * hasOne property + * + * @var array + */ + public $hasOne = array('Bid'); +} + +/** + * Bid class + * + * @package Cake.Test.Case.Model + */ +class Bid extends CakeTestModel { + +/** + * name property + * + * @var string 'Bid' + */ + public $name = 'Bid'; + +/** + * belongsTo property + * + * @var array + */ + public $belongsTo = array('Message'); +} + +/** + * BiddingMessage class + * + * @package Cake.Test.Case.Model + */ +class BiddingMessage extends CakeTestModel { + +/** + * name property + * + * @var string 'BiddingMessage' + */ + public $name = 'BiddingMessage'; + +/** + * primaryKey property + * + * @var string 'bidding' + */ + public $primaryKey = 'bidding'; + +/** + * belongsTo property + * + * @var array + */ + public $belongsTo = array( + 'Bidding' => array( + 'foreignKey' => false, + 'conditions' => array('BiddingMessage.bidding = Bidding.bid') + ) + ); +} + +/** + * Bidding class + * + * @package Cake.Test.Case.Model + */ +class Bidding extends CakeTestModel { + +/** + * name property + * + * @var string 'Bidding' + */ + public $name = 'Bidding'; + +/** + * hasOne property + * + * @var array + */ + public $hasOne = array( + 'BiddingMessage' => array( + 'foreignKey' => false, + 'conditions' => array('BiddingMessage.bidding = Bidding.bid'), + 'dependent' => true + ) + ); +} + +/** + * NodeAfterFind class + * + * @package Cake.Test.Case.Model + */ +class NodeAfterFind extends CakeTestModel { + +/** + * name property + * + * @var string 'NodeAfterFind' + */ + public $name = 'NodeAfterFind'; + +/** + * validate property + * + * @var array + */ + public $validate = array('name' => 'notEmpty'); + +/** + * useTable property + * + * @var string 'apples' + */ + public $useTable = 'apples'; + +/** + * hasOne property + * + * @var array + */ + public $hasOne = array('Sample' => array('className' => 'NodeAfterFindSample')); + +/** + * hasMany property + * + * @var array + */ + public $hasMany = array('Child' => array('className' => 'NodeAfterFind', 'dependent' => true)); + +/** + * belongsTo property + * + * @var array + */ + public $belongsTo = array('Parent' => array('className' => 'NodeAfterFind', 'foreignKey' => 'apple_id')); + +/** + * afterFind method + * + * @param mixed $results + * @return array + */ + public function afterFind($results, $primary = false) { + return $results; + } + +} + +/** + * NodeAfterFindSample class + * + * @package Cake.Test.Case.Model + */ +class NodeAfterFindSample extends CakeTestModel { + +/** + * name property + * + * @var string 'NodeAfterFindSample' + */ + public $name = 'NodeAfterFindSample'; + +/** + * useTable property + * + * @var string 'samples' + */ + public $useTable = 'samples'; + +/** + * belongsTo property + * + * @var string 'NodeAfterFind' + */ + public $belongsTo = 'NodeAfterFind'; +} + +/** + * NodeNoAfterFind class + * + * @package Cake.Test.Case.Model + */ +class NodeNoAfterFind extends CakeTestModel { + +/** + * name property + * + * @var string 'NodeAfterFind' + */ + public $name = 'NodeAfterFind'; + +/** + * validate property + * + * @var array + */ + public $validate = array('name' => 'notEmpty'); + +/** + * useTable property + * + * @var string 'apples' + */ + public $useTable = 'apples'; + +/** + * hasOne property + * + * @var array + */ + public $hasOne = array('Sample' => array('className' => 'NodeAfterFindSample')); + +/** + * hasMany property + * + * @var array + */ + public $hasMany = array('Child' => array('className' => 'NodeAfterFind', 'dependent' => true)); + +/** + * belongsTo property + * + * @var array + */ + public $belongsTo = array('Parent' => array('className' => 'NodeAfterFind', 'foreignKey' => 'apple_id')); +} + +/** + * Node class + * + * @package Cake.Test.Case.Model + */ +class Node extends CakeTestModel{ + +/** + * name property + * + * @var string 'Node' + */ + public $name = 'Node'; + +/** + * hasAndBelongsToMany property + * + * @var array + */ + public $hasAndBelongsToMany = array( + 'ParentNode' => array( + 'className' => 'Node', + 'joinTable' => 'dependency', + 'with' => 'Dependency', + 'foreignKey' => 'child_id', + 'associationForeignKey' => 'parent_id', + ) + ); +} + +/** + * Dependency class + * + * @package Cake.Test.Case.Model + */ +class Dependency extends CakeTestModel { + +/** + * name property + * + * @var string 'Dependency' + */ + public $name = 'Dependency'; +} + +/** + * ModelA class + * + * @package Cake.Test.Case.Model + */ +class ModelA extends CakeTestModel { + +/** + * name property + * + * @var string 'ModelA' + */ + public $name = 'ModelA'; + +/** + * useTable property + * + * @var string 'apples' + */ + public $useTable = 'apples'; + +/** + * hasMany property + * + * @var array + */ + public $hasMany = array('ModelB', 'ModelC'); +} + +/** + * ModelB class + * + * @package Cake.Test.Case.Model + */ +class ModelB extends CakeTestModel { + +/** + * name property + * + * @var string 'ModelB' + */ + public $name = 'ModelB'; + +/** + * useTable property + * + * @var string 'messages' + */ + public $useTable = 'messages'; + +/** + * hasMany property + * + * @var array + */ + public $hasMany = array('ModelD'); +} + +/** + * ModelC class + * + * @package Cake.Test.Case.Model + */ +class ModelC extends CakeTestModel { + +/** + * name property + * + * @var string 'ModelC' + */ + public $name = 'ModelC'; + +/** + * useTable property + * + * @var string 'bids' + */ + public $useTable = 'bids'; + +/** + * hasMany property + * + * @var array + */ + public $hasMany = array('ModelD'); +} + +/** + * ModelD class + * + * @package Cake.Test.Case.Model + */ +class ModelD extends CakeTestModel { + +/** + * name property + * + * @var string 'ModelD' + */ + public $name = 'ModelD'; + +/** + * useTable property + * + * @var string 'threads' + */ + public $useTable = 'threads'; +} + +/** + * Something class + * + * @package Cake.Test.Case.Model + */ +class Something extends CakeTestModel { + +/** + * name property + * + * @var string 'Something' + */ + public $name = 'Something'; + +/** + * hasAndBelongsToMany property + * + * @var array + */ + public $hasAndBelongsToMany = array('SomethingElse' => array('with' => array('JoinThing' => array('doomed')))); +} + +/** + * SomethingElse class + * + * @package Cake.Test.Case.Model + */ +class SomethingElse extends CakeTestModel { + +/** + * name property + * + * @var string 'SomethingElse' + */ + public $name = 'SomethingElse'; + +/** + * hasAndBelongsToMany property + * + * @var array + */ + public $hasAndBelongsToMany = array('Something' => array('with' => 'JoinThing')); +} + +/** + * JoinThing class + * + * @package Cake.Test.Case.Model + */ +class JoinThing extends CakeTestModel { + +/** + * name property + * + * @var string 'JoinThing' + */ + public $name = 'JoinThing'; + +/** + * belongsTo property + * + * @var array + */ + public $belongsTo = array('Something', 'SomethingElse'); +} + +/** + * Portfolio class + * + * @package Cake.Test.Case.Model + */ +class Portfolio extends CakeTestModel { + +/** + * name property + * + * @var string 'Portfolio' + */ + public $name = 'Portfolio'; + +/** + * hasAndBelongsToMany property + * + * @var array + */ + public $hasAndBelongsToMany = array('Item'); +} + +/** + * Item class + * + * @package Cake.Test.Case.Model + */ +class Item extends CakeTestModel { + +/** + * name property + * + * @var string 'Item' + */ + public $name = 'Item'; + +/** + * belongsTo property + * + * @var array + */ + public $belongsTo = array('Syfile' => array('counterCache' => true)); + +/** + * hasAndBelongsToMany property + * + * @var array + */ + public $hasAndBelongsToMany = array('Portfolio' => array('unique' => false)); +} + +/** + * ItemsPortfolio class + * + * @package Cake.Test.Case.Model + */ +class ItemsPortfolio extends CakeTestModel { + +/** + * name property + * + * @var string 'ItemsPortfolio' + */ + public $name = 'ItemsPortfolio'; +} + +/** + * Syfile class + * + * @package Cake.Test.Case.Model + */ +class Syfile extends CakeTestModel { + +/** + * name property + * + * @var string 'Syfile' + */ + public $name = 'Syfile'; + +/** + * belongsTo property + * + * @var array + */ + public $belongsTo = array('Image'); +} + +/** + * Image class + * + * @package Cake.Test.Case.Model + */ +class Image extends CakeTestModel { + +/** + * name property + * + * @var string 'Image' + */ + public $name = 'Image'; +} + +/** + * DeviceType class + * + * @package Cake.Test.Case.Model + */ +class DeviceType extends CakeTestModel { + +/** + * name property + * + * @var string 'DeviceType' + */ + public $name = 'DeviceType'; + +/** + * order property + * + * @var array + */ + public $order = array('DeviceType.order' => 'ASC'); + +/** + * belongsTo property + * + * @var array + */ + public $belongsTo = array( + 'DeviceTypeCategory', 'FeatureSet', 'ExteriorTypeCategory', + 'Image' => array('className' => 'Document'), + 'Extra1' => array('className' => 'Document'), + 'Extra2' => array('className' => 'Document')); + +/** + * hasMany property + * + * @var array + */ + public $hasMany = array('Device' => array('order' => array('Device.id' => 'ASC'))); +} + +/** + * DeviceTypeCategory class + * + * @package Cake.Test.Case.Model + */ +class DeviceTypeCategory extends CakeTestModel { + +/** + * name property + * + * @var string 'DeviceTypeCategory' + */ + public $name = 'DeviceTypeCategory'; +} + +/** + * FeatureSet class + * + * @package Cake.Test.Case.Model + */ +class FeatureSet extends CakeTestModel { + +/** + * name property + * + * @var string 'FeatureSet' + */ + public $name = 'FeatureSet'; +} + +/** + * ExteriorTypeCategory class + * + * @package Cake.Test.Case.Model + */ +class ExteriorTypeCategory extends CakeTestModel { + +/** + * name property + * + * @var string 'ExteriorTypeCategory' + */ + public $name = 'ExteriorTypeCategory'; + +/** + * belongsTo property + * + * @var array + */ + public $belongsTo = array('Image' => array('className' => 'Device')); +} + +/** + * Document class + * + * @package Cake.Test.Case.Model + */ +class Document extends CakeTestModel { + +/** + * name property + * + * @var string 'Document' + */ + public $name = 'Document'; + +/** + * belongsTo property + * + * @var array + */ + public $belongsTo = array('DocumentDirectory'); +} + +/** + * Device class + * + * @package Cake.Test.Case.Model + */ +class Device extends CakeTestModel { + +/** + * name property + * + * @var string 'Device' + */ + public $name = 'Device'; +} + +/** + * DocumentDirectory class + * + * @package Cake.Test.Case.Model + */ +class DocumentDirectory extends CakeTestModel { + +/** + * name property + * + * @var string 'DocumentDirectory' + */ + public $name = 'DocumentDirectory'; +} + +/** + * PrimaryModel class + * + * @package Cake.Test.Case.Model + */ +class PrimaryModel extends CakeTestModel { + +/** + * name property + * + * @var string 'PrimaryModel' + */ + public $name = 'PrimaryModel'; +} + +/** + * SecondaryModel class + * + * @package Cake.Test.Case.Model + */ +class SecondaryModel extends CakeTestModel { + +/** + * name property + * + * @var string 'SecondaryModel' + */ + public $name = 'SecondaryModel'; +} + +/** + * JoinA class + * + * @package Cake.Test.Case.Model + */ +class JoinA extends CakeTestModel { + +/** + * name property + * + * @var string 'JoinA' + */ + public $name = 'JoinA'; + +/** + * hasAndBelongsToMany property + * + * @var array + */ + public $hasAndBelongsToMany = array('JoinB', 'JoinC'); +} + +/** + * JoinB class + * + * @package Cake.Test.Case.Model + */ +class JoinB extends CakeTestModel { + +/** + * name property + * + * @var string 'JoinB' + */ + public $name = 'JoinB'; + +/** + * hasAndBelongsToMany property + * + * @var array + */ + public $hasAndBelongsToMany = array('JoinA'); +} + +/** + * JoinC class + * + * @package Cake.Test.Case.Model + */ +class JoinC extends CakeTestModel { + +/** + * name property + * + * @var string 'JoinC' + */ + public $name = 'JoinC'; + +/** + * hasAndBelongsToMany property + * + * @var array + */ + public $hasAndBelongsToMany = array('JoinA'); +} + +/** + * ThePaper class + * + * @package Cake.Test.Case.Model + */ +class ThePaper extends CakeTestModel { + +/** + * name property + * + * @var string 'ThePaper' + */ + public $name = 'ThePaper'; + +/** + * useTable property + * + * @var string 'apples' + */ + public $useTable = 'apples'; + +/** + * hasOne property + * + * @var array + */ + public $hasOne = array('Itself' => array('className' => 'ThePaper', 'foreignKey' => 'apple_id')); + +/** + * hasAndBelongsToMany property + * + * @var array + */ + public $hasAndBelongsToMany = array('Monkey' => array('joinTable' => 'the_paper_monkies', 'order' => 'id')); +} + +/** + * Monkey class + * + * @package Cake.Test.Case.Model + */ +class Monkey extends CakeTestModel { + +/** + * name property + * + * @var string 'Monkey' + */ + public $name = 'Monkey'; + +/** + * useTable property + * + * @var string 'devices' + */ + public $useTable = 'devices'; +} + +/** + * AssociationTest1 class + * + * @package Cake.Test.Case.Model + */ +class AssociationTest1 extends CakeTestModel { + +/** + * useTable property + * + * @var string 'join_as' + */ + public $useTable = 'join_as'; + +/** + * name property + * + * @var string 'AssociationTest1' + */ + public $name = 'AssociationTest1'; + +/** + * hasAndBelongsToMany property + * + * @var array + */ + public $hasAndBelongsToMany = array('AssociationTest2' => array( + 'unique' => false, 'joinTable' => 'join_as_join_bs', 'foreignKey' => false + )); +} + +/** + * AssociationTest2 class + * + * @package Cake.Test.Case.Model + */ +class AssociationTest2 extends CakeTestModel { + +/** + * useTable property + * + * @var string 'join_bs' + */ + public $useTable = 'join_bs'; + +/** + * name property + * + * @var string 'AssociationTest2' + */ + public $name = 'AssociationTest2'; + +/** + * hasAndBelongsToMany property + * + * @var array + */ + public $hasAndBelongsToMany = array('AssociationTest1' => array( + 'unique' => false, 'joinTable' => 'join_as_join_bs' + )); +} + +/** + * Callback class + * + * @package Cake.Test.Case.Model + */ +class Callback extends CakeTestModel { + +} + +/** + * CallbackPostTestModel class + * + * @package Cake.Test.Case.Model + */ +class CallbackPostTestModel extends CakeTestModel { + + public $useTable = 'posts'; + +/** + * variable to control return of beforeValidate + * + * @var string + */ + public $beforeValidateReturn = true; + +/** + * variable to control return of beforeSave + * + * @var string + */ + public $beforeSaveReturn = true; + +/** + * variable to control return of beforeDelete + * + * @var string + */ + public $beforeDeleteReturn = true; + +/** + * beforeSave callback + * + * @return void + */ + public function beforeSave($options = array()) { + return $this->beforeSaveReturn; + } + +/** + * beforeValidate callback + * + * @return void + */ + public function beforeValidate($options = array()) { + return $this->beforeValidateReturn; + } + +/** + * beforeDelete callback + * + * @return void + */ + public function beforeDelete($cascade = true) { + return $this->beforeDeleteReturn; + } + +} + +/** + * Uuid class + * + * @package Cake.Test.Case.Model + */ +class Uuid extends CakeTestModel { + +/** + * name property + * + * @var string 'Uuid' + */ + public $name = 'Uuid'; +} + +/** + * DataTest class + * + * @package Cake.Test.Case.Model + */ +class DataTest extends CakeTestModel { + +/** + * name property + * + * @var string 'DataTest' + */ + public $name = 'DataTest'; +} + +/** + * TheVoid class + * + * @package Cake.Test.Case.Model + */ +class TheVoid extends CakeTestModel { + +/** + * name property + * + * @var string 'TheVoid' + */ + public $name = 'TheVoid'; + +/** + * useTable property + * + * @var bool false + */ + public $useTable = false; +} + +/** + * ValidationTest1 class + * + * @package Cake.Test.Case.Model + */ +class ValidationTest1 extends CakeTestModel { + +/** + * name property + * + * @var string 'ValidationTest' + */ + public $name = 'ValidationTest1'; + +/** + * useTable property + * + * @var bool false + */ + public $useTable = false; + +/** + * schema property + * + * @var array + */ + protected $_schema = array(); + +/** + * validate property + * + * @var array + */ + public $validate = array( + 'title' => 'notEmpty', + 'published' => 'customValidationMethod', + 'body' => array( + 'notEmpty', + '/^.{5,}$/s' => 'no matchy', + '/^[0-9A-Za-z \\.]{1,}$/s' + ) + ); + +/** + * customValidationMethod method + * + * @param mixed $data + * @return void + */ + public function customValidationMethod($data) { + return $data === 1; + } + +/** + * Custom validator with parameters + default values + * + * @return array + */ + public function customValidatorWithParams($data, $validator, $or = true, $ignoreOnSame = 'id') { + $this->validatorParams = get_defined_vars(); + unset($this->validatorParams['this']); + return true; + } + +/** + * Custom validator with message + * + * @return array + */ + public function customValidatorWithMessage($data) { + return 'This field will *never* validate! Muhahaha!'; + } + +/** + * Test validation with many parameters + * + * @return void + */ + public function customValidatorWithSixParams($data, $one = 1, $two = 2, $three = 3, $four = 4, $five = 5, $six = 6) { + $this->validatorParams = get_defined_vars(); + unset($this->validatorParams['this']); + return true; + } + +} + +/** + * ValidationTest2 class + * + * @package Cake.Test.Case.Model + */ +class ValidationTest2 extends CakeTestModel { + +/** + * name property + * + * @var string 'ValidationTest2' + */ + public $name = 'ValidationTest2'; + +/** + * useTable property + * + * @var bool false + */ + public $useTable = false; + +/** + * validate property + * + * @var array + */ + public $validate = array( + 'title' => 'notEmpty', + 'published' => 'customValidationMethod', + 'body' => array( + 'notEmpty', + '/^.{5,}$/s' => 'no matchy', + '/^[0-9A-Za-z \\.]{1,}$/s' + ) + ); + +/** + * customValidationMethod method + * + * @param mixed $data + * @return void + */ + public function customValidationMethod($data) { + return $data === 1; + } + +/** + * schema method + * + * @return void + */ + public function schema($field = false) { + return array(); + } + +} + +/** + * Person class + * + * @package Cake.Test.Case.Model + */ +class Person extends CakeTestModel { + +/** + * name property + * + * @var string 'Person' + */ + public $name = 'Person'; + +/** + * belongsTo property + * + * @var array + */ + public $belongsTo = array( + 'Mother' => array( + 'className' => 'Person', + 'foreignKey' => 'mother_id' + ), + 'Father' => array( + 'className' => 'Person', + 'foreignKey' => 'father_id' + ) + ); +} + +/** + * UnderscoreField class + * + * @package Cake.Test.Case.Model + */ +class UnderscoreField extends CakeTestModel { + +/** + * name property + * + * @var string 'UnderscoreField' + */ + public $name = 'UnderscoreField'; +} + +/** + * Product class + * + * @package Cake.Test.Case.Model + */ +class Product extends CakeTestModel { + +/** + * name property + * + * @var string 'Product' + */ + public $name = 'Product'; +} + +/** + * Story class + * + * @package Cake.Test.Case.Model + */ +class Story extends CakeTestModel { + +/** + * name property + * + * @var string 'Story' + */ + public $name = 'Story'; + +/** + * primaryKey property + * + * @var string 'story' + */ + public $primaryKey = 'story'; + +/** + * hasAndBelongsToMany property + * + * @var array + */ + public $hasAndBelongsToMany = array('Tag' => array('foreignKey' => 'story')); + +/** + * validate property + * + * @var array + */ + public $validate = array('title' => 'notEmpty'); +} + +/** + * Cd class + * + * @package Cake.Test.Case.Model + */ +class Cd extends CakeTestModel { + +/** + * name property + * + * @var string 'Cd' + */ + public $name = 'Cd'; + +/** + * hasOne property + * + * @var array + */ + public $hasOne = array( + 'OverallFavorite' => array( + 'foreignKey' => 'model_id', + 'dependent' => true, + 'conditions' => array('model_type' => 'Cd') + ) + ); + +} + +/** + * Book class + * + * @package Cake.Test.Case.Model + */ +class Book extends CakeTestModel { + +/** + * name property + * + * @var string 'Book' + */ + public $name = 'Book'; + +/** + * hasOne property + * + * @var array + */ + public $hasOne = array( + 'OverallFavorite' => array( + 'foreignKey' => 'model_id', + 'dependent' => true, + 'conditions' => 'OverallFavorite.model_type = \'Book\'' + ) + ); + +} + +/** + * OverallFavorite class + * + * @package Cake.Test.Case.Model + */ +class OverallFavorite extends CakeTestModel { + +/** + * name property + * + * @var string 'OverallFavorite' + */ + public $name = 'OverallFavorite'; +} + +/** + * MyUser class + * + * @package Cake.Test.Case.Model + */ +class MyUser extends CakeTestModel { + +/** + * name property + * + * @var string 'MyUser' + */ + public $name = 'MyUser'; + +/** + * undocumented variable + * + * @var string + */ + public $hasAndBelongsToMany = array('MyCategory'); +} + +/** + * MyCategory class + * + * @package Cake.Test.Case.Model + */ +class MyCategory extends CakeTestModel { + +/** + * name property + * + * @var string 'MyCategory' + */ + public $name = 'MyCategory'; + +/** + * undocumented variable + * + * @var string + */ + public $hasAndBelongsToMany = array('MyProduct', 'MyUser'); +} + +/** + * MyProduct class + * + * @package Cake.Test.Case.Model + */ +class MyProduct extends CakeTestModel { + +/** + * name property + * + * @var string 'MyProduct' + */ + public $name = 'MyProduct'; + +/** + * undocumented variable + * + * @var string + */ + public $hasAndBelongsToMany = array('MyCategory'); +} + +/** + * MyCategoriesMyUser class + * + * @package Cake.Test.Case.Model + */ +class MyCategoriesMyUser extends CakeTestModel { + +/** + * name property + * + * @var string 'MyCategoriesMyUser' + */ + public $name = 'MyCategoriesMyUser'; +} + +/** + * MyCategoriesMyProduct class + * + * @package Cake.Test.Case.Model + */ +class MyCategoriesMyProduct extends CakeTestModel { + +/** + * name property + * + * @var string 'MyCategoriesMyProduct' + */ + public $name = 'MyCategoriesMyProduct'; +} + + +/** + * NumberTree class + * + * @package Cake.Test.Case.Model + */ +class NumberTree extends CakeTestModel { + +/** + * name property + * + * @var string 'NumberTree' + */ + public $name = 'NumberTree'; + +/** + * actsAs property + * + * @var array + */ + public $actsAs = array('Tree'); + +/** + * initialize method + * + * @param integer $levelLimit + * @param integer $childLimit + * @param mixed $currentLevel + * @param mixed $parent_id + * @param string $prefix + * @param bool $hierarchal + * @return void + */ + public function initialize($levelLimit = 3, $childLimit = 3, $currentLevel = null, $parentId = null, $prefix = '1', $hierarchal = true) { + if (!$parentId) { + $db = ConnectionManager::getDataSource($this->useDbConfig); + $db->truncate($this->table); + $this->save(array($this->name => array('name' => '1. Root'))); + $this->initialize($levelLimit, $childLimit, 1, $this->id, '1', $hierarchal); + $this->create(array()); + } + + if (!$currentLevel || $currentLevel > $levelLimit) { + return; + } + + for ($i = 1; $i <= $childLimit; $i++) { + $name = $prefix . '.' . $i; + $data = array($this->name => array('name' => $name)); + $this->create($data); + + if ($hierarchal) { + if ($this->name == 'UnconventionalTree') { + $data[$this->name]['join'] = $parentId; + } else { + $data[$this->name]['parent_id'] = $parentId; + } + } + $this->save($data); + $this->initialize($levelLimit, $childLimit, $currentLevel + 1, $this->id, $name, $hierarchal); + } + } + +} + +/** + * NumberTreeTwo class + * + * @package Cake.Test.Case.Model + */ +class NumberTreeTwo extends NumberTree { + +/** + * name property + * + * @var string 'NumberTree' + */ + public $name = 'NumberTreeTwo'; + +/** + * actsAs property + * + * @var array + */ + public $actsAs = array(); +} + +/** + * FlagTree class + * + * @package Cake.Test.Case.Model + */ +class FlagTree extends NumberTree { + +/** + * name property + * + * @var string 'FlagTree' + */ + public $name = 'FlagTree'; +} + +/** + * UnconventionalTree class + * + * @package Cake.Test.Case.Model + */ +class UnconventionalTree extends NumberTree { + +/** + * name property + * + * @var string 'FlagTree' + */ + public $name = 'UnconventionalTree'; + + public $actsAs = array( + 'Tree' => array( + 'parent' => 'join', + 'left' => 'left', + 'right' => 'right' + ) + ); + +} + +/** + * UuidTree class + * + * @package Cake.Test.Case.Model + */ +class UuidTree extends NumberTree { + +/** + * name property + * + * @var string 'FlagTree' + */ + public $name = 'UuidTree'; +} + +/** + * Campaign class + * + * @package Cake.Test.Case.Model + */ +class Campaign extends CakeTestModel { + +/** + * name property + * + * @var string 'Campaign' + */ + public $name = 'Campaign'; + +/** + * hasMany property + * + * @var array + */ + public $hasMany = array('Ad' => array('fields' => array('id', 'campaign_id', 'name'))); +} + +/** + * Ad class + * + * @package Cake.Test.Case.Model + */ +class Ad extends CakeTestModel { + +/** + * name property + * + * @var string 'Ad' + */ + public $name = 'Ad'; + +/** + * actsAs property + * + * @var array + */ + public $actsAs = array('Tree'); + +/** + * belongsTo property + * + * @var array + */ + public $belongsTo = array('Campaign'); +} + +/** + * AfterTree class + * + * @package Cake.Test.Case.Model + */ +class AfterTree extends NumberTree { + +/** + * name property + * + * @var string 'AfterTree' + */ + public $name = 'AfterTree'; + +/** + * actsAs property + * + * @var array + */ + public $actsAs = array('Tree'); + + public function afterSave($created) { + if ($created && isset($this->data['AfterTree'])) { + $this->data['AfterTree']['name'] = 'Six and One Half Changed in AfterTree::afterSave() but not in database'; + } + } + +} + +/** + * Nonconformant Content class + * + * @package Cake.Test.Case.Model + */ +class Content extends CakeTestModel { + +/** + * name property + * + * @var string 'Content' + */ + public $name = 'Content'; + +/** + * useTable property + * + * @var string 'Content' + */ + public $useTable = 'Content'; + +/** + * primaryKey property + * + * @var string 'iContentId' + */ + public $primaryKey = 'iContentId'; + +/** + * hasAndBelongsToMany property + * + * @var array + */ + public $hasAndBelongsToMany = array('Account' => array('className' => 'Account', 'with' => 'ContentAccount', 'joinTable' => 'ContentAccounts', 'foreignKey' => 'iContentId', 'associationForeignKey', 'iAccountId')); +} + +/** + * Nonconformant Account class + * + * @package Cake.Test.Case.Model + */ +class Account extends CakeTestModel { + +/** + * name property + * + * @var string 'Account' + */ + public $name = 'Account'; + +/** + * useTable property + * + * @var string 'Account' + */ + public $useTable = 'Accounts'; + +/** + * primaryKey property + * + * @var string 'iAccountId' + */ + public $primaryKey = 'iAccountId'; +} + +/** + * Nonconformant ContentAccount class + * + * @package Cake.Test.Case.Model + */ +class ContentAccount extends CakeTestModel { + +/** + * name property + * + * @var string 'Account' + */ + public $name = 'ContentAccount'; + +/** + * useTable property + * + * @var string 'Account' + */ + public $useTable = 'ContentAccounts'; + +/** + * primaryKey property + * + * @var string 'iAccountId' + */ + public $primaryKey = 'iContentAccountsId'; +} + +/** + * FilmFile class + * + * @package Cake.Test.Case.Model + */ +class FilmFile extends CakeTestModel { + + public $name = 'FilmFile'; + +} + +/** + * Basket test model + * + * @package Cake.Test.Case.Model + */ +class Basket extends CakeTestModel { + + public $name = 'Basket'; + + public $belongsTo = array( + 'FilmFile' => array( + 'className' => 'FilmFile', + 'foreignKey' => 'object_id', + 'conditions' => "Basket.type = 'file'", + 'fields' => '', + 'order' => '' + ) + ); + +} + +/** + * TestPluginArticle class + * + * @package Cake.Test.Case.Model + */ +class TestPluginArticle extends CakeTestModel { + +/** + * name property + * + * @var string 'TestPluginArticle' + */ + public $name = 'TestPluginArticle'; + +/** + * belongsTo property + * + * @var array + */ + public $belongsTo = array('User'); + +/** + * hasMany property + * + * @var array + */ + public $hasMany = array( + 'TestPluginComment' => array( + 'className' => 'TestPlugin.TestPluginComment', + 'foreignKey' => 'article_id', + 'dependent' => true + ) + ); +} + +/** + * TestPluginComment class + * + * @package Cake.Test.Case.Model + */ +class TestPluginComment extends CakeTestModel { + +/** + * name property + * + * @var string 'TestPluginComment' + */ + public $name = 'TestPluginComment'; + +/** + * belongsTo property + * + * @var array + */ + public $belongsTo = array( + 'TestPluginArticle' => array( + 'className' => 'TestPlugin.TestPluginArticle', + 'foreignKey' => 'article_id', + ), + 'TestPlugin.User' + ); +} + +/** + * Uuidportfolio class + * + * @package Cake.Test.Case.Model + */ +class Uuidportfolio extends CakeTestModel { + +/** + * name property + * + * @var string 'Uuidportfolio' + */ + public $name = 'Uuidportfolio'; + +/** + * hasAndBelongsToMany property + * + * @var array + */ + public $hasAndBelongsToMany = array('Uuiditem'); +} + +/** + * Uuiditem class + * + * @package Cake.Test.Case.Model + */ +class Uuiditem extends CakeTestModel { + +/** + * name property + * + * @var string 'Item' + */ + public $name = 'Uuiditem'; + +/** + * hasAndBelongsToMany property + * + * @var array + */ + public $hasAndBelongsToMany = array('Uuidportfolio' => array('with' => 'UuiditemsUuidportfolioNumericid')); + +} + +/** + * UuiditemsPortfolio class + * + * @package Cake.Test.Case.Model + */ +class UuiditemsUuidportfolio extends CakeTestModel { + +/** + * name property + * + * @var string 'ItemsPortfolio' + */ + public $name = 'UuiditemsUuidportfolio'; +} + +/** + * UuiditemsPortfolioNumericid class + * + * @package Cake.Test.Case.Model + */ +class UuiditemsUuidportfolioNumericid extends CakeTestModel { + +/** + * name property + * + * @var string + */ + public $name = 'UuiditemsUuidportfolioNumericid'; +} + +/** + * TranslateTestModel class. + * + * @package Cake.Test.Case.Model + */ +class TranslateTestModel extends CakeTestModel { + +/** + * name property + * + * @var string 'TranslateTestModel' + */ + public $name = 'TranslateTestModel'; + +/** + * useTable property + * + * @var string 'i18n' + */ + public $useTable = 'i18n'; + +/** + * displayField property + * + * @var string 'field' + */ + public $displayField = 'field'; +} + +/** + * TranslateTestModel class. + * + * @package Cake.Test.Case.Model + */ +class TranslateWithPrefix extends CakeTestModel { + +/** + * name property + * + * @var string 'TranslateTestModel' + */ + public $name = 'TranslateWithPrefix'; + +/** + * tablePrefix property + * + * @var string 'i18n' + */ + public $tablePrefix = 'i18n_'; + +/** + * displayField property + * + * @var string 'field' + */ + public $displayField = 'field'; + +} + +/** + * TranslatedItem class. + * + * @package Cake.Test.Case.Model + */ +class TranslatedItem extends CakeTestModel { + +/** + * name property + * + * @var string 'TranslatedItem' + */ + public $name = 'TranslatedItem'; + +/** + * cacheQueries property + * + * @var bool false + */ + public $cacheQueries = false; + +/** + * actsAs property + * + * @var array + */ + public $actsAs = array('Translate' => array('content', 'title')); + +/** + * translateModel property + * + * @var string 'TranslateTestModel' + */ + public $translateModel = 'TranslateTestModel'; + +} + +/** + * TranslatedItem class. + * + * @package Cake.Test.Case.Model + */ +class TranslatedItem2 extends CakeTestModel { + +/** + * name property + * + * @var string 'TranslatedItem' + */ + public $name = 'TranslatedItem'; + +/** + * cacheQueries property + * + * @var bool false + */ + public $cacheQueries = false; + +/** + * actsAs property + * + * @var array + */ + public $actsAs = array('Translate' => array('content', 'title')); + +/** + * translateModel property + * + * @var string + */ + public $translateModel = 'TranslateWithPrefix'; + +} + +/** + * TranslatedItemWithTable class. + * + * @package Cake.Test.Case.Model + */ +class TranslatedItemWithTable extends CakeTestModel { + +/** + * name property + * + * @var string 'TranslatedItemWithTable' + */ + public $name = 'TranslatedItemWithTable'; + +/** + * useTable property + * + * @var string 'translated_items' + */ + public $useTable = 'translated_items'; + +/** + * cacheQueries property + * + * @var bool false + */ + public $cacheQueries = false; + +/** + * actsAs property + * + * @var array + */ + public $actsAs = array('Translate' => array('content', 'title')); + +/** + * translateModel property + * + * @var string + */ + public $translateModel = 'TranslateTestModel'; + +/** + * translateTable property + * + * @var string 'another_i18n' + */ + public $translateTable = 'another_i18n'; + +} + +/** + * TranslateArticleModel class. + * + * @package Cake.Test.Case.Model + */ +class TranslateArticleModel extends CakeTestModel { + +/** + * name property + * + * @var string 'TranslateArticleModel' + */ + public $name = 'TranslateArticleModel'; + +/** + * useTable property + * + * @var string 'article_i18n' + */ + public $useTable = 'article_i18n'; + +/** + * displayField property + * + * @var string 'field' + */ + public $displayField = 'field'; + +} + +/** + * TranslatedArticle class. + * + * @package Cake.Test.Case.Model + */ +class TranslatedArticle extends CakeTestModel { + +/** + * name property + * + * @var string 'TranslatedArticle' + */ + public $name = 'TranslatedArticle'; + +/** + * cacheQueries property + * + * @var bool false + */ + public $cacheQueries = false; + +/** + * actsAs property + * + * @var array + */ + public $actsAs = array('Translate' => array('title', 'body')); + +/** + * translateModel property + * + * @var string 'TranslateArticleModel' + */ + public $translateModel = 'TranslateArticleModel'; + +/** + * belongsTo property + * + * @var array + */ + public $belongsTo = array('User'); + +/** + * belongsTo property + * + * @var array + */ + public $hasMany = array('TranslatedItem'); + +} + +class CounterCacheUser extends CakeTestModel { + + public $name = 'CounterCacheUser'; + + public $alias = 'User'; + + public $hasMany = array( + 'Post' => array( + 'className' => 'CounterCachePost', + 'foreignKey' => 'user_id' + ) + ); +} + +class CounterCachePost extends CakeTestModel { + + public $name = 'CounterCachePost'; + + public $alias = 'Post'; + + public $belongsTo = array( + 'User' => array( + 'className' => 'CounterCacheUser', + 'foreignKey' => 'user_id', + 'counterCache' => true + ) + ); +} + +class CounterCacheUserNonstandardPrimaryKey extends CakeTestModel { + + public $name = 'CounterCacheUserNonstandardPrimaryKey'; + + public $alias = 'User'; + + public $primaryKey = 'uid'; + + public $hasMany = array( + 'Post' => array( + 'className' => 'CounterCachePostNonstandardPrimaryKey', + 'foreignKey' => 'uid' + ) + ); + +} + +class CounterCachePostNonstandardPrimaryKey extends CakeTestModel { + + public $name = 'CounterCachePostNonstandardPrimaryKey'; + + public $alias = 'Post'; + + public $primaryKey = 'pid'; + + public $belongsTo = array( + 'User' => array( + 'className' => 'CounterCacheUserNonstandardPrimaryKey', + 'foreignKey' => 'uid', + 'counterCache' => true + ) + ); + +} + +class ArticleB extends CakeTestModel { + + public $name = 'ArticleB'; + + public $useTable = 'articles'; + + public $hasAndBelongsToMany = array( + 'TagB' => array( + 'className' => 'TagB', + 'joinTable' => 'articles_tags', + 'foreignKey' => 'article_id', + 'associationForeignKey' => 'tag_id' + ) + ); + +} + +class TagB extends CakeTestModel { + + public $name = 'TagB'; + + public $useTable = 'tags'; + + public $hasAndBelongsToMany = array( + 'ArticleB' => array( + 'className' => 'ArticleB', + 'joinTable' => 'articles_tags', + 'foreignKey' => 'tag_id', + 'associationForeignKey' => 'article_id' + ) + ); + +} + +class Fruit extends CakeTestModel { + + public $name = 'Fruit'; + + public $hasAndBelongsToMany = array( + 'UuidTag' => array( + 'className' => 'UuidTag', + 'joinTable' => 'fruits_uuid_tags', + 'foreignKey' => 'fruit_id', + 'associationForeignKey' => 'uuid_tag_id', + 'with' => 'FruitsUuidTag' + ) + ); + +} + +class FruitsUuidTag extends CakeTestModel { + + public $name = 'FruitsUuidTag'; + + public $primaryKey = false; + + public $belongsTo = array( + 'UuidTag' => array( + 'className' => 'UuidTag', + 'foreignKey' => 'uuid_tag_id', + ), + 'Fruit' => array( + 'className' => 'Fruit', + 'foreignKey' => 'fruit_id', + ) + ); + +} + +class UuidTag extends CakeTestModel { + + public $name = 'UuidTag'; + + public $hasAndBelongsToMany = array( + 'Fruit' => array( + 'className' => 'Fruit', + 'joinTable' => 'fruits_uuid_tags', + 'foreign_key' => 'uuid_tag_id', + 'associationForeignKey' => 'fruit_id', + 'with' => 'FruitsUuidTag' + ) + ); + +} + +class FruitNoWith extends CakeTestModel { + + public $name = 'Fruit'; + + public $useTable = 'fruits'; + + public $hasAndBelongsToMany = array( + 'UuidTag' => array( + 'className' => 'UuidTagNoWith', + 'joinTable' => 'fruits_uuid_tags', + 'foreignKey' => 'fruit_id', + 'associationForeignKey' => 'uuid_tag_id', + ) + ); + +} + +class UuidTagNoWith extends CakeTestModel { + + public $name = 'UuidTag'; + + public $useTable = 'uuid_tags'; + + public $hasAndBelongsToMany = array( + 'Fruit' => array( + 'className' => 'FruitNoWith', + 'joinTable' => 'fruits_uuid_tags', + 'foreign_key' => 'uuid_tag_id', + 'associationForeignKey' => 'fruit_id', + ) + ); + +} + +class ProductUpdateAll extends CakeTestModel { + + public $name = 'ProductUpdateAll'; + + public $useTable = 'product_update_all'; + +} + +class GroupUpdateAll extends CakeTestModel { + + public $name = 'GroupUpdateAll'; + + public $useTable = 'group_update_all'; + +} + +class TransactionTestModel extends CakeTestModel { + + public $name = 'TransactionTestModel'; + + public $useTable = 'samples'; + + public function afterSave($created) { + $data = array( + array('apple_id' => 1, 'name' => 'sample6'), + ); + $this->saveAll($data, array('atomic' => true, 'callbacks' => false)); + } + +} + +class TransactionManyTestModel extends CakeTestModel { + + public $name = 'TransactionManyTestModel'; + + public $useTable = 'samples'; + + public function afterSave($created) { + $data = array( + array('apple_id' => 1, 'name' => 'sample6'), + ); + $this->saveMany($data, array('atomic' => true, 'callbacks' => false)); + } + +} + +class Site extends CakeTestModel { + + public $name = 'Site'; + + public $useTable = 'sites'; + + public $hasAndBelongsToMany = array( + 'Domain' => array('unique' => 'keepExisting'), + ); +} + +class Domain extends CakeTestModel { + + public $name = 'Domain'; + + public $useTable = 'domains'; + + public $hasAndBelongsToMany = array( + 'Site' => array('unique' => 'keepExisting'), + ); +} + +/** + * TestModel class + * + * @package Cake.Test.Case.Model + */ +class TestModel extends CakeTestModel { + +/** + * name property + * + * @var string 'TestModel' + */ + public $name = 'TestModel'; + +/** + * useTable property + * + * @var bool false + */ + public $useTable = false; + +/** + * schema property + * + * @var array + */ + protected $_schema = array( + 'id' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => '8'), + 'client_id' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => '11'), + 'name' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'), + 'login' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'), + 'passwd' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '255'), + 'addr_1' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '255'), + 'addr_2' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '25'), + 'zip_code' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'), + 'city' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'), + 'country' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'), + 'phone' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'), + 'fax' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'), + 'url' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '255'), + 'email' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'), + 'comments' => array('type' => 'text', 'null' => '1', 'default' => '', 'length' => '155'), + 'last_login' => array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => ''), + 'created' => array('type' => 'date', 'null' => '1', 'default' => '', 'length' => ''), + 'updated' => array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => null) + ); + +/** + * find method + * + * @param mixed $conditions + * @param mixed $fields + * @param mixed $order + * @param mixed $recursive + * @return void + */ + public function find($conditions = null, $fields = null, $order = null, $recursive = null) { + return array($conditions, $fields); + } + +/** + * findAll method + * + * @param mixed $conditions + * @param mixed $fields + * @param mixed $order + * @param mixed $recursive + * @return void + */ + public function findAll($conditions = null, $fields = null, $order = null, $recursive = null) { + return $conditions; + } + +} + +/** + * TestModel2 class + * + * @package Cake.Test.Case.Model + */ +class TestModel2 extends CakeTestModel { + +/** + * name property + * + * @var string 'TestModel2' + */ + public $name = 'TestModel2'; + +/** + * useTable property + * + * @var bool false + */ + public $useTable = false; +} + +/** + * TestModel4 class + * + * @package Cake.Test.Case.Model + */ +class TestModel3 extends CakeTestModel { + +/** + * name property + * + * @var string 'TestModel3' + */ + public $name = 'TestModel3'; + +/** + * useTable property + * + * @var bool false + */ + public $useTable = false; +} + +/** + * TestModel4 class + * + * @package Cake.Test.Case.Model + */ +class TestModel4 extends CakeTestModel { + +/** + * name property + * + * @var string 'TestModel4' + */ + public $name = 'TestModel4'; + +/** + * table property + * + * @var string 'test_model4' + */ + public $table = 'test_model4'; + +/** + * useTable property + * + * @var bool false + */ + public $useTable = false; + +/** + * belongsTo property + * + * @var array + */ + public $belongsTo = array( + 'TestModel4Parent' => array( + 'className' => 'TestModel4', + 'foreignKey' => 'parent_id' + ) + ); + +/** + * hasOne property + * + * @var array + */ + public $hasOne = array( + 'TestModel5' => array( + 'className' => 'TestModel5', + 'foreignKey' => 'test_model4_id' + ) + ); + +/** + * hasAndBelongsToMany property + * + * @var array + */ + public $hasAndBelongsToMany = array('TestModel7' => array( + 'className' => 'TestModel7', + 'joinTable' => 'test_model4_test_model7', + 'foreignKey' => 'test_model4_id', + 'associationForeignKey' => 'test_model7_id', + 'with' => 'TestModel4TestModel7' + )); + +/** + * schema method + * + * @return void + */ + public function schema($field = false) { + if (!isset($this->_schema)) { + $this->_schema = array( + 'id' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => '8'), + 'name' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'), + 'created' => array('type' => 'date', 'null' => '1', 'default' => '', 'length' => ''), + 'updated' => array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => null) + ); + } + return $this->_schema; + } + +} + +/** + * TestModel4TestModel7 class + * + * @package Cake.Test.Case.Model + */ +class TestModel4TestModel7 extends CakeTestModel { + +/** + * name property + * + * @var string 'TestModel4TestModel7' + */ + public $name = 'TestModel4TestModel7'; + +/** + * table property + * + * @var string 'test_model4_test_model7' + */ + public $table = 'test_model4_test_model7'; + +/** + * useTable property + * + * @var bool false + */ + public $useTable = false; + +/** + * schema method + * + * @return void + */ + public function schema($field = false) { + if (!isset($this->_schema)) { + $this->_schema = array( + 'test_model4_id' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => '8'), + 'test_model7_id' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => '8') + ); + } + return $this->_schema; + } + +} + +/** + * TestModel5 class + * + * @package Cake.Test.Case.Model + */ +class TestModel5 extends CakeTestModel { + +/** + * name property + * + * @var string 'TestModel5' + */ + public $name = 'TestModel5'; + +/** + * table property + * + * @var string 'test_model5' + */ + public $table = 'test_model5'; + +/** + * useTable property + * + * @var bool false + */ + public $useTable = false; + +/** + * belongsTo property + * + * @var array + */ + public $belongsTo = array('TestModel4' => array( + 'className' => 'TestModel4', + 'foreignKey' => 'test_model4_id' + )); + +/** + * hasMany property + * + * @var array + */ + public $hasMany = array('TestModel6' => array( + 'className' => 'TestModel6', + 'foreignKey' => 'test_model5_id' + )); + +/** + * schema method + * + * @return void + */ + public function schema($field = false) { + if (!isset($this->_schema)) { + $this->_schema = array( + 'id' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => '8'), + 'test_model4_id' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => '8'), + 'name' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'), + 'created' => array('type' => 'date', 'null' => '1', 'default' => '', 'length' => ''), + 'updated' => array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => null) + ); + } + return $this->_schema; + } + +} + +/** + * TestModel6 class + * + * @package Cake.Test.Case.Model + */ +class TestModel6 extends CakeTestModel { + +/** + * name property + * + * @var string 'TestModel6' + */ + public $name = 'TestModel6'; + +/** + * table property + * + * @var string 'test_model6' + */ + public $table = 'test_model6'; + +/** + * useTable property + * + * @var bool false + */ + public $useTable = false; + +/** + * belongsTo property + * + * @var array + */ + public $belongsTo = array( + 'TestModel5' => array( + 'className' => 'TestModel5', + 'foreignKey' => 'test_model5_id' + ) + ); + +/** + * schema method + * + * @return void + */ + public function schema($field = false) { + if (!isset($this->_schema)) { + $this->_schema = array( + 'id' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => '8'), + 'test_model5_id' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => '8'), + 'name' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'), + 'created' => array('type' => 'date', 'null' => '1', 'default' => '', 'length' => ''), + 'updated' => array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => null) + ); + } + return $this->_schema; + } + +} + +/** + * TestModel7 class + * + * @package Cake.Test.Case.Model + */ +class TestModel7 extends CakeTestModel { + +/** + * name property + * + * @var string 'TestModel7' + */ + public $name = 'TestModel7'; + +/** + * table property + * + * @var string 'test_model7' + */ + public $table = 'test_model7'; + +/** + * useTable property + * + * @var bool false + */ + public $useTable = false; + +/** + * schema method + * + * @return void + */ + public function schema($field = false) { + if (!isset($this->_schema)) { + $this->_schema = array( + 'id' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => '8'), + 'name' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'), + 'created' => array('type' => 'date', 'null' => '1', 'default' => '', 'length' => ''), + 'updated' => array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => null) + ); + } + return $this->_schema; + } + +} + +/** + * TestModel8 class + * + * @package Cake.Test.Case.Model + */ +class TestModel8 extends CakeTestModel { + +/** + * name property + * + * @var string 'TestModel8' + */ + public $name = 'TestModel8'; + +/** + * table property + * + * @var string 'test_model8' + */ + public $table = 'test_model8'; + +/** + * useTable property + * + * @var bool false + */ + public $useTable = false; + +/** + * hasOne property + * + * @var array + */ + public $hasOne = array( + 'TestModel9' => array( + 'className' => 'TestModel9', + 'foreignKey' => 'test_model8_id', + 'conditions' => 'TestModel9.name != \'mariano\'' + ) + ); + +/** + * schema method + * + * @return void + */ + public function schema($field = false) { + if (!isset($this->_schema)) { + $this->_schema = array( + 'id' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => '8'), + 'test_model9_id' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => '8'), + 'name' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'), + 'created' => array('type' => 'date', 'null' => '1', 'default' => '', 'length' => ''), + 'updated' => array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => null) + ); + } + return $this->_schema; + } + +} + +/** + * TestModel9 class + * + * @package Cake.Test.Case.Model + */ +class TestModel9 extends CakeTestModel { + +/** + * name property + * + * @var string 'TestModel9' + */ + public $name = 'TestModel9'; + +/** + * table property + * + * @var string 'test_model9' + */ + public $table = 'test_model9'; + +/** + * useTable property + * + * @var bool false + */ + public $useTable = false; + +/** + * belongsTo property + * + * @var array + */ + public $belongsTo = array( + 'TestModel8' => array( + 'className' => 'TestModel8', + 'foreignKey' => 'test_model8_id', + 'conditions' => 'TestModel8.name != \'larry\'' + ) + ); + +/** + * schema method + * + * @return void + */ + public function schema($field = false) { + if (!isset($this->_schema)) { + $this->_schema = array( + 'id' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => '8'), + 'test_model8_id' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => '11'), + 'name' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'), + 'created' => array('type' => 'date', 'null' => '1', 'default' => '', 'length' => ''), + 'updated' => array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => null) + ); + } + return $this->_schema; + } + +} + +/** + * Level class + * + * @package Cake.Test.Case.Model + */ +class Level extends CakeTestModel { + +/** + * name property + * + * @var string 'Level' + */ + public $name = 'Level'; + +/** + * table property + * + * @var string 'level' + */ + public $table = 'level'; + +/** + * useTable property + * + * @var bool false + */ + public $useTable = false; + +/** + * hasMany property + * + * @var array + */ + public $hasMany = array( + 'Group' => array( + 'className' => 'Group' + ), + 'User2' => array( + 'className' => 'User2' + ) + ); + +/** + * schema method + * + * @return void + */ + public function schema($field = false) { + if (!isset($this->_schema)) { + $this->_schema = array( + 'id' => array('type' => 'integer', 'null' => false, 'default' => null, 'length' => '10'), + 'name' => array('type' => 'string', 'null' => true, 'default' => null, 'length' => '20'), + ); + } + return $this->_schema; + } + +} + +/** + * Group class + * + * @package Cake.Test.Case.Model + */ +class Group extends CakeTestModel { + +/** + * name property + * + * @var string 'Group' + */ + public $name = 'Group'; + +/** + * table property + * + * @var string 'group' + */ + public $table = 'group'; + +/** + * useTable property + * + * @var bool false + */ + public $useTable = false; + +/** + * belongsTo property + * + * @var array + */ + public $belongsTo = array('Level'); + +/** + * hasMany property + * + * @var array + */ + public $hasMany = array('Category2', 'User2'); + +/** + * schema method + * + * @return void + */ + public function schema($field = false) { + if (!isset($this->_schema)) { + $this->_schema = array( + 'id' => array('type' => 'integer', 'null' => false, 'default' => null, 'length' => '10'), + 'level_id' => array('type' => 'integer', 'null' => false, 'default' => null, 'length' => '10'), + 'name' => array('type' => 'string', 'null' => true, 'default' => null, 'length' => '20'), + ); + } + return $this->_schema; + } + +} + +/** + * User2 class + * + * @package Cake.Test.Case.Model + */ +class User2 extends CakeTestModel { + +/** + * name property + * + * @var string 'User2' + */ + public $name = 'User2'; + +/** + * table property + * + * @var string 'user' + */ + public $table = 'user'; + +/** + * useTable property + * + * @var bool false + */ + public $useTable = false; + +/** + * belongsTo property + * + * @var array + */ + public $belongsTo = array( + 'Group' => array( + 'className' => 'Group' + ), + 'Level' => array( + 'className' => 'Level' + ) + ); + +/** + * hasMany property + * + * @var array + */ + public $hasMany = array( + 'Article2' => array( + 'className' => 'Article2' + ), + ); + +/** + * schema method + * + * @return void + */ + public function schema($field = false) { + if (!isset($this->_schema)) { + $this->_schema = array( + 'id' => array('type' => 'integer', 'null' => false, 'default' => null, 'length' => '10'), + 'group_id' => array('type' => 'integer', 'null' => false, 'default' => null, 'length' => '10'), + 'level_id' => array('type' => 'integer', 'null' => false, 'default' => null, 'length' => '10'), + 'name' => array('type' => 'string', 'null' => true, 'default' => null, 'length' => '20'), + ); + } + return $this->_schema; + } + +} + +/** + * Category2 class + * + * @package Cake.Test.Case.Model + */ +class Category2 extends CakeTestModel { + +/** + * name property + * + * @var string 'Category2' + */ + public $name = 'Category2'; + +/** + * table property + * + * @var string 'category' + */ + public $table = 'category'; + +/** + * useTable property + * + * @var bool false + */ + public $useTable = false; + +/** + * belongsTo property + * + * @var array + */ + public $belongsTo = array( + 'Group' => array( + 'className' => 'Group', + 'foreignKey' => 'group_id' + ), + 'ParentCat' => array( + 'className' => 'Category2', + 'foreignKey' => 'parent_id' + ) + ); + +/** + * hasMany property + * + * @var array + */ + public $hasMany = array( + 'ChildCat' => array( + 'className' => 'Category2', + 'foreignKey' => 'parent_id' + ), + 'Article2' => array( + 'className' => 'Article2', + 'order' => 'Article2.published_date DESC', + 'foreignKey' => 'category_id', + 'limit' => '3') + ); + +/** + * schema method + * + * @return void + */ + public function schema($field = false) { + if (!isset($this->_schema)) { + $this->_schema = array( + 'id' => array('type' => 'integer', 'null' => false, 'default' => '', 'length' => '10'), + 'group_id' => array('type' => 'integer', 'null' => false, 'default' => '', 'length' => '10'), + 'parent_id' => array('type' => 'integer', 'null' => false, 'default' => '', 'length' => '10'), + 'name' => array('type' => 'string', 'null' => false, 'default' => '', 'length' => '255'), + 'icon' => array('type' => 'string', 'null' => false, 'default' => '', 'length' => '255'), + 'description' => array('type' => 'text', 'null' => false, 'default' => '', 'length' => null), + + ); + } + return $this->_schema; + } + +} + +/** + * Article2 class + * + * @package Cake.Test.Case.Model + */ +class Article2 extends CakeTestModel { + +/** + * name property + * + * @var string 'Article2' + */ + public $name = 'Article2'; + +/** + * table property + * + * @var string 'article' + */ + public $table = 'articles'; + +/** + * useTable property + * + * @var bool false + */ + public $useTable = false; + +/** + * belongsTo property + * + * @var array + */ + public $belongsTo = array( + 'Category2' => array('className' => 'Category2'), + 'User2' => array('className' => 'User2') + ); + +/** + * schema method + * + * @return void + */ + public function schema($field = false) { + if (!isset($this->_schema)) { + $this->_schema = array( + 'id' => array('type' => 'integer', 'null' => false, 'default' => '', 'length' => '10'), + 'category_id' => array('type' => 'integer', 'null' => false, 'default' => '0', 'length' => '10'), + 'user_id' => array('type' => 'integer', 'null' => false, 'default' => '0', 'length' => '10'), + 'rate_count' => array('type' => 'integer', 'null' => false, 'default' => '0', 'length' => '10'), + 'rate_sum' => array('type' => 'integer', 'null' => false, 'default' => '0', 'length' => '10'), + 'viewed' => array('type' => 'integer', 'null' => false, 'default' => '0', 'length' => '10'), + 'version' => array('type' => 'string', 'null' => true, 'default' => '', 'length' => '45'), + 'title' => array('type' => 'string', 'null' => false, 'default' => '', 'length' => '200'), + 'intro' => array('text' => 'string', 'null' => true, 'default' => '', 'length' => null), + 'comments' => array('type' => 'integer', 'null' => false, 'default' => '0', 'length' => '4'), + 'body' => array('text' => 'string', 'null' => true, 'default' => '', 'length' => null), + 'isdraft' => array('type' => 'boolean', 'null' => false, 'default' => '0', 'length' => '1'), + 'allow_comments' => array('type' => 'boolean', 'null' => false, 'default' => '1', 'length' => '1'), + 'moderate_comments' => array('type' => 'boolean', 'null' => false, 'default' => '1', 'length' => '1'), + 'published' => array('type' => 'boolean', 'null' => false, 'default' => '0', 'length' => '1'), + 'multipage' => array('type' => 'boolean', 'null' => false, 'default' => '0', 'length' => '1'), + 'published_date' => array('type' => 'datetime', 'null' => true, 'default' => '', 'length' => null), + 'created' => array('type' => 'datetime', 'null' => false, 'default' => '0000-00-00 00:00:00', 'length' => null), + 'modified' => array('type' => 'datetime', 'null' => false, 'default' => '0000-00-00 00:00:00', 'length' => null) + ); + } + return $this->_schema; + } + +} + +/** + * CategoryFeatured2 class + * + * @package Cake.Test.Case.Model + */ +class CategoryFeatured2 extends CakeTestModel { + +/** + * name property + * + * @var string 'CategoryFeatured2' + */ + public $name = 'CategoryFeatured2'; + +/** + * table property + * + * @var string 'category_featured' + */ + public $table = 'category_featured'; + +/** + * useTable property + * + * @var bool false + */ + public $useTable = false; + +/** + * schema method + * + * @return void + */ + public function schema($field = false) { + if (!isset($this->_schema)) { + $this->_schema = array( + 'id' => array('type' => 'integer', 'null' => false, 'default' => '', 'length' => '10'), + 'parent_id' => array('type' => 'integer', 'null' => false, 'default' => '', 'length' => '10'), + 'name' => array('type' => 'string', 'null' => false, 'default' => '', 'length' => '255'), + 'icon' => array('type' => 'string', 'null' => false, 'default' => '', 'length' => '255'), + 'description' => array('text' => 'string', 'null' => false, 'default' => '', 'length' => null) + ); + } + return $this->_schema; + } + +} + +/** + * Featured2 class + * + * @package Cake.Test.Case.Model + */ +class Featured2 extends CakeTestModel { + +/** + * name property + * + * @var string 'Featured2' + */ + public $name = 'Featured2'; + +/** + * table property + * + * @var string 'featured2' + */ + public $table = 'featured2'; + +/** + * useTable property + * + * @var bool false + */ + public $useTable = false; + +/** + * belongsTo property + * + * @var array + */ + public $belongsTo = array( + 'CategoryFeatured2' => array( + 'className' => 'CategoryFeatured2' + ) + ); + +/** + * schema method + * + * @return void + */ + public function schema($field = false) { + if (!isset($this->_schema)) { + $this->_schema = array( + 'id' => array('type' => 'integer', 'null' => false, 'default' => null, 'length' => '10'), + 'article_id' => array('type' => 'integer', 'null' => false, 'default' => '0', 'length' => '10'), + 'category_id' => array('type' => 'integer', 'null' => false, 'default' => '0', 'length' => '10'), + 'name' => array('type' => 'string', 'null' => true, 'default' => null, 'length' => '20') + ); + } + return $this->_schema; + } + +} + +/** + * Comment2 class + * + * @package Cake.Test.Case.Model + */ +class Comment2 extends CakeTestModel { + +/** + * name property + * + * @var string 'Comment2' + */ + public $name = 'Comment2'; + +/** + * table property + * + * @var string 'comment' + */ + public $table = 'comment'; + +/** + * belongsTo property + * + * @var array + */ + public $belongsTo = array('ArticleFeatured2', 'User2'); + +/** + * useTable property + * + * @var bool false + */ + public $useTable = false; + +/** + * schema method + * + * @return void + */ + public function schema($field = false) { + if (!isset($this->_schema)) { + $this->_schema = array( + 'id' => array('type' => 'integer', 'null' => false, 'default' => null, 'length' => '10'), + 'article_featured_id' => array('type' => 'integer', 'null' => false, 'default' => '0', 'length' => '10'), + 'user_id' => array('type' => 'integer', 'null' => false, 'default' => '0', 'length' => '10'), + 'name' => array('type' => 'string', 'null' => true, 'default' => null, 'length' => '20') + ); + } + return $this->_schema; + } + +} + +/** + * ArticleFeatured2 class + * + * @package Cake.Test.Case.Model + */ +class ArticleFeatured2 extends CakeTestModel { + +/** + * name property + * + * @var string 'ArticleFeatured2' + */ + public $name = 'ArticleFeatured2'; + +/** + * table property + * + * @var string 'article_featured' + */ + public $table = 'article_featured'; + +/** + * useTable property + * + * @var bool false + */ + public $useTable = false; + +/** + * belongsTo property + * + * @var array + */ + public $belongsTo = array( + 'CategoryFeatured2' => array('className' => 'CategoryFeatured2'), + 'User2' => array('className' => 'User2') + ); + +/** + * hasOne property + * + * @var array + */ + public $hasOne = array( + 'Featured2' => array('className' => 'Featured2') + ); + +/** + * hasMany property + * + * @var array + */ + public $hasMany = array( + 'Comment2' => array('className' => 'Comment2', 'dependent' => true) + ); + +/** + * schema method + * + * @return void + */ + public function schema($field = false) { + if (!isset($this->_schema)) { + $this->_schema = array( + 'id' => array('type' => 'integer', 'null' => false, 'default' => null, 'length' => '10'), + 'category_featured_id' => array('type' => 'integer', 'null' => false, 'default' => '0', 'length' => '10'), + 'user_id' => array('type' => 'integer', 'null' => false, 'default' => '0', 'length' => '10'), + 'title' => array('type' => 'string', 'null' => true, 'default' => null, 'length' => '20'), + 'body' => array('text' => 'string', 'null' => true, 'default' => '', 'length' => null), + 'published' => array('type' => 'boolean', 'null' => false, 'default' => '0', 'length' => '1'), + 'published_date' => array('type' => 'datetime', 'null' => true, 'default' => '', 'length' => null), + 'created' => array('type' => 'datetime', 'null' => false, 'default' => '0000-00-00 00:00:00', 'length' => null), + 'modified' => array('type' => 'datetime', 'null' => false, 'default' => '0000-00-00 00:00:00', 'length' => null) + ); + } + return $this->_schema; + } + +} + +/** + * MysqlTestModel class + * + * @package Cake.Test.Case.Model + */ +class MysqlTestModel extends Model { + +/** + * name property + * + * @var string 'MysqlTestModel' + */ + public $name = 'MysqlTestModel'; + +/** + * useTable property + * + * @var bool false + */ + public $useTable = false; + +/** + * find method + * + * @param mixed $conditions + * @param mixed $fields + * @param mixed $order + * @param mixed $recursive + * @return void + */ + public function find($conditions = null, $fields = null, $order = null, $recursive = null) { + return $conditions; + } + +/** + * findAll method + * + * @param mixed $conditions + * @param mixed $fields + * @param mixed $order + * @param mixed $recursive + * @return void + */ + public function findAll($conditions = null, $fields = null, $order = null, $recursive = null) { + return $conditions; + } + +/** + * schema method + * + * @return void + */ + public function schema($field = false) { + return array( + 'id' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => '8'), + 'client_id' => array('type' => 'integer', 'null' => '', 'default' => '0', 'length' => '11'), + 'name' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'), + 'login' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'), + 'passwd' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '255'), + 'addr_1' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '255'), + 'addr_2' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '25'), + 'zip_code' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'), + 'city' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'), + 'country' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'), + 'phone' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'), + 'fax' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'), + 'url' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '255'), + 'email' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'), + 'comments' => array('type' => 'text', 'null' => '1', 'default' => '', 'length' => ''), + 'last_login' => array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => ''), + 'created' => array('type' => 'date', 'null' => '1', 'default' => '', 'length' => ''), + 'updated' => array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => null) + ); + } + +} + +/** + * Test model for datasource prefixes + * + */ +class PrefixTestModel extends CakeTestModel { +} + +class PrefixTestUseTableModel extends CakeTestModel { + + public $name = 'PrefixTest'; + + public $useTable = 'prefix_tests'; + +} + +/** + * ScaffoldMock class + * + * @package Cake.Test.Case.Controller + */ +class ScaffoldMock extends CakeTestModel { + +/** + * useTable property + * + * @var string 'posts' + */ + public $useTable = 'articles'; + +/** + * belongsTo property + * + * @var array + */ + public $belongsTo = array( + 'User' => array( + 'className' => 'ScaffoldUser', + 'foreignKey' => 'user_id', + ) + ); + +/** + * hasMany property + * + * @var array + */ + public $hasMany = array( + 'Comment' => array( + 'className' => 'ScaffoldComment', + 'foreignKey' => 'article_id', + ) + ); + +/** + * hasAndBelongsToMany property + * + * @var string + */ + public $hasAndBelongsToMany = array( + 'ScaffoldTag' => array( + 'className' => 'ScaffoldTag', + 'foreignKey' => 'something_id', + 'associationForeignKey' => 'something_else_id', + 'joinTable' => 'join_things' + ) + ); + +} + +/** + * ScaffoldUser class + * + * @package Cake.Test.Case.Controller + */ +class ScaffoldUser extends CakeTestModel { + +/** + * useTable property + * + * @var string 'posts' + */ + public $useTable = 'users'; + +/** + * hasMany property + * + * @var array + */ + public $hasMany = array( + 'Article' => array( + 'className' => 'ScaffoldMock', + 'foreignKey' => 'article_id', + ) + ); +} + +/** + * ScaffoldComment class + * + * @package Cake.Test.Case.Controller + */ +class ScaffoldComment extends CakeTestModel { + +/** + * useTable property + * + * @var string 'posts' + */ + public $useTable = 'comments'; + +/** + * belongsTo property + * + * @var array + */ + public $belongsTo = array( + 'Article' => array( + 'className' => 'ScaffoldMock', + 'foreignKey' => 'article_id', + ) + ); +} + +/** + * ScaffoldTag class + * + * @package Cake.Test.Case.Controller + */ +class ScaffoldTag extends CakeTestModel { + +/** + * useTable property + * + * @var string 'posts' + */ + public $useTable = 'tags'; + +} + +/** + * Player class + * + * @package Cake.Test.Case.Model + */ +class Player extends CakeTestModel { + + public $hasAndBelongsToMany = array( + 'Guild' => array( + 'with' => 'GuildsPlayer', + 'unique' => true, + ), + ); + +} + +/** + * Guild class + * + * @package Cake.Test.Case.Model + */ +class Guild extends CakeTestModel { + + public $hasAndBelongsToMany = array( + 'Player' => array( + 'with' => 'GuildsPlayer', + 'unique' => true, + ), + ); + +} + +/** + * GuildsPlayer class + * + * @package Cake.Test.Case.Model + */ +class GuildsPlayer extends CakeTestModel { + + public $useDbConfig = 'test2'; + + public $belongsTo = array( + 'Player', + 'Guild', + ); +} + +/** + * Armor class + * + * @package Cake.Test.Case.Model + */ +class Armor extends CakeTestModel { + + public $useDbConfig = 'test2'; + + public $hasAndBelongsToMany = array( + 'Player' => array('with' => 'ArmorsPlayer'), + ); +} + +/** + * ArmorsPlayer class + * + * @package Cake.Test.Case.Model + */ +class ArmorsPlayer extends CakeTestModel { + + public $useDbConfig = 'test_database_three'; + +} + +/** + * CustomArticle class + * + * @package Cake.Test.Case.Model + */ +class CustomArticle extends AppModel { + +/** + * useTable property + * + * @var string + */ + public $useTable = 'articles'; + +/** + * findMethods property + * + * @var array + */ + public $findMethods = array('unPublished' => true); + +/** + * belongsTo property + * + * @var array + */ + public $belongsTo = array('User'); + +/** + * _findUnPublished custom find + * + * @return array + */ + protected function _findUnPublished($state, $query, $results = array()) { + if ($state === 'before') { + $query['conditions']['published'] = 'N'; + return $query; + } + return $results; + } + +/** + * Alters title data + * + * @return void + **/ + public function beforeValidate($options = array()) { + $this->data[$this->alias]['title'] = 'foo'; + if ($this->findMethods['unPublished'] === true) { + $this->findMethods['unPublished'] = false; + } else { + $this->findMethods['unPublished'] = 'true again'; + } + } + +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Network/CakeRequestTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Network/CakeRequestTest.php new file mode 100644 index 0000000..8ef0e18 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Network/CakeRequestTest.php @@ -0,0 +1,1890 @@ +_base(); + if (empty($url)) { + $url = $this->_url(); + } + if ($url[0] == '/') { + $url = substr($url, 1); + } + $this->url = $url; + + if ($parseEnvironment) { + $this->_processPost(); + $this->_processGet(); + $this->_processFiles(); + } + $this->here = $this->base . '/' . $this->url; + } + +} + +class CakeRequestTest extends CakeTestCase { + +/** + * setup callback + * + * @return void + */ + public function setUp() { + parent::setUp(); + $this->_app = Configure::read('App'); + $this->_case = null; + if (isset($_GET['case'])) { + $this->_case = $_GET['case']; + unset($_GET['case']); + } + + Configure::write('App.baseUrl', false); + } + +/** + * tearDown + * + * @return void + */ + public function tearDown() { + parent::tearDown(); + if (!empty($this->_case)) { + $_GET['case'] = $this->_case; + } + Configure::write('App', $this->_app); + } + +/** + * test that the autoparse = false constructor works. + * + * @return void + */ + public function testNoAutoParseConstruction() { + $_GET = array( + 'one' => 'param' + ); + $request = new CakeRequest(null, false); + $this->assertFalse(isset($request->query['one'])); + } + +/** + * test construction + * + * @return void + */ + public function testConstructionGetParsing() { + $_GET = array( + 'one' => 'param', + 'two' => 'banana' + ); + $request = new CakeRequest('some/path'); + $this->assertEquals($request->query, $_GET); + + $_GET = array( + 'one' => 'param', + 'two' => 'banana', + ); + $request = new CakeRequest('some/path'); + $this->assertEquals($request->query, $_GET); + $this->assertEquals('some/path', $request->url); + } + +/** + * Test that querystring args provided in the url string are parsed. + * + * @return void + */ + public function testQueryStringParsingFromInputUrl() { + $_GET = array(); + $request = new CakeRequest('some/path?one=something&two=else'); + $expected = array('one' => 'something', 'two' => 'else'); + $this->assertEquals($expected, $request->query); + $this->assertEquals('some/path?one=something&two=else', $request->url); + } + +/** + * Test that named arguments + querystrings are handled correctly. + * + * @return void + */ + public function testQueryStringAndNamedParams() { + $_SERVER['REQUEST_URI'] = '/tasks/index/page:1?ts=123456'; + $request = new CakeRequest(); + $this->assertEquals('tasks/index/page:1', $request->url); + + $_SERVER['REQUEST_URI'] = '/tasks/index/page:1/?ts=123456'; + $request = new CakeRequest(); + $this->assertEquals('tasks/index/page:1/', $request->url); + } + +/** + * test addParams() method + * + * @return void + */ + public function testAddParams() { + $request = new CakeRequest('some/path'); + $request->params = array('controller' => 'posts', 'action' => 'view'); + $result = $request->addParams(array('plugin' => null, 'action' => 'index')); + + $this->assertSame($result, $request, 'Method did not return itself. %s'); + + $this->assertEquals('posts', $request->controller); + $this->assertEquals('index', $request->action); + $this->assertEquals(null, $request->plugin); + } + +/** + * test splicing in paths. + * + * @return void + */ + public function testAddPaths() { + $request = new CakeRequest('some/path'); + $request->webroot = '/some/path/going/here/'; + $result = $request->addPaths(array( + 'random' => '/something', 'webroot' => '/', 'here' => '/', 'base' => '/base_dir' + )); + + $this->assertSame($result, $request, 'Method did not return itself. %s'); + + $this->assertEquals('/', $request->webroot); + $this->assertEquals('/base_dir', $request->base); + $this->assertEquals('/', $request->here); + $this->assertFalse(isset($request->random)); + } + +/** + * test parsing POST data into the object. + * + * @return void + */ + public function testPostParsing() { + $_POST = array('data' => array( + 'Article' => array('title') + )); + $request = new CakeRequest('some/path'); + $this->assertEquals($_POST['data'], $request->data); + + $_POST = array('one' => 1, 'two' => 'three'); + $request = new CakeRequest('some/path'); + $this->assertEquals($_POST, $request->data); + + $_POST = array( + 'data' => array( + 'Article' => array('title' => 'Testing'), + ), + 'action' => 'update' + ); + $request = new CakeRequest('some/path'); + $expected = array( + 'Article' => array('title' => 'Testing'), + 'action' => 'update' + ); + $this->assertEquals($expected, $request->data); + + $_POST = array('data' => array( + 'Article' => array('title'), + 'Tag' => array('Tag' => array(1, 2)) + )); + $request = new CakeRequest('some/path'); + $this->assertEquals($_POST['data'], $request->data); + + $_POST = array('data' => array( + 'Article' => array('title' => 'some title'), + 'Tag' => array('Tag' => array(1, 2)) + )); + $request = new CakeRequest('some/path'); + $this->assertEquals($_POST['data'], $request->data); + + $_POST = array( + 'a' => array(1, 2), + 'b' => array(1, 2) + ); + $request = new CakeRequest('some/path'); + $this->assertEquals($_POST, $request->data); + } + +/** + * test parsing PUT data into the object. + * + * @return void + */ + public function testPutParsing() { + $_SERVER['REQUEST_METHOD'] = 'PUT'; + $_SERVER['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'; + + $data = array('data' => array( + 'Article' => array('title') + )); + + $request = $this->getMock('TestCakeRequest', array('_readInput')); + $request->expects($this->at(0))->method('_readInput') + ->will($this->returnValue('data[Article][]=title')); + $request->reConstruct(); + $this->assertEquals($data['data'], $request->data); + + $data = array('one' => 1, 'two' => 'three'); + $request = $this->getMock('TestCakeRequest', array('_readInput')); + $request->expects($this->at(0))->method('_readInput') + ->will($this->returnValue('one=1&two=three')); + $request->reConstruct(); + $this->assertEquals($data, $request->data); + + $data = array( + 'data' => array( + 'Article' => array('title' => 'Testing'), + ), + 'action' => 'update' + ); + $request = $this->getMock('TestCakeRequest', array('_readInput')); + $request->expects($this->at(0))->method('_readInput') + ->will($this->returnValue('data[Article][title]=Testing&action=update')); + $request->reConstruct(); + $expected = array( + 'Article' => array('title' => 'Testing'), + 'action' => 'update' + ); + $this->assertEquals($expected, $request->data); + + $_SERVER['REQUEST_METHOD'] = 'DELETE'; + $data = array('data' => array( + 'Article' => array('title'), + 'Tag' => array('Tag' => array(1, 2)) + )); + $request = $this->getMock('TestCakeRequest', array('_readInput')); + $request->expects($this->at(0))->method('_readInput') + ->will($this->returnValue('data[Article][]=title&Tag[Tag][]=1&Tag[Tag][]=2')); + $request->reConstruct(); + $this->assertEquals($data['data'], $request->data); + + $data = array('data' => array( + 'Article' => array('title' => 'some title'), + 'Tag' => array('Tag' => array(1, 2)) + )); + $request = $this->getMock('TestCakeRequest', array('_readInput')); + $request->expects($this->at(0))->method('_readInput') + ->will($this->returnValue('data[Article][title]=some%20title&Tag[Tag][]=1&Tag[Tag][]=2')); + $request->reConstruct(); + $this->assertEquals($data['data'], $request->data); + + $data = array( + 'a' => array(1, 2), + 'b' => array(1, 2) + ); + $request = $this->getMock('TestCakeRequest', array('_readInput')); + $request->expects($this->at(0))->method('_readInput') + ->will($this->returnValue('a[]=1&a[]=2&b[]=1&b[]=2')); + $request->reConstruct(); + $this->assertEquals($data, $request->data); + } + +/** + * test parsing json PUT data into the object. + * + * @return void + */ + public function testPutParsingJSON() { + $_SERVER['REQUEST_METHOD'] = 'PUT'; + $_SERVER['CONTENT_TYPE'] = 'application/json'; + + $request = $this->getMock('TestCakeRequest', array('_readInput')); + $request->expects($this->at(0))->method('_readInput') + ->will($this->returnValue('{Article":["title"]}')); + $request->reConstruct(); + $this->assertEquals('{Article":["title"]}', $request->data); + } + +/** + * test parsing of FILES array + * + * @return void + */ + public function testFilesParsing() { + $_FILES = array( + 'data' => array( + 'name' => array( + 'File' => array( + array('data' => 'cake_sqlserver_patch.patch'), + array('data' => 'controller.diff'), + array('data' => ''), + array('data' => ''), + ), + 'Post' => array('attachment' => 'jquery-1.2.1.js'), + ), + 'type' => array( + 'File' => array( + array('data' => ''), + array('data' => ''), + array('data' => ''), + array('data' => ''), + ), + 'Post' => array('attachment' => 'application/x-javascript'), + ), + 'tmp_name' => array( + 'File' => array( + array('data' => '/private/var/tmp/phpy05Ywj'), + array('data' => '/private/var/tmp/php7MBztY'), + array('data' => ''), + array('data' => ''), + ), + 'Post' => array('attachment' => '/private/var/tmp/phpEwlrIo'), + ), + 'error' => array( + 'File' => array( + array('data' => 0), + array('data' => 0), + array('data' => 4), + array('data' => 4) + ), + 'Post' => array('attachment' => 0) + ), + 'size' => array( + 'File' => array( + array('data' => 6271), + array('data' => 350), + array('data' => 0), + array('data' => 0), + ), + 'Post' => array('attachment' => 80469) + ), + ) + ); + + $request = new CakeRequest('some/path'); + $expected = array( + 'File' => array( + array( + 'data' => array( + 'name' => 'cake_sqlserver_patch.patch', + 'type' => '', + 'tmp_name' => '/private/var/tmp/phpy05Ywj', + 'error' => 0, + 'size' => 6271, + ) + ), + array( + 'data' => array( + 'name' => 'controller.diff', + 'type' => '', + 'tmp_name' => '/private/var/tmp/php7MBztY', + 'error' => 0, + 'size' => 350, + ) + ), + array( + 'data' => array( + 'name' => '', + 'type' => '', + 'tmp_name' => '', + 'error' => 4, + 'size' => 0, + ) + ), + array( + 'data' => array( + 'name' => '', + 'type' => '', + 'tmp_name' => '', + 'error' => 4, + 'size' => 0, + ) + ), + ), + 'Post' => array( + 'attachment' => array( + 'name' => 'jquery-1.2.1.js', + 'type' => 'application/x-javascript', + 'tmp_name' => '/private/var/tmp/phpEwlrIo', + 'error' => 0, + 'size' => 80469, + ) + ) + ); + $this->assertEquals($expected, $request->data); + + $_FILES = array( + 'data' => array( + 'name' => array( + 'Document' => array( + 1 => array( + 'birth_cert' => 'born on.txt', + 'passport' => 'passport.txt', + 'drivers_license' => 'ugly pic.jpg' + ), + 2 => array( + 'birth_cert' => 'aunt betty.txt', + 'passport' => 'betty-passport.txt', + 'drivers_license' => 'betty-photo.jpg' + ), + ), + ), + 'type' => array( + 'Document' => array( + 1 => array( + 'birth_cert' => 'application/octet-stream', + 'passport' => 'application/octet-stream', + 'drivers_license' => 'application/octet-stream', + ), + 2 => array( + 'birth_cert' => 'application/octet-stream', + 'passport' => 'application/octet-stream', + 'drivers_license' => 'application/octet-stream', + ) + ) + ), + 'tmp_name' => array( + 'Document' => array( + 1 => array( + 'birth_cert' => '/private/var/tmp/phpbsUWfH', + 'passport' => '/private/var/tmp/php7f5zLt', + 'drivers_license' => '/private/var/tmp/phpMXpZgT', + ), + 2 => array( + 'birth_cert' => '/private/var/tmp/php5kHZt0', + 'passport' => '/private/var/tmp/phpnYkOuM', + 'drivers_license' => '/private/var/tmp/php9Rq0P3', + ) + ) + ), + 'error' => array( + 'Document' => array( + 1 => array( + 'birth_cert' => 0, + 'passport' => 0, + 'drivers_license' => 0, + ), + 2 => array( + 'birth_cert' => 0, + 'passport' => 0, + 'drivers_license' => 0, + ) + ) + ), + 'size' => array( + 'Document' => array( + 1 => array( + 'birth_cert' => 123, + 'passport' => 458, + 'drivers_license' => 875, + ), + 2 => array( + 'birth_cert' => 876, + 'passport' => 976, + 'drivers_license' => 9783, + ) + ) + ) + ) + ); + + $request = new CakeRequest('some/path'); + $expected = array( + 'Document' => array( + 1 => array( + 'birth_cert' => array( + 'name' => 'born on.txt', + 'tmp_name' => '/private/var/tmp/phpbsUWfH', + 'error' => 0, + 'size' => 123, + 'type' => 'application/octet-stream', + ), + 'passport' => array( + 'name' => 'passport.txt', + 'tmp_name' => '/private/var/tmp/php7f5zLt', + 'error' => 0, + 'size' => 458, + 'type' => 'application/octet-stream', + ), + 'drivers_license' => array( + 'name' => 'ugly pic.jpg', + 'tmp_name' => '/private/var/tmp/phpMXpZgT', + 'error' => 0, + 'size' => 875, + 'type' => 'application/octet-stream', + ), + ), + 2 => array( + 'birth_cert' => array( + 'name' => 'aunt betty.txt', + 'tmp_name' => '/private/var/tmp/php5kHZt0', + 'error' => 0, + 'size' => 876, + 'type' => 'application/octet-stream', + ), + 'passport' => array( + 'name' => 'betty-passport.txt', + 'tmp_name' => '/private/var/tmp/phpnYkOuM', + 'error' => 0, + 'size' => 976, + 'type' => 'application/octet-stream', + ), + 'drivers_license' => array( + 'name' => 'betty-photo.jpg', + 'tmp_name' => '/private/var/tmp/php9Rq0P3', + 'error' => 0, + 'size' => 9783, + 'type' => 'application/octet-stream', + ), + ), + ) + ); + $this->assertEquals($expected, $request->data); + + $_FILES = array( + 'data' => array( + 'name' => array('birth_cert' => 'born on.txt'), + 'type' => array('birth_cert' => 'application/octet-stream'), + 'tmp_name' => array('birth_cert' => '/private/var/tmp/phpbsUWfH'), + 'error' => array('birth_cert' => 0), + 'size' => array('birth_cert' => 123) + ) + ); + + $request = new CakeRequest('some/path'); + $expected = array( + 'birth_cert' => array( + 'name' => 'born on.txt', + 'type' => 'application/octet-stream', + 'tmp_name' => '/private/var/tmp/phpbsUWfH', + 'error' => 0, + 'size' => 123 + ) + ); + $this->assertEquals($expected, $request->data); + + $_FILES = array( + 'something' => array( + 'name' => 'something.txt', + 'type' => 'text/plain', + 'tmp_name' => '/some/file', + 'error' => 0, + 'size' => 123 + ) + ); + $request = new CakeRequest('some/path'); + $this->assertEquals($request->params['form'], $_FILES); + } + +/** + * test method overrides coming in from POST data. + * + * @return void + */ + public function testMethodOverrides() { + $_POST = array('_method' => 'POST'); + $request = new CakeRequest('some/path'); + $this->assertEquals(env('REQUEST_METHOD'), 'POST'); + + $_POST = array('_method' => 'DELETE'); + $request = new CakeRequest('some/path'); + $this->assertEquals(env('REQUEST_METHOD'), 'DELETE'); + + $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'] = 'PUT'; + $request = new CakeRequest('some/path'); + $this->assertEquals(env('REQUEST_METHOD'), 'PUT'); + } + +/** + * test the clientIp method. + * + * @return void + */ + public function testclientIp() { + $_SERVER['HTTP_X_FORWARDED_FOR'] = '192.168.1.5, 10.0.1.1, proxy.com'; + $_SERVER['HTTP_CLIENT_IP'] = '192.168.1.2'; + $_SERVER['REMOTE_ADDR'] = '192.168.1.3'; + $request = new CakeRequest('some/path'); + $this->assertEquals('192.168.1.5', $request->clientIp(false)); + $this->assertEquals('192.168.1.2', $request->clientIp()); + + unset($_SERVER['HTTP_X_FORWARDED_FOR']); + $this->assertEquals('192.168.1.2', $request->clientIp()); + + unset($_SERVER['HTTP_CLIENT_IP']); + $this->assertEquals('192.168.1.3', $request->clientIp()); + + $_SERVER['HTTP_CLIENTADDRESS'] = '10.0.1.2, 10.0.1.1'; + $this->assertEquals('10.0.1.2', $request->clientIp()); + } + +/** + * test the referer function. + * + * @return void + */ + public function testReferer() { + $request = new CakeRequest('some/path'); + $request->webroot = '/'; + + $_SERVER['HTTP_REFERER'] = 'http://cakephp.org'; + $result = $request->referer(); + $this->assertSame($result, 'http://cakephp.org'); + + $_SERVER['HTTP_REFERER'] = ''; + $result = $request->referer(); + $this->assertSame($result, '/'); + + $_SERVER['HTTP_REFERER'] = FULL_BASE_URL . '/some/path'; + $result = $request->referer(true); + $this->assertSame($result, '/some/path'); + + $_SERVER['HTTP_REFERER'] = FULL_BASE_URL . '/some/path'; + $result = $request->referer(false); + $this->assertSame($result, FULL_BASE_URL . '/some/path'); + + $_SERVER['HTTP_REFERER'] = FULL_BASE_URL . '/some/path'; + $result = $request->referer(true); + $this->assertSame($result, '/some/path'); + + $_SERVER['HTTP_REFERER'] = FULL_BASE_URL . '/recipes/add'; + $result = $request->referer(true); + $this->assertSame($result, '/recipes/add'); + + $_SERVER['HTTP_X_FORWARDED_HOST'] = 'cakephp.org'; + $result = $request->referer(); + $this->assertSame($result, 'cakephp.org'); + } + +/** + * test the simple uses of is() + * + * @return void + */ + public function testIsHttpMethods() { + $request = new CakeRequest('some/path'); + + $this->assertFalse($request->is('undefined-behavior')); + + $_SERVER['REQUEST_METHOD'] = 'GET'; + $this->assertTrue($request->is('get')); + + $_SERVER['REQUEST_METHOD'] = 'POST'; + $this->assertTrue($request->is('POST')); + + $_SERVER['REQUEST_METHOD'] = 'PUT'; + $this->assertTrue($request->is('put')); + $this->assertFalse($request->is('get')); + + $_SERVER['REQUEST_METHOD'] = 'DELETE'; + $this->assertTrue($request->is('delete')); + $this->assertTrue($request->isDelete()); + + $_SERVER['REQUEST_METHOD'] = 'delete'; + $this->assertFalse($request->is('delete')); + } + +/** + * test the method() method. + * + * @return void + */ + public function testMethod() { + $_SERVER['REQUEST_METHOD'] = 'delete'; + $request = new CakeRequest('some/path'); + + $this->assertEquals('delete', $request->method()); + } + +/** + * test host retrieval. + * + * @return void + */ + public function testHost() { + $_SERVER['HTTP_HOST'] = 'localhost'; + $request = new CakeRequest('some/path'); + + $this->assertEquals('localhost', $request->host()); + } + +/** + * test domain retrieval. + * + * @return void + */ + public function testDomain() { + $_SERVER['HTTP_HOST'] = 'something.example.com'; + $request = new CakeRequest('some/path'); + + $this->assertEquals('example.com', $request->domain()); + + $_SERVER['HTTP_HOST'] = 'something.example.co.uk'; + $this->assertEquals('example.co.uk', $request->domain(2)); + } + +/** + * test getting subdomains for a host. + * + * @return void + */ + public function testSubdomain() { + $_SERVER['HTTP_HOST'] = 'something.example.com'; + $request = new CakeRequest('some/path'); + + $this->assertEquals(array('something'), $request->subdomains()); + + $_SERVER['HTTP_HOST'] = 'www.something.example.com'; + $this->assertEquals(array('www', 'something'), $request->subdomains()); + + $_SERVER['HTTP_HOST'] = 'www.something.example.co.uk'; + $this->assertEquals(array('www', 'something'), $request->subdomains(2)); + + $_SERVER['HTTP_HOST'] = 'example.co.uk'; + $this->assertEquals(array(), $request->subdomains(2)); + } + +/** + * test ajax, flash and friends + * + * @return void + */ + public function testisAjaxFlashAndFriends() { + $request = new CakeRequest('some/path'); + + $_SERVER['HTTP_USER_AGENT'] = 'Shockwave Flash'; + $this->assertTrue($request->is('flash')); + + $_SERVER['HTTP_USER_AGENT'] = 'Adobe Flash'; + $this->assertTrue($request->is('flash')); + + $_SERVER['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest'; + $this->assertTrue($request->is('ajax')); + + $_SERVER['HTTP_X_REQUESTED_WITH'] = 'XMLHTTPREQUEST'; + $this->assertFalse($request->is('ajax')); + $this->assertFalse($request->isAjax()); + + $_SERVER['HTTP_USER_AGENT'] = 'Android 2.0'; + $this->assertTrue($request->is('mobile')); + $this->assertTrue($request->isMobile()); + + $_SERVER['HTTP_USER_AGENT'] = 'Mozilla/5.0 (Windows NT 5.1; rv:2.0b6pre) Gecko/20100902 Firefox/4.0b6pre Fennec/2.0b1pre'; + $this->assertTrue($request->is('mobile')); + $this->assertTrue($request->isMobile()); + + $_SERVER['HTTP_USER_AGENT'] = 'Mozilla/5.0 (compatible; MSIE 9.0; Windows Phone OS 7.5; Trident/5.0; IEMobile/9.0; SAMSUNG; OMNIA7)'; + $this->assertTrue($request->is('mobile')); + $this->assertTrue($request->isMobile()); + } + +/** + * test __call expcetions + * + * @expectedException CakeException + * @return void + */ + public function testMagicCallExceptionOnUnknownMethod() { + $request = new CakeRequest('some/path'); + $request->IamABanana(); + } + +/** + * test is(ssl) + * + * @return void + */ + public function testIsSsl() { + $request = new CakeRequest('some/path'); + + $_SERVER['HTTPS'] = 1; + $this->assertTrue($request->is('ssl')); + + $_SERVER['HTTPS'] = 'on'; + $this->assertTrue($request->is('ssl')); + + $_SERVER['HTTPS'] = '1'; + $this->assertTrue($request->is('ssl')); + + $_SERVER['HTTPS'] = 'I am not empty'; + $this->assertTrue($request->is('ssl')); + + $_SERVER['HTTPS'] = 1; + $this->assertTrue($request->is('ssl')); + + $_SERVER['HTTPS'] = 'off'; + $this->assertFalse($request->is('ssl')); + + $_SERVER['HTTPS'] = false; + $this->assertFalse($request->is('ssl')); + + $_SERVER['HTTPS'] = ''; + $this->assertFalse($request->is('ssl')); + } + +/** + * test getting request params with object properties. + * + * @return void + */ + public function testMagicget() { + $request = new CakeRequest('some/path'); + $request->params = array('controller' => 'posts', 'action' => 'view', 'plugin' => 'blogs'); + + $this->assertEquals('posts', $request->controller); + $this->assertEquals('view', $request->action); + $this->assertEquals('blogs', $request->plugin); + $this->assertSame($request->banana, null); + } + +/** + * Test isset()/empty() with overloaded properties. + * + * @return void + */ + public function testMagicisset() { + $request = new CakeRequest('some/path'); + $request->params = array( + 'controller' => 'posts', + 'action' => 'view', + 'plugin' => 'blogs', + 'named' => array() + ); + + $this->assertTrue(isset($request->controller)); + $this->assertFalse(isset($request->notthere)); + $this->assertFalse(empty($request->controller)); + $this->assertTrue(empty($request->named)); + } + +/** + * test the array access implementation + * + * @return void + */ + public function testArrayAccess() { + $request = new CakeRequest('some/path'); + $request->params = array('controller' => 'posts', 'action' => 'view', 'plugin' => 'blogs'); + + $this->assertEquals('posts', $request['controller']); + + $request['slug'] = 'speedy-slug'; + $this->assertEquals('speedy-slug', $request->slug); + $this->assertEquals('speedy-slug', $request['slug']); + + $this->assertTrue(isset($request['action'])); + $this->assertFalse(isset($request['wrong-param'])); + + $this->assertTrue(isset($request['plugin'])); + unset($request['plugin']); + $this->assertFalse(isset($request['plugin'])); + $this->assertNull($request['plugin']); + $this->assertNull($request->plugin); + + $request = new CakeRequest('some/path?one=something&two=else'); + $this->assertTrue(isset($request['url']['one'])); + + $request->data = array('Post' => array('title' => 'something')); + $this->assertEquals('something', $request['data']['Post']['title']); + } + +/** + * test adding detectors and having them work. + * + * @return void + */ + public function testAddDetector() { + $request = new CakeRequest('some/path'); + $request->addDetector('compare', array('env' => 'TEST_VAR', 'value' => 'something')); + + $_SERVER['TEST_VAR'] = 'something'; + $this->assertTrue($request->is('compare'), 'Value match failed.'); + + $_SERVER['TEST_VAR'] = 'wrong'; + $this->assertFalse($request->is('compare'), 'Value mis-match failed.'); + + $request->addDetector('compareCamelCase', array('env' => 'TEST_VAR', 'value' => 'foo')); + + $_SERVER['TEST_VAR'] = 'foo'; + $this->assertTrue($request->is('compareCamelCase'), 'Value match failed.'); + + $request->addDetector('banana', array('env' => 'TEST_VAR', 'pattern' => '/^ban.*$/')); + $_SERVER['TEST_VAR'] = 'banana'; + $this->assertTrue($request->isBanana()); + + $_SERVER['TEST_VAR'] = 'wrong value'; + $this->assertFalse($request->isBanana()); + + $request->addDetector('mobile', array('options' => array('Imagination'))); + $_SERVER['HTTP_USER_AGENT'] = 'Imagination land'; + $this->assertTrue($request->isMobile()); + + $_SERVER['HTTP_USER_AGENT'] = 'iPhone 3.0'; + $this->assertTrue($request->isMobile()); + + $request->addDetector('callme', array('env' => 'TEST_VAR', 'callback' => array($this, 'detectCallback'))); + + $request->addDetector('index', array('param' => 'action', 'value' => 'index')); + $request->params['action'] = 'index'; + $this->assertTrue($request->isIndex()); + + $request->params['action'] = 'add'; + $this->assertFalse($request->isIndex()); + + $request->return = true; + $this->assertTrue($request->isCallMe()); + + $request->return = false; + $this->assertFalse($request->isCallMe()); + } + +/** + * helper function for testing callbacks. + * + * @return void + */ + public function detectCallback($request) { + return $request->return == true; + } + +/** + * test getting headers + * + * @return void + */ + public function testHeader() { + $_SERVER['HTTP_HOST'] = 'localhost'; + $_SERVER['HTTP_USER_AGENT'] = 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_4; en-ca) AppleWebKit/534.8+ (KHTML, like Gecko) Version/5.0 Safari/533.16'; + $request = new CakeRequest('/', false); + + $this->assertEquals($_SERVER['HTTP_HOST'], $request->header('host')); + $this->assertEquals($_SERVER['HTTP_USER_AGENT'], $request->header('User-Agent')); + } + +/** + * test accepts() with and without parameters + * + * @return void + */ + public function testAccepts() { + $_SERVER['HTTP_ACCEPT'] = 'text/xml,application/xml;q=0.9,application/xhtml+xml,text/html,text/plain,image/png'; + $request = new CakeRequest('/', false); + + $result = $request->accepts(); + $expected = array( + 'text/xml', 'application/xhtml+xml', 'text/html', 'text/plain', 'image/png', 'application/xml' + ); + $this->assertEquals($expected, $result, 'Content types differ.'); + + $result = $request->accepts('text/html'); + $this->assertTrue($result); + + $result = $request->accepts('image/gif'); + $this->assertFalse($result); + } + +/** + * Test that accept header types are trimmed for comparisons. + * + * @return void + */ + public function testAcceptWithWhitespace() { + $_SERVER['HTTP_ACCEPT'] = 'text/xml , text/html , text/plain,image/png'; + $request = new CakeRequest('/', false); + $result = $request->accepts(); + $expected = array( + 'text/xml', 'text/html', 'text/plain', 'image/png' + ); + $this->assertEquals($expected, $result, 'Content types differ.'); + + $this->assertTrue($request->accepts('text/html')); + } + +/** + * Content types from accepts() should respect the client's q preference values. + * + * @return void + */ + public function testAcceptWithQvalueSorting() { + $_SERVER['HTTP_ACCEPT'] = 'text/html;q=0.8,application/json;q=0.7,application/xml;q=1.0'; + $request = new CakeRequest('/', false); + $result = $request->accepts(); + $expected = array('application/xml', 'text/html', 'application/json'); + $this->assertEquals($expected, $result); + } + +/** + * Test the raw parsing of accept headers into the q value formatting. + * + * @return void + */ + public function testParseAcceptWithQValue() { + $_SERVER['HTTP_ACCEPT'] = 'text/html;q=0.8,application/json;q=0.7,application/xml;q=1.0,image/png'; + $request = new CakeRequest('/', false); + $result = $request->parseAccept(); + $expected = array( + '1.0' => array('application/xml', 'image/png'), + '0.8' => array('text/html'), + '0.7' => array('application/json'), + ); + $this->assertEquals($expected, $result); + } + +/** + * Test parsing accept with a confusing accept value. + * + * @return void + */ + public function testParseAcceptNoQValues() { + $_SERVER['HTTP_ACCEPT'] = 'application/json, text/plain, */*'; + + $request = new CakeRequest('/', false); + $result = $request->parseAccept(); + $expected = array( + '1.0' => array('application/json', 'text/plain', '*/*'), + ); + $this->assertEquals($expected, $result); + } + +/** + * testBaseUrlAndWebrootWithModRewrite method + * + * @return void + */ + public function testBaseUrlAndWebrootWithModRewrite() { + Configure::write('App.baseUrl', false); + + $_SERVER['DOCUMENT_ROOT'] = '/cake/repo/branches'; + $_SERVER['PHP_SELF'] = '/1.2.x.x/app/webroot/index.php'; + $_SERVER['PATH_INFO'] = '/posts/view/1'; + + $request = new CakeRequest(); + $this->assertEquals('/1.2.x.x', $request->base); + $this->assertEquals('/1.2.x.x/', $request->webroot); + $this->assertEquals('posts/view/1', $request->url); + + $_SERVER['DOCUMENT_ROOT'] = '/cake/repo/branches/1.2.x.x/app/webroot'; + $_SERVER['PHP_SELF'] = '/index.php'; + $_SERVER['PATH_INFO'] = '/posts/add'; + $request = new CakeRequest(); + + $this->assertEquals('', $request->base); + $this->assertEquals('/', $request->webroot); + $this->assertEquals('posts/add', $request->url); + + $_SERVER['DOCUMENT_ROOT'] = '/cake/repo/branches/1.2.x.x/test/'; + $_SERVER['PHP_SELF'] = '/webroot/index.php'; + $request = new CakeRequest(); + + $this->assertEquals('', $request->base); + $this->assertEquals('/', $request->webroot); + + $_SERVER['DOCUMENT_ROOT'] = '/some/apps/where'; + $_SERVER['PHP_SELF'] = '/app/webroot/index.php'; + $request = new CakeRequest(); + + $this->assertEquals('', $request->base); + $this->assertEquals('/', $request->webroot); + + Configure::write('App.dir', 'auth'); + + $_SERVER['DOCUMENT_ROOT'] = '/cake/repo/branches'; + $_SERVER['PHP_SELF'] = '/demos/auth/webroot/index.php'; + + $request = new CakeRequest(); + + $this->assertEquals('/demos/auth', $request->base); + $this->assertEquals('/demos/auth/', $request->webroot); + + Configure::write('App.dir', 'code'); + + $_SERVER['DOCUMENT_ROOT'] = '/Library/WebServer/Documents'; + $_SERVER['PHP_SELF'] = '/clients/PewterReport/code/webroot/index.php'; + $request = new CakeRequest(); + + $this->assertEquals('/clients/PewterReport/code', $request->base); + $this->assertEquals('/clients/PewterReport/code/', $request->webroot); + } + +/** + * testBaseUrlwithModRewriteAlias method + * + * @return void + */ + public function testBaseUrlwithModRewriteAlias() { + $_SERVER['DOCUMENT_ROOT'] = '/home/aplusnur/public_html'; + $_SERVER['PHP_SELF'] = '/control/index.php'; + + Configure::write('App.base', '/control'); + + $request = new CakeRequest(); + + $this->assertEquals('/control', $request->base); + $this->assertEquals('/control/', $request->webroot); + + Configure::write('App.base', false); + Configure::write('App.dir', 'affiliate'); + Configure::write('App.webroot', 'newaffiliate'); + + $_SERVER['DOCUMENT_ROOT'] = '/var/www/abtravaff/html'; + $_SERVER['PHP_SELF'] = '/newaffiliate/index.php'; + $request = new CakeRequest(); + + $this->assertEquals('/newaffiliate', $request->base); + $this->assertEquals('/newaffiliate/', $request->webroot); + } + +/** + * test base, webroot, and url parsing when there is no url rewriting + * + * @return void + */ + public function testBaseUrlWithNoModRewrite() { + $_SERVER['DOCUMENT_ROOT'] = '/Users/markstory/Sites'; + $_SERVER['SCRIPT_FILENAME'] = '/Users/markstory/Sites/cake/index.php'; + $_SERVER['PHP_SELF'] = '/cake/index.php/posts/index'; + $_SERVER['REQUEST_URI'] = '/cake/index.php/posts/index'; + + Configure::write('App', array( + 'dir' => APP_DIR, + 'webroot' => WEBROOT_DIR, + 'base' => false, + 'baseUrl' => '/cake/index.php' + )); + + $request = new CakeRequest(); + $this->assertEquals('/cake/index.php', $request->base); + $this->assertEquals('/cake/app/webroot/', $request->webroot); + $this->assertEquals('posts/index', $request->url); + } + +/** + * testBaseUrlAndWebrootWithBaseUrl method + * + * @return void + */ + public function testBaseUrlAndWebrootWithBaseUrl() { + Configure::write('App.dir', 'app'); + Configure::write('App.baseUrl', '/app/webroot/index.php'); + + $request = new CakeRequest(); + $this->assertEquals('/app/webroot/index.php', $request->base); + $this->assertEquals('/app/webroot/', $request->webroot); + + Configure::write('App.baseUrl', '/app/webroot/test.php'); + $request = new CakeRequest(); + $this->assertEquals('/app/webroot/test.php', $request->base); + $this->assertEquals('/app/webroot/', $request->webroot); + + Configure::write('App.baseUrl', '/app/index.php'); + $request = new CakeRequest(); + $this->assertEquals('/app/index.php', $request->base); + $this->assertEquals('/app/webroot/', $request->webroot); + + Configure::write('App.baseUrl', '/CakeBB/app/webroot/index.php'); + $request = new CakeRequest(); + $this->assertEquals('/CakeBB/app/webroot/index.php', $request->base); + $this->assertEquals('/CakeBB/app/webroot/', $request->webroot); + + Configure::write('App.baseUrl', '/CakeBB/app/index.php'); + $request = new CakeRequest(); + + $this->assertEquals('/CakeBB/app/index.php', $request->base); + $this->assertEquals('/CakeBB/app/webroot/', $request->webroot); + + Configure::write('App.baseUrl', '/CakeBB/index.php'); + $request = new CakeRequest(); + + $this->assertEquals('/CakeBB/index.php', $request->base); + $this->assertEquals('/CakeBB/app/webroot/', $request->webroot); + + Configure::write('App.baseUrl', '/dbhauser/index.php'); + $_SERVER['DOCUMENT_ROOT'] = '/kunden/homepages/4/d181710652/htdocs/joomla'; + $_SERVER['SCRIPT_FILENAME'] = '/kunden/homepages/4/d181710652/htdocs/joomla/dbhauser/index.php'; + $request = new CakeRequest(); + + $this->assertEquals('/dbhauser/index.php', $request->base); + $this->assertEquals('/dbhauser/app/webroot/', $request->webroot); + } + +/** + * test baseUrl with no rewrite and using the top level index.php. + * + * @return void + */ + public function testBaseUrlNoRewriteTopLevelIndex() { + Configure::write('App.baseUrl', '/index.php'); + $_SERVER['DOCUMENT_ROOT'] = '/Users/markstory/Sites/cake_dev'; + $_SERVER['SCRIPT_FILENAME'] = '/Users/markstory/Sites/cake_dev/index.php'; + + $request = new CakeRequest(); + $this->assertEquals('/index.php', $request->base); + $this->assertEquals('/app/webroot/', $request->webroot); + } + +/** + * Check that a sub-directory containing app|webroot doesn't get mishandled when re-writing is off. + * + * @return void + */ + public function testBaseUrlWithAppAndWebrootInDirname() { + Configure::write('App.baseUrl', '/approval/index.php'); + $_SERVER['DOCUMENT_ROOT'] = '/Users/markstory/Sites/'; + $_SERVER['SCRIPT_FILENAME'] = '/Users/markstory/Sites/approval/index.php'; + + $request = new CakeRequest(); + $this->assertEquals('/approval/index.php', $request->base); + $this->assertEquals('/approval/app/webroot/', $request->webroot); + + Configure::write('App.baseUrl', '/webrootable/index.php'); + $_SERVER['DOCUMENT_ROOT'] = '/Users/markstory/Sites/'; + $_SERVER['SCRIPT_FILENAME'] = '/Users/markstory/Sites/webrootable/index.php'; + + $request = new CakeRequest(); + $this->assertEquals('/webrootable/index.php', $request->base); + $this->assertEquals('/webrootable/app/webroot/', $request->webroot); + } + +/** + * test baseUrl with no rewrite, and using the app/webroot/index.php file as is normal with virtual hosts. + * + * @return void + */ + public function testBaseUrlNoRewriteWebrootIndex() { + Configure::write('App.baseUrl', '/index.php'); + $_SERVER['DOCUMENT_ROOT'] = '/Users/markstory/Sites/cake_dev/app/webroot'; + $_SERVER['SCRIPT_FILENAME'] = '/Users/markstory/Sites/cake_dev/app/webroot/index.php'; + + $request = new CakeRequest(); + $this->assertEquals('/index.php', $request->base); + $this->assertEquals('/', $request->webroot); + } + +/** + * Test that a request with a . in the main GET parameter is filtered out. + * PHP changes GET parameter keys containing dots to _. + * + * @return void + */ + public function testGetParamsWithDot() { + $_GET = array(); + $_GET['/posts/index/add_add'] = ''; + $_SERVER['PHP_SELF'] = '/cake_dev/app/webroot/index.php'; + $_SERVER['REQUEST_URI'] = '/cake_dev/posts/index/add.add'; + + $request = new CakeRequest(); + $this->assertEquals(array(), $request->query); + } + +/** + * Test that a request with urlencoded bits in the main GET parameter are filtered out. + * + * @return void + */ + public function testGetParamWithUrlencodedElement() { + $_GET = array(); + $_GET['/posts/add/∂∂'] = ''; + $_SERVER['PHP_SELF'] = '/cake_dev/app/webroot/index.php'; + $_SERVER['REQUEST_URI'] = '/cake_dev/posts/add/%E2%88%82%E2%88%82'; + + $request = new CakeRequest(); + $this->assertEquals(array(), $request->query); + } + +/** + * generator for environment configurations + * + * @return void + */ + public static function environmentGenerator() { + return array( + array( + 'IIS - No rewrite base path', + array( + 'App' => array( + 'base' => false, + 'baseUrl' => '/index.php', + 'dir' => 'app', + 'webroot' => 'webroot' + ), + 'SERVER' => array( + 'SCRIPT_NAME' => '/index.php', + 'PATH_TRANSLATED' => 'C:\\Inetpub\\wwwroot', + 'QUERY_STRING' => '', + 'REQUEST_URI' => '/index.php', + 'URL' => '/index.php', + 'SCRIPT_FILENAME' => 'C:\\Inetpub\\wwwroot\\index.php', + 'ORIG_PATH_INFO' => '/index.php', + 'PATH_INFO' => '', + 'ORIG_PATH_TRANSLATED' => 'C:\\Inetpub\\wwwroot\\index.php', + 'DOCUMENT_ROOT' => 'C:\\Inetpub\\wwwroot', + 'PHP_SELF' => '/index.php', + ), + ), + array( + 'base' => '/index.php', + 'webroot' => '/app/webroot/', + 'url' => '' + ), + ), + array( + 'IIS - No rewrite with path, no PHP_SELF', + array( + 'App' => array( + 'base' => false, + 'baseUrl' => '/index.php?', + 'dir' => 'app', + 'webroot' => 'webroot' + ), + 'SERVER' => array( + 'QUERY_STRING' => '/posts/add', + 'REQUEST_URI' => '/index.php?/posts/add', + 'PHP_SELF' => '', + 'URL' => '/index.php?/posts/add', + 'DOCUMENT_ROOT' => 'C:\\Inetpub\\wwwroot', + 'argv' => array('/posts/add'), + 'argc' => 1 + ), + ), + array( + 'url' => 'posts/add', + 'base' => '/index.php?', + 'webroot' => '/app/webroot/' + ) + ), + array( + 'IIS - No rewrite sub dir 2', + array( + 'App' => array( + 'base' => false, + 'baseUrl' => '/site/index.php', + 'dir' => 'app', + 'webroot' => 'webroot', + ), + 'SERVER' => array( + 'SCRIPT_NAME' => '/site/index.php', + 'PATH_TRANSLATED' => 'C:\\Inetpub\\wwwroot', + 'QUERY_STRING' => '', + 'REQUEST_URI' => '/site/index.php', + 'URL' => '/site/index.php', + 'SCRIPT_FILENAME' => 'C:\\Inetpub\\wwwroot\\site\\index.php', + 'DOCUMENT_ROOT' => 'C:\\Inetpub\\wwwroot', + 'PHP_SELF' => '/site/index.php', + 'argv' => array(), + 'argc' => 0 + ), + ), + array( + 'url' => '', + 'base' => '/site/index.php', + 'webroot' => '/site/app/webroot/' + ), + ), + array( + 'IIS - No rewrite sub dir 2 with path', + array( + 'App' => array( + 'base' => false, + 'baseUrl' => '/site/index.php', + 'dir' => 'app', + 'webroot' => 'webroot' + ), + 'GET' => array('/posts/add' => ''), + 'SERVER' => array( + 'SCRIPT_NAME' => '/site/index.php', + 'PATH_TRANSLATED' => 'C:\\Inetpub\\wwwroot', + 'QUERY_STRING' => '/posts/add', + 'REQUEST_URI' => '/site/index.php/posts/add', + 'URL' => '/site/index.php/posts/add', + 'ORIG_PATH_TRANSLATED' => 'C:\\Inetpub\\wwwroot\\site\\index.php', + 'DOCUMENT_ROOT' => 'C:\\Inetpub\\wwwroot', + 'PHP_SELF' => '/site/index.php/posts/add', + 'argv' => array('/posts/add'), + 'argc' => 1 + ), + ), + array( + 'url' => 'posts/add', + 'base' => '/site/index.php', + 'webroot' => '/site/app/webroot/' + ) + ), + array( + 'Apache - No rewrite, document root set to webroot, requesting path', + array( + 'App' => array( + 'base' => false, + 'baseUrl' => '/index.php', + 'dir' => 'app', + 'webroot' => 'webroot' + ), + 'SERVER' => array( + 'DOCUMENT_ROOT' => '/Library/WebServer/Documents/site/app/webroot', + 'SCRIPT_FILENAME' => '/Library/WebServer/Documents/site/app/webroot/index.php', + 'QUERY_STRING' => '', + 'REQUEST_URI' => '/index.php/posts/index', + 'SCRIPT_NAME' => '/index.php', + 'PATH_INFO' => '/posts/index', + 'PHP_SELF' => '/index.php/posts/index', + ), + ), + array( + 'url' => 'posts/index', + 'base' => '/index.php', + 'webroot' => '/' + ), + ), + array( + 'Apache - No rewrite, document root set to webroot, requesting root', + array( + 'App' => array( + 'base' => false, + 'baseUrl' => '/index.php', + 'dir' => 'app', + 'webroot' => 'webroot' + ), + 'SERVER' => array( + 'DOCUMENT_ROOT' => '/Library/WebServer/Documents/site/app/webroot', + 'SCRIPT_FILENAME' => '/Library/WebServer/Documents/site/app/webroot/index.php', + 'QUERY_STRING' => '', + 'REQUEST_URI' => '/index.php', + 'SCRIPT_NAME' => '/index.php', + 'PATH_INFO' => '', + 'PHP_SELF' => '/index.php', + ), + ), + array( + 'url' => '', + 'base' => '/index.php', + 'webroot' => '/' + ), + ), + array( + 'Apache - No rewrite, document root set above top level cake dir, requesting path', + array( + 'App' => array( + 'base' => false, + 'baseUrl' => '/site/index.php', + 'dir' => 'app', + 'webroot' => 'webroot' + ), + 'SERVER' => array( + 'SERVER_NAME' => 'localhost', + 'DOCUMENT_ROOT' => '/Library/WebServer/Documents', + 'SCRIPT_FILENAME' => '/Library/WebServer/Documents/site/index.php', + 'REQUEST_URI' => '/site/index.php/posts/index', + 'SCRIPT_NAME' => '/site/index.php', + 'PATH_INFO' => '/posts/index', + 'PHP_SELF' => '/site/index.php/posts/index', + ), + ), + array( + 'url' => 'posts/index', + 'base' => '/site/index.php', + 'webroot' => '/site/app/webroot/', + ), + ), + array( + 'Apache - No rewrite, document root set above top level cake dir, request root, no PATH_INFO', + array( + 'App' => array( + 'base' => false, + 'baseUrl' => '/site/index.php', + 'dir' => 'app', + 'webroot' => 'webroot' + ), + 'SERVER' => array( + 'SERVER_NAME' => 'localhost', + 'DOCUMENT_ROOT' => '/Library/WebServer/Documents', + 'SCRIPT_FILENAME' => '/Library/WebServer/Documents/site/index.php', + 'REQUEST_URI' => '/site/index.php/', + 'SCRIPT_NAME' => '/site/index.php', + 'PHP_SELF' => '/site/index.php/', + ), + ), + array( + 'url' => '', + 'base' => '/site/index.php', + 'webroot' => '/site/app/webroot/', + ), + ), + array( + 'Apache - No rewrite, document root set above top level cake dir, request path, with GET', + array( + 'App' => array( + 'base' => false, + 'baseUrl' => '/site/index.php', + 'dir' => 'app', + 'webroot' => 'webroot' + ), + 'GET' => array('a' => 'b', 'c' => 'd'), + 'SERVER' => array( + 'SERVER_NAME' => 'localhost', + 'DOCUMENT_ROOT' => '/Library/WebServer/Documents', + 'SCRIPT_FILENAME' => '/Library/WebServer/Documents/site/index.php', + 'REQUEST_URI' => '/site/index.php/posts/index?a=b&c=d', + 'SCRIPT_NAME' => '/site/index.php', + 'PATH_INFO' => '/posts/index', + 'PHP_SELF' => '/site/index.php/posts/index', + 'QUERY_STRING' => 'a=b&c=d' + ), + ), + array( + 'urlParams' => array('a' => 'b', 'c' => 'd'), + 'url' => 'posts/index', + 'base' => '/site/index.php', + 'webroot' => '/site/app/webroot/', + ), + ), + array( + 'Apache - w/rewrite, document root set above top level cake dir, request root, no PATH_INFO', + array( + 'App' => array( + 'base' => false, + 'baseUrl' => false, + 'dir' => 'app', + 'webroot' => 'webroot' + ), + 'SERVER' => array( + 'SERVER_NAME' => 'localhost', + 'DOCUMENT_ROOT' => '/Library/WebServer/Documents', + 'SCRIPT_FILENAME' => '/Library/WebServer/Documents/site/index.php', + 'REQUEST_URI' => '/site/', + 'SCRIPT_NAME' => '/site/app/webroot/index.php', + 'PHP_SELF' => '/site/app/webroot/index.php', + ), + ), + array( + 'url' => '', + 'base' => '/site', + 'webroot' => '/site/', + ), + ), + array( + 'Apache - w/rewrite, document root above top level cake dir, request root, no PATH_INFO/REQUEST_URI', + array( + 'App' => array( + 'base' => false, + 'baseUrl' => false, + 'dir' => 'app', + 'webroot' => 'webroot' + ), + 'SERVER' => array( + 'SERVER_NAME' => 'localhost', + 'DOCUMENT_ROOT' => '/Library/WebServer/Documents', + 'SCRIPT_FILENAME' => '/Library/WebServer/Documents/site/index.php', + 'SCRIPT_NAME' => '/site/app/webroot/index.php', + 'PHP_SELF' => '/site/app/webroot/index.php', + 'PATH_INFO' => null, + 'REQUEST_URI' => null, + ), + ), + array( + 'url' => '', + 'base' => '/site', + 'webroot' => '/site/', + ), + ), + array( + 'Apache - w/rewrite, document root set to webroot, request root, no PATH_INFO/REQUEST_URI', + array( + 'App' => array( + 'base' => false, + 'baseUrl' => false, + 'dir' => 'app', + 'webroot' => 'webroot' + ), + 'SERVER' => array( + 'SERVER_NAME' => 'localhost', + 'DOCUMENT_ROOT' => '/Library/WebServer/Documents/site/app/webroot', + 'SCRIPT_FILENAME' => '/Library/WebServer/Documents/site/app/webroot/index.php', + 'SCRIPT_NAME' => '/index.php', + 'PHP_SELF' => '/index.php', + 'PATH_INFO' => null, + 'REQUEST_URI' => null, + ), + ), + array( + 'url' => '', + 'base' => '', + 'webroot' => '/', + ), + ), + array( + 'Nginx - w/rewrite, document root set to webroot, request root, no PATH_INFO', + array( + 'App' => array( + 'base' => false, + 'baseUrl' => false, + 'dir' => 'app', + 'webroot' => 'webroot' + ), + 'GET' => array('/posts/add' => ''), + 'SERVER' => array( + 'SERVER_NAME' => 'localhost', + 'DOCUMENT_ROOT' => '/Library/WebServer/Documents/site/app/webroot', + 'SCRIPT_FILENAME' => '/Library/WebServer/Documents/site/app/webroot/index.php', + 'SCRIPT_NAME' => '/index.php', + 'QUERY_STRING' => '/posts/add&', + 'PHP_SELF' => '/index.php', + 'PATH_INFO' => null, + 'REQUEST_URI' => '/posts/add', + ), + ), + array( + 'url' => 'posts/add', + 'base' => '', + 'webroot' => '/', + 'urlParams' => array() + ), + ), + ); + } + +/** + * testEnvironmentDetection method + * + * @dataProvider environmentGenerator + * @return void + */ + public function testEnvironmentDetection($name, $env, $expected) { + $_GET = array(); + $this->__loadEnvironment($env); + + $request = new CakeRequest(); + $this->assertEquals($expected['url'], $request->url, "url error"); + $this->assertEquals($expected['base'], $request->base, "base error"); + $this->assertEquals($expected['webroot'], $request->webroot, "webroot error"); + if (isset($expected['urlParams'])) { + $this->assertEquals($expected['urlParams'], $request->query, "GET param mismatch"); + } + } + +/** + * test the data() method reading + * + * @return void + */ + public function testDataReading() { + $_POST['data'] = array( + 'Model' => array( + 'field' => 'value' + ) + ); + $request = new CakeRequest('posts/index'); + $result = $request->data('Model'); + $this->assertEquals($_POST['data']['Model'], $result); + + $result = $request->data('Model.imaginary'); + $this->assertNull($result); + } + +/** + * test writing with data() + * + * @return void + */ + public function testDataWriting() { + $_POST['data'] = array( + 'Model' => array( + 'field' => 'value' + ) + ); + $request = new CakeRequest('posts/index'); + $result = $request->data('Model.new_value', 'new value'); + $this->assertSame($result, $request, 'Return was not $this'); + + $this->assertEquals('new value', $request->data['Model']['new_value']); + + $request->data('Post.title', 'New post')->data('Comment.1.author', 'Mark'); + $this->assertEquals('New post', $request->data['Post']['title']); + $this->assertEquals('Mark', $request->data['Comment']['1']['author']); + } + +/** + * test writing falsey values. + * + * @return void + */ + public function testDataWritingFalsey() { + $request = new CakeRequest('posts/index'); + + $request->data('Post.null', null); + $this->assertNull($request->data['Post']['null']); + + $request->data('Post.false', false); + $this->assertFalse($request->data['Post']['false']); + + $request->data('Post.zero', 0); + $this->assertSame(0, $request->data['Post']['zero']); + + $request->data('Post.empty', ''); + $this->assertSame('', $request->data['Post']['empty']); + } + +/** + * test accept language + * + * @return void + */ + public function testAcceptLanguage() { + $_SERVER['HTTP_ACCEPT_LANGUAGE'] = 'inexistent,en-ca'; + $result = CakeRequest::acceptLanguage(); + $this->assertEquals(array('inexistent', 'en-ca'), $result, 'Languages do not match'); + + $_SERVER['HTTP_ACCEPT_LANGUAGE'] = 'es_mx;en_ca'; + $result = CakeRequest::acceptLanguage(); + $this->assertEquals(array('es-mx', 'en-ca'), $result, 'Languages do not match'); + + $result = CakeRequest::acceptLanguage('en-ca'); + $this->assertTrue($result); + + $result = CakeRequest::acceptLanguage('en-us'); + $this->assertFalse($result); + } + +/** + * test the here() method + * + * @return void + */ + public function testHere() { + Configure::write('App.base', '/base_path'); + $_GET = array('test' => 'value'); + $request = new CakeRequest('/posts/add/1/name:value'); + + $result = $request->here(); + $this->assertEquals('/base_path/posts/add/1/name:value?test=value', $result); + + $result = $request->here(false); + $this->assertEquals('/posts/add/1/name:value?test=value', $result); + + $request = new CakeRequest('/posts/base_path/1/name:value'); + $result = $request->here(); + $this->assertEquals('/base_path/posts/base_path/1/name:value?test=value', $result); + + $result = $request->here(false); + $this->assertEquals('/posts/base_path/1/name:value?test=value', $result); + } + +/** + * Test the input() method. + * + * @return void + */ + public function testInput() { + $request = $this->getMock('CakeRequest', array('_readInput')); + $request->expects($this->once())->method('_readInput') + ->will($this->returnValue('I came from stdin')); + + $result = $request->input(); + $this->assertEquals('I came from stdin', $result); + } + +/** + * Test input() decoding. + * + * @return void + */ + public function testInputDecode() { + $request = $this->getMock('CakeRequest', array('_readInput')); + $request->expects($this->once())->method('_readInput') + ->will($this->returnValue('{"name":"value"}')); + + $result = $request->input('json_decode'); + $this->assertEquals(array('name' => 'value'), (array)$result); + } + +/** + * Test input() decoding with additional arguments. + * + * @return void + */ + public function testInputDecodeExtraParams() { + $xml = << + + Test + +XML; + + $request = $this->getMock('CakeRequest', array('_readInput')); + $request->expects($this->once())->method('_readInput') + ->will($this->returnValue($xml)); + + $result = $request->input('Xml::build', array('return' => 'domdocument')); + $this->assertInstanceOf('DOMDocument', $result); + $this->assertEquals( + 'Test', + $result->getElementsByTagName('title')->item(0)->childNodes->item(0)->wholeText + ); + } + +/** + * Test is('requested') and isRequested() + * + * @return void + */ + public function testIsRequested() { + $request = new CakeRequest('/posts/index'); + $request->addParams(array( + 'controller' => 'posts', + 'action' => 'index', + 'plugin' => null, + 'requested' => 1 + )); + $this->assertTrue($request->is('requested')); + $this->assertTrue($request->isRequested()); + + $request = new CakeRequest('/posts/index'); + $request->addParams(array( + 'controller' => 'posts', + 'action' => 'index', + 'plugin' => null, + )); + $this->assertFalse($request->is('requested')); + $this->assertFalse($request->isRequested()); + } + +/** + * loadEnvironment method + * + * @param array $env + * @return void + */ + protected function __loadEnvironment($env) { + if (isset($env['App'])) { + Configure::write('App', $env['App']); + } + + if (isset($env['GET'])) { + foreach ($env['GET'] as $key => $val) { + $_GET[$key] = $val; + } + } + + if (isset($env['POST'])) { + foreach ($env['POST'] as $key => $val) { + $_POST[$key] = $val; + } + } + + if (isset($env['SERVER'])) { + foreach ($env['SERVER'] as $key => $val) { + $_SERVER[$key] = $val; + } + } + } + +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Network/CakeResponseTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Network/CakeResponseTest.php new file mode 100644 index 0000000..9f601b1 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Network/CakeResponseTest.php @@ -0,0 +1,1009 @@ +assertNull($response->body()); + $this->assertEquals('UTF-8', $response->charset()); + $this->assertEquals('text/html', $response->type()); + $this->assertEquals(200, $response->statusCode()); + + $options = array( + 'body' => 'This is the body', + 'charset' => 'my-custom-charset', + 'type' => 'mp3', + 'status' => '203' + ); + $response = new CakeResponse($options); + $this->assertEquals('This is the body', $response->body()); + $this->assertEquals('my-custom-charset', $response->charset()); + $this->assertEquals('audio/mpeg', $response->type()); + $this->assertEquals(203, $response->statusCode()); + } + +/** + * Tests the body method + * + */ + public function testBody() { + $response = new CakeResponse(); + $this->assertNull($response->body()); + $response->body('Response body'); + $this->assertEquals('Response body', $response->body()); + $this->assertEquals('Changed Body', $response->body('Changed Body')); + } + +/** + * Tests the charset method + * + */ + public function testCharset() { + $response = new CakeResponse(); + $this->assertEquals('UTF-8', $response->charset()); + $response->charset('iso-8859-1'); + $this->assertEquals('iso-8859-1', $response->charset()); + $this->assertEquals('UTF-16', $response->charset('UTF-16')); + } + +/** + * Tests the statusCode method + * + * @expectedException CakeException + */ + public function testStatusCode() { + $response = new CakeResponse(); + $this->assertEquals(200, $response->statusCode()); + $response->statusCode(404); + $this->assertEquals(404, $response->statusCode()); + $this->assertEquals(500, $response->statusCode(500)); + + //Throws exception + $response->statusCode(1001); + } + +/** + * Tests the type method + * + */ + public function testType() { + $response = new CakeResponse(); + $this->assertEquals('text/html', $response->type()); + $response->type('pdf'); + $this->assertEquals('application/pdf', $response->type()); + $this->assertEquals('application/crazy-mime', $response->type('application/crazy-mime')); + $this->assertEquals('application/json', $response->type('json')); + $this->assertEquals('text/vnd.wap.wml', $response->type('wap')); + $this->assertEquals('application/vnd.wap.xhtml+xml', $response->type('xhtml-mobile')); + $this->assertEquals('text/csv', $response->type('csv')); + + $response->type(array('keynote' => 'application/keynote', 'bat' => 'application/bat')); + $this->assertEquals('application/keynote', $response->type('keynote')); + $this->assertEquals('application/bat', $response->type('bat')); + + $this->assertFalse($response->type('wackytype')); + } + +/** + * Tests the header method + * + */ + public function testHeader() { + $response = new CakeResponse(); + $headers = array(); + $this->assertEquals($response->header(), $headers); + + $response->header('Location', 'http://example.com'); + $headers += array('Location' => 'http://example.com'); + $this->assertEquals($response->header(), $headers); + + //Headers with the same name are overwritten + $response->header('Location', 'http://example2.com'); + $headers = array('Location' => 'http://example2.com'); + $this->assertEquals($response->header(), $headers); + + $response->header(array('WWW-Authenticate' => 'Negotiate')); + $headers += array('WWW-Authenticate' => 'Negotiate'); + $this->assertEquals($response->header(), $headers); + + $response->header(array('WWW-Authenticate' => 'Not-Negotiate')); + $headers['WWW-Authenticate'] = 'Not-Negotiate'; + $this->assertEquals($response->header(), $headers); + + $response->header(array('Age' => 12, 'Allow' => 'GET, HEAD')); + $headers += array('Age' => 12, 'Allow' => 'GET, HEAD'); + $this->assertEquals($response->header(), $headers); + + // String headers are allowed + $response->header('Content-Language: da'); + $headers += array('Content-Language' => 'da'); + $this->assertEquals($response->header(), $headers); + + $response->header('Content-Language: da'); + $headers += array('Content-Language' => 'da'); + $this->assertEquals($response->header(), $headers); + + $response->header(array('Content-Encoding: gzip', 'Vary: *', 'Pragma' => 'no-cache')); + $headers += array('Content-Encoding' => 'gzip', 'Vary' => '*', 'Pragma' => 'no-cache'); + $this->assertEquals($response->header(), $headers); + } + +/** + * Tests the send method + * + */ + public function testSend() { + $response = $this->getMock('CakeResponse', array('_sendHeader', '_sendContent', '_setCookies')); + $response->header(array( + 'Content-Language' => 'es', + 'WWW-Authenticate' => 'Negotiate' + )); + $response->body('the response body'); + $response->expects($this->once())->method('_sendContent')->with('the response body'); + $response->expects($this->at(0))->method('_setCookies'); + $response->expects($this->at(1)) + ->method('_sendHeader')->with('HTTP/1.1 200 OK'); + $response->expects($this->at(2)) + ->method('_sendHeader')->with('Content-Language', 'es'); + $response->expects($this->at(3)) + ->method('_sendHeader')->with('WWW-Authenticate', 'Negotiate'); + $response->expects($this->at(4)) + ->method('_sendHeader')->with('Content-Length', 17); + $response->expects($this->at(5)) + ->method('_sendHeader')->with('Content-Type', 'text/html; charset=UTF-8'); + $response->send(); + } + +/** + * Tests the send method and changing the content type + * + */ + public function testSendChangingContentYype() { + $response = $this->getMock('CakeResponse', array('_sendHeader', '_sendContent', '_setCookies')); + $response->type('mp3'); + $response->body('the response body'); + $response->expects($this->once())->method('_sendContent')->with('the response body'); + $response->expects($this->at(0))->method('_setCookies'); + $response->expects($this->at(1)) + ->method('_sendHeader')->with('HTTP/1.1 200 OK'); + $response->expects($this->at(2)) + ->method('_sendHeader')->with('Content-Length', 17); + $response->expects($this->at(3)) + ->method('_sendHeader')->with('Content-Type', 'audio/mpeg'); + $response->send(); + } + +/** + * Tests the send method and changing the content type + * + */ + public function testSendChangingContentType() { + $response = $this->getMock('CakeResponse', array('_sendHeader', '_sendContent', '_setCookies')); + $response->type('mp3'); + $response->body('the response body'); + $response->expects($this->once())->method('_sendContent')->with('the response body'); + $response->expects($this->at(0))->method('_setCookies'); + $response->expects($this->at(1)) + ->method('_sendHeader')->with('HTTP/1.1 200 OK'); + $response->expects($this->at(2)) + ->method('_sendHeader')->with('Content-Length', 17); + $response->expects($this->at(3)) + ->method('_sendHeader')->with('Content-Type', 'audio/mpeg'); + $response->send(); + } + +/** + * Tests the send method and changing the content type + * + */ + public function testSendWithLocation() { + $response = $this->getMock('CakeResponse', array('_sendHeader', '_sendContent', '_setCookies')); + $response->header('Location', 'http://www.example.com'); + $response->expects($this->at(0))->method('_setCookies'); + $response->expects($this->at(1)) + ->method('_sendHeader')->with('HTTP/1.1 302 Found'); + $response->expects($this->at(2)) + ->method('_sendHeader')->with('Location', 'http://www.example.com'); + $response->expects($this->at(3)) + ->method('_sendHeader')->with('Content-Type', 'text/html; charset=UTF-8'); + $response->send(); + } + +/** + * Tests the disableCache method + * + */ + public function testDisableCache() { + $response = new CakeResponse(); + $expected = array( + 'Expires' => 'Mon, 26 Jul 1997 05:00:00 GMT', + 'Last-Modified' => gmdate("D, d M Y H:i:s") . " GMT", + 'Cache-Control' => 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0' + ); + $response->disableCache(); + $this->assertEquals($expected, $response->header()); + } + +/** + * Tests the cache method + * + */ + public function testCache() { + $response = new CakeResponse(); + $since = time(); + $time = new DateTime('+1 day', new DateTimeZone('UTC')); + $response->expires('+1 day'); + $expected = array( + 'Date' => gmdate("D, j M Y G:i:s ", $since) . 'GMT', + 'Last-Modified' => gmdate("D, j M Y H:i:s ", $since) . 'GMT', + 'Expires' => $time->format('D, j M Y H:i:s') . ' GMT', + 'Cache-Control' => 'public, max-age=' . ($time->format('U') - time()) + ); + $response->cache($since); + $this->assertEquals($expected, $response->header()); + + $response = new CakeResponse(); + $since = time(); + $time = '+5 day'; + $expected = array( + 'Date' => gmdate("D, j M Y G:i:s ", $since) . 'GMT', + 'Last-Modified' => gmdate("D, j M Y H:i:s ", $since) . 'GMT', + 'Expires' => gmdate("D, j M Y H:i:s", strtotime($time)) . " GMT", + 'Cache-Control' => 'public, max-age=' . (strtotime($time) - time()) + ); + $response->cache($since, $time); + $this->assertEquals($expected, $response->header()); + + $response = new CakeResponse(); + $since = time(); + $time = time(); + $expected = array( + 'Date' => gmdate("D, j M Y G:i:s ", $since) . 'GMT', + 'Last-Modified' => gmdate("D, j M Y H:i:s ", $since) . 'GMT', + 'Expires' => gmdate("D, j M Y H:i:s", $time) . " GMT", + 'Cache-Control' => 'public, max-age=0' + ); + $response->cache($since, $time); + $this->assertEquals($expected, $response->header()); + } + +/** + * Tests the compress method + * + * @return void + */ + public function testCompress() { + if (php_sapi_name() !== 'cli') { + $this->markTestSkipped('The response compression can only be tested in cli.'); + } + + $response = new CakeResponse(); + if (ini_get("zlib.output_compression") === '1' || !extension_loaded("zlib")) { + $this->assertFalse($response->compress()); + $this->markTestSkipped('Is not possible to test output compression'); + } + + $_SERVER['HTTP_ACCEPT_ENCODING'] = ''; + $result = $response->compress(); + $this->assertFalse($result); + + $_SERVER['HTTP_ACCEPT_ENCODING'] = 'gzip'; + $result = $response->compress(); + $this->assertTrue($result); + $this->assertTrue(in_array('ob_gzhandler', ob_list_handlers())); + + ob_get_clean(); + } + +/** + * Tests the httpCodes method + * + */ + public function testHttpCodes() { + $response = new CakeResponse(); + $result = $response->httpCodes(); + $this->assertEquals(39, count($result)); + + $result = $response->httpCodes(100); + $expected = array(100 => 'Continue'); + $this->assertEquals($expected, $result); + + $codes = array( + 1337 => 'Undefined Unicorn', + 1729 => 'Hardy-Ramanujan Located' + ); + + $result = $response->httpCodes($codes); + $this->assertTrue($result); + $this->assertEquals(41, count($response->httpCodes())); + + $result = $response->httpCodes(1337); + $expected = array(1337 => 'Undefined Unicorn'); + $this->assertEquals($expected, $result); + + $codes = array(404 => 'Sorry Bro'); + $result = $response->httpCodes($codes); + $this->assertTrue($result); + $this->assertEquals(41, count($response->httpCodes())); + + $result = $response->httpCodes(404); + $expected = array(404 => 'Sorry Bro'); + $this->assertEquals($expected, $result); + } + +/** + * Tests the download method + * + */ + public function testDownload() { + $response = new CakeResponse(); + $expected = array( + 'Content-Disposition' => 'attachment; filename="myfile.mp3"' + ); + $response->download('myfile.mp3'); + $this->assertEquals($expected, $response->header()); + } + +/** + * Tests the mapType method + * + */ + public function testMapType() { + $response = new CakeResponse(); + $this->assertEquals('wav', $response->mapType('audio/x-wav')); + $this->assertEquals('pdf', $response->mapType('application/pdf')); + $this->assertEquals('xml', $response->mapType('text/xml')); + $this->assertEquals('html', $response->mapType('*/*')); + $this->assertEquals('csv', $response->mapType('application/vnd.ms-excel')); + $expected = array('json', 'xhtml', 'css'); + $result = $response->mapType(array('application/json', 'application/xhtml+xml', 'text/css')); + $this->assertEquals($expected, $result); + } + +/** + * Tests the outputCompressed method + * + */ + public function testOutputCompressed() { + $response = new CakeResponse(); + + $_SERVER['HTTP_ACCEPT_ENCODING'] = 'gzip'; + $result = $response->outputCompressed(); + $this->assertFalse($result); + + $_SERVER['HTTP_ACCEPT_ENCODING'] = ''; + $result = $response->outputCompressed(); + $this->assertFalse($result); + + if (!extension_loaded("zlib")) { + $this->markTestSkipped('Skipping further tests for outputCompressed as zlib extension is not loaded'); + } + if (php_sapi_name() !== 'cli') { + $this->markTestSkipped('Testing outputCompressed method with compression enabled done only in cli'); + } + + if (ini_get("zlib.output_compression") !== '1') { + ob_start('ob_gzhandler'); + } + $_SERVER['HTTP_ACCEPT_ENCODING'] = 'gzip'; + $result = $response->outputCompressed(); + $this->assertTrue($result); + + $_SERVER['HTTP_ACCEPT_ENCODING'] = ''; + $result = $response->outputCompressed(); + $this->assertFalse($result); + if (ini_get("zlib.output_compression") !== '1') { + ob_get_clean(); + } + } + +/** + * Tests the send and setting of Content-Length + * + */ + public function testSendContentLength() { + $response = $this->getMock('CakeResponse', array('_sendHeader', '_sendContent')); + $response->body('the response body'); + $response->expects($this->once())->method('_sendContent')->with('the response body'); + $response->expects($this->at(0)) + ->method('_sendHeader')->with('HTTP/1.1 200 OK'); + $response->expects($this->at(2)) + ->method('_sendHeader')->with('Content-Type', 'text/html; charset=UTF-8'); + $response->expects($this->at(1)) + ->method('_sendHeader')->with('Content-Length', strlen('the response body')); + $response->send(); + + $response = $this->getMock('CakeResponse', array('_sendHeader', '_sendContent')); + $body = '長い長い長いSubjectの場合はfoldingするのが正しいんだけどいったいどうなるんだろう?'; + $response->body($body); + $response->expects($this->once())->method('_sendContent')->with($body); + $response->expects($this->at(0)) + ->method('_sendHeader')->with('HTTP/1.1 200 OK'); + $response->expects($this->at(2)) + ->method('_sendHeader')->with('Content-Type', 'text/html; charset=UTF-8'); + $response->expects($this->at(1)) + ->method('_sendHeader')->with('Content-Length', 116); + $response->send(); + + $response = $this->getMock('CakeResponse', array('_sendHeader', '_sendContent', 'outputCompressed')); + $body = '長い長い長いSubjectの場合はfoldingするのが正しいんだけどいったいどうなるんだろう?'; + $response->body($body); + $response->expects($this->once())->method('outputCompressed')->will($this->returnValue(true)); + $response->expects($this->once())->method('_sendContent')->with($body); + $response->expects($this->exactly(2))->method('_sendHeader'); + $response->send(); + + $response = $this->getMock('CakeResponse', array('_sendHeader', '_sendContent', 'outputCompressed')); + $body = 'hwy'; + $response->body($body); + $response->header('Content-Length', 1); + $response->expects($this->never())->method('outputCompressed'); + $response->expects($this->once())->method('_sendContent')->with($body); + $response->expects($this->at(1)) + ->method('_sendHeader')->with('Content-Length', 1); + $response->send(); + + $response = $this->getMock('CakeResponse', array('_sendHeader', '_sendContent')); + $body = 'content'; + $response->statusCode(301); + $response->body($body); + $response->expects($this->once())->method('_sendContent')->with($body); + $response->expects($this->exactly(2))->method('_sendHeader'); + $response->send(); + + ob_start(); + $response = $this->getMock('CakeResponse', array('_sendHeader', '_sendContent')); + $goofyOutput = 'I am goofily sending output in the controller'; + echo $goofyOutput; + $response = $this->getMock('CakeResponse', array('_sendHeader', '_sendContent')); + $body = '長い長い長いSubjectの場合はfoldingするのが正しいんだけどいったいどうなるんだろう?'; + $response->body($body); + $response->expects($this->once())->method('_sendContent')->with($body); + $response->expects($this->at(0)) + ->method('_sendHeader')->with('HTTP/1.1 200 OK'); + $response->expects($this->at(1)) + ->method('_sendHeader')->with('Content-Length', strlen($goofyOutput) + 116); + $response->expects($this->at(2)) + ->method('_sendHeader')->with('Content-Type', 'text/html; charset=UTF-8'); + $response->send(); + ob_end_clean(); + } + +/** + * Tests getting/setting the protocol + * + * @return void + */ + public function testProtocol() { + $response = $this->getMock('CakeResponse', array('_sendHeader', '_sendContent')); + $response->protocol('HTTP/1.0'); + $this->assertEquals('HTTP/1.0', $response->protocol()); + $response->expects($this->at(0)) + ->method('_sendHeader')->with('HTTP/1.0 200 OK'); + $response->send(); + } + +/** + * Tests getting/setting the Content-Length + * + * @return void + */ + public function testLength() { + $response = $this->getMock('CakeResponse', array('_sendHeader', '_sendContent')); + $response->length(100); + $this->assertEquals(100, $response->length()); + $response->expects($this->at(1)) + ->method('_sendHeader')->with('Content-Length', 100); + $response->send(); + + $response = $this->getMock('CakeResponse', array('_sendHeader', '_sendContent')); + $response->length(false); + $this->assertFalse($response->length()); + $response->expects($this->exactly(2)) + ->method('_sendHeader'); + $response->send(); + } + +/** + * Tests that the response body is unset if the status code is 304 or 204 + * + * @return void + */ + public function testUnmodifiedContent() { + $response = $this->getMock('CakeResponse', array('_sendHeader', '_sendContent')); + $response->body('This is a body'); + $response->statusCode(204); + $response->expects($this->once()) + ->method('_sendContent')->with(''); + $response->send(); + $this->assertFalse(array_key_exists('Content-Type', $response->header())); + + $response = $this->getMock('CakeResponse', array('_sendHeader', '_sendContent')); + $response->body('This is a body'); + $response->statusCode(304); + $response->expects($this->once()) + ->method('_sendContent')->with(''); + $response->send(); + + $response = $this->getMock('CakeResponse', array('_sendHeader', '_sendContent')); + $response->body('This is a body'); + $response->statusCode(200); + $response->expects($this->once()) + ->method('_sendContent')->with('This is a body'); + $response->send(); + } + +/** + * Tests setting the expiration date + * + * @return void + */ + public function testExpires() { + $response = $this->getMock('CakeResponse', array('_sendHeader', '_sendContent')); + $now = new DateTime('now', new DateTimeZone('America/Los_Angeles')); + $response->expires($now); + $now->setTimeZone(new DateTimeZone('UTC')); + $this->assertEquals($now->format('D, j M Y H:i:s') . ' GMT', $response->expires()); + $response->expects($this->at(1)) + ->method('_sendHeader')->with('Expires', $now->format('D, j M Y H:i:s') . ' GMT'); + $response->send(); + + $response = $this->getMock('CakeResponse', array('_sendHeader', '_sendContent')); + $now = time(); + $response->expires($now); + $this->assertEquals(gmdate('D, j M Y H:i:s', $now) . ' GMT', $response->expires()); + $response->expects($this->at(1)) + ->method('_sendHeader')->with('Expires', gmdate('D, j M Y H:i:s', $now) . ' GMT'); + $response->send(); + + $response = $this->getMock('CakeResponse', array('_sendHeader', '_sendContent')); + $time = new DateTime('+1 day', new DateTimeZone('UTC')); + $response->expires('+1 day'); + $this->assertEquals($time->format('D, j M Y H:i:s') . ' GMT', $response->expires()); + $response->expects($this->at(1)) + ->method('_sendHeader')->with('Expires', $time->format('D, j M Y H:i:s') . ' GMT'); + $response->send(); + } + +/** + * Tests setting the modification date + * + * @return void + */ + public function testModified() { + $response = $this->getMock('CakeResponse', array('_sendHeader', '_sendContent')); + $now = new DateTime('now', new DateTimeZone('America/Los_Angeles')); + $response->modified($now); + $now->setTimeZone(new DateTimeZone('UTC')); + $this->assertEquals($now->format('D, j M Y H:i:s') . ' GMT', $response->modified()); + $response->expects($this->at(1)) + ->method('_sendHeader')->with('Last-Modified', $now->format('D, j M Y H:i:s') . ' GMT'); + $response->send(); + + $response = $this->getMock('CakeResponse', array('_sendHeader', '_sendContent')); + $now = time(); + $response->modified($now); + $this->assertEquals(gmdate('D, j M Y H:i:s', $now) . ' GMT', $response->modified()); + $response->expects($this->at(1)) + ->method('_sendHeader')->with('Last-Modified', gmdate('D, j M Y H:i:s', $now) . ' GMT'); + $response->send(); + + $response = $this->getMock('CakeResponse', array('_sendHeader', '_sendContent')); + $time = new DateTime('+1 day', new DateTimeZone('UTC')); + $response->modified('+1 day'); + $this->assertEquals($time->format('D, j M Y H:i:s') . ' GMT', $response->modified()); + $response->expects($this->at(1)) + ->method('_sendHeader')->with('Last-Modified', $time->format('D, j M Y H:i:s') . ' GMT'); + $response->send(); + } + +/** + * Tests setting of public/private Cache-Control directives + * + * @return void + */ + public function testSharable() { + $response = $this->getMock('CakeResponse', array('_sendHeader', '_sendContent')); + $this->assertNull($response->sharable()); + $response->sharable(true); + $headers = $response->header(); + $this->assertEquals('public', $headers['Cache-Control']); + $response->expects($this->at(1)) + ->method('_sendHeader')->with('Cache-Control', 'public'); + $response->send(); + + $response = $this->getMock('CakeResponse', array('_sendHeader', '_sendContent')); + $response->sharable(false); + $headers = $response->header(); + $this->assertEquals('private', $headers['Cache-Control']); + $response->expects($this->at(1)) + ->method('_sendHeader')->with('Cache-Control', 'private'); + $response->send(); + + $response = $this->getMock('CakeResponse', array('_sendHeader', '_sendContent')); + $response->sharable(true); + $headers = $response->header(); + $this->assertEquals('public', $headers['Cache-Control']); + $response->sharable(false); + $headers = $response->header(); + $this->assertEquals('private', $headers['Cache-Control']); + $response->expects($this->at(1)) + ->method('_sendHeader')->with('Cache-Control', 'private'); + $response->send(); + $this->assertFalse($response->sharable()); + $response->sharable(true); + $this->assertTrue($response->sharable()); + + $response = new CakeResponse; + $response->sharable(true, 3600); + $headers = $response->header(); + $this->assertEquals('public, s-maxage=3600', $headers['Cache-Control']); + + $response = new CakeResponse; + $response->sharable(false, 3600); + $headers = $response->header(); + $this->assertEquals('private, max-age=3600', $headers['Cache-Control']); + $response->send(); + } + +/** + * Tests setting of max-age Cache-Control directive + * + * @return void + */ + public function testMaxAge() { + $response = $this->getMock('CakeResponse', array('_sendHeader', '_sendContent')); + $this->assertNull($response->maxAge()); + $response->maxAge(3600); + $this->assertEquals(3600, $response->maxAge()); + $headers = $response->header(); + $this->assertEquals('max-age=3600', $headers['Cache-Control']); + $response->expects($this->at(1)) + ->method('_sendHeader')->with('Cache-Control', 'max-age=3600'); + $response->send(); + + $response = $this->getMock('CakeResponse', array('_sendHeader', '_sendContent')); + $response->maxAge(3600); + $response->sharable(false); + $headers = $response->header(); + $this->assertEquals('max-age=3600, private', $headers['Cache-Control']); + $response->expects($this->at(1)) + ->method('_sendHeader')->with('Cache-Control', 'max-age=3600, private'); + $response->send(); + } + +/** + * Tests setting of s-maxage Cache-Control directive + * + * @return void + */ + public function testSharedMaxAge() { + $response = $this->getMock('CakeResponse', array('_sendHeader', '_sendContent')); + $this->assertNull($response->maxAge()); + $response->sharedMaxAge(3600); + $this->assertEquals(3600, $response->sharedMaxAge()); + $headers = $response->header(); + $this->assertEquals('s-maxage=3600', $headers['Cache-Control']); + $response->expects($this->at(1)) + ->method('_sendHeader')->with('Cache-Control', 's-maxage=3600'); + $response->send(); + + $response = $this->getMock('CakeResponse', array('_sendHeader', '_sendContent')); + $response->sharedMaxAge(3600); + $response->sharable(true); + $headers = $response->header(); + $this->assertEquals('s-maxage=3600, public', $headers['Cache-Control']); + $response->expects($this->at(1)) + ->method('_sendHeader')->with('Cache-Control', 's-maxage=3600, public'); + $response->send(); + } + +/** + * Tests setting of must-revalidate Cache-Control directive + * + * @return void + */ + public function testMustRevalidate() { + $response = $this->getMock('CakeResponse', array('_sendHeader', '_sendContent')); + $this->assertFalse($response->mustRevalidate()); + $response->mustRevalidate(true); + $this->assertTrue($response->mustRevalidate()); + $headers = $response->header(); + $this->assertEquals('must-revalidate', $headers['Cache-Control']); + $response->expects($this->at(1)) + ->method('_sendHeader')->with('Cache-Control', 'must-revalidate'); + $response->send(); + $response->mustRevalidate(false); + $this->assertFalse($response->mustRevalidate()); + + $response = $this->getMock('CakeResponse', array('_sendHeader', '_sendContent')); + $response->sharedMaxAge(3600); + $response->mustRevalidate(true); + $headers = $response->header(); + $this->assertEquals('s-maxage=3600, must-revalidate', $headers['Cache-Control']); + $response->expects($this->at(1)) + ->method('_sendHeader')->with('Cache-Control', 's-maxage=3600, must-revalidate'); + $response->send(); + } + +/** + * Tests getting/setting the Vary header + * + * @return void + */ + public function testVary() { + $response = $this->getMock('CakeResponse', array('_sendHeader', '_sendContent')); + $response->vary('Accept-encoding'); + $this->assertEquals(array('Accept-encoding'), $response->vary()); + $response->expects($this->at(1)) + ->method('_sendHeader')->with('Vary', 'Accept-encoding'); + $response->send(); + + $response = $this->getMock('CakeResponse', array('_sendHeader', '_sendContent')); + $response->vary(array('Accept-language', 'Accept-encoding')); + $response->expects($this->at(1)) + ->method('_sendHeader')->with('Vary', 'Accept-language, Accept-encoding'); + $response->send(); + $this->assertEquals(array('Accept-language', 'Accept-encoding'), $response->vary()); + } + +/** + * Tests getting/setting the Etag header + * + * @return void + */ + public function testEtag() { + $response = $this->getMock('CakeResponse', array('_sendHeader', '_sendContent')); + $response->etag('something'); + $this->assertEquals('"something"', $response->etag()); + $response->expects($this->at(1)) + ->method('_sendHeader')->with('Etag', '"something"'); + $response->send(); + + $response = $this->getMock('CakeResponse', array('_sendHeader', '_sendContent')); + $response->etag('something', true); + $this->assertEquals('W/"something"', $response->etag()); + $response->expects($this->at(1)) + ->method('_sendHeader')->with('Etag', 'W/"something"'); + $response->send(); + } + +/** + * Tests that the response is able to be marked as not modified + * + * @return void + */ + public function testNotModified() { + $response = $this->getMock('CakeResponse', array('_sendHeader', '_sendContent')); + $response->body('something'); + $response->statusCode(200); + $response->length(100); + $response->modified('now'); + $response->notModified(); + + $this->assertEmpty($response->header()); + $this->assertEmpty($response->body()); + $this->assertEquals(304, $response->statusCode()); + } + +/** + * Test checkNotModified method + * + * @return void + **/ + public function testCheckNotModifiedByEtagStar() { + $_SERVER['HTTP_IF_NONE_MATCH'] = '*'; + $response = $this->getMock('CakeResponse', array('notModified')); + $response->etag('something'); + $response->expects($this->once())->method('notModified'); + $response->checkNotModified(new CakeRequest); + } + +/** + * Test checkNotModified method + * + * @return void + **/ + public function testCheckNotModifiedByEtagExact() { + $_SERVER['HTTP_IF_NONE_MATCH'] = 'W/"something", "other"'; + $response = $this->getMock('CakeResponse', array('notModified')); + $response->etag('something', true); + $response->expects($this->once())->method('notModified'); + $this->assertTrue($response->checkNotModified(new CakeRequest)); + } + +/** + * Test checkNotModified method + * + * @return void + **/ + public function testCheckNotModifiedByEtagAndTime() { + $_SERVER['HTTP_IF_NONE_MATCH'] = 'W/"something", "other"'; + $_SERVER['HTTP_IF_MODIFIED_SINCE'] = '2012-01-01 00:00:00'; + $response = $this->getMock('CakeResponse', array('notModified')); + $response->etag('something', true); + $response->modified('2012-01-01 00:00:00'); + $response->expects($this->once())->method('notModified'); + $this->assertTrue($response->checkNotModified(new CakeRequest)); + } + +/** + * Test checkNotModified method + * + * @return void + **/ + public function testCheckNotModifiedByEtagAndTimeMismatch() { + $_SERVER['HTTP_IF_NONE_MATCH'] = 'W/"something", "other"'; + $_SERVER['HTTP_IF_MODIFIED_SINCE'] = '2012-01-01 00:00:00'; + $response = $this->getMock('CakeResponse', array('notModified')); + $response->etag('something', true); + $response->modified('2012-01-01 00:00:01'); + $response->expects($this->never())->method('notModified'); + $this->assertFalse($response->checkNotModified(new CakeRequest)); + } + +/** + * Test checkNotModified method + * + * @return void + **/ + public function testCheckNotModifiedByEtagMismatch() { + $_SERVER['HTTP_IF_NONE_MATCH'] = 'W/"something-else", "other"'; + $_SERVER['HTTP_IF_MODIFIED_SINCE'] = '2012-01-01 00:00:00'; + $response = $this->getMock('CakeResponse', array('notModified')); + $response->etag('something', true); + $response->modified('2012-01-01 00:00:00'); + $response->expects($this->never())->method('notModified'); + $this->assertFalse($response->checkNotModified(new CakeRequest)); + } + +/** + * Test checkNotModified method + * + * @return void + **/ + public function testCheckNotModifiedByTime() { + $_SERVER['HTTP_IF_MODIFIED_SINCE'] = '2012-01-01 00:00:00'; + $response = $this->getMock('CakeResponse', array('notModified')); + $response->modified('2012-01-01 00:00:00'); + $response->expects($this->once())->method('notModified'); + $this->assertTrue($response->checkNotModified(new CakeRequest)); + } + +/** + * Test checkNotModified method + * + * @return void + **/ + public function testCheckNotModifiedNoHints() { + $_SERVER['HTTP_IF_NONE_MATCH'] = 'W/"something", "other"'; + $_SERVER['HTTP_IF_MODIFIED_SINCE'] = '2012-01-01 00:00:00'; + $response = $this->getMock('CakeResponse', array('notModified')); + $response->expects($this->never())->method('notModified'); + $this->assertFalse($response->checkNotModified(new CakeRequest)); + } + +/** + * Test cookie setting + * + * @return void + */ + public function testCookieSettings() { + $response = new CakeResponse(); + $cookie = array( + 'name' => 'CakeTestCookie[Testing]' + ); + $response->cookie($cookie); + $expected = array( + 'name' => 'CakeTestCookie[Testing]', + 'value' => '', + 'expire' => 0, + 'path' => '/', + 'domain' => '', + 'secure' => false, + 'httpOnly' => false); + $result = $response->cookie('CakeTestCookie[Testing]'); + $this->assertEquals($expected, $result); + + $cookie = array( + 'name' => 'CakeTestCookie[Testing2]', + 'value' => '[a,b,c]', + 'expire' => 1000, + 'path' => '/test', + 'secure' => true + ); + $response->cookie($cookie); + $expected = array( + 'CakeTestCookie[Testing]' => array( + 'name' => 'CakeTestCookie[Testing]', + 'value' => '', + 'expire' => 0, + 'path' => '/', + 'domain' => '', + 'secure' => false, + 'httpOnly' => false + ), + 'CakeTestCookie[Testing2]' => array( + 'name' => 'CakeTestCookie[Testing2]', + 'value' => '[a,b,c]', + 'expire' => 1000, + 'path' => '/test', + 'domain' => '', + 'secure' => true, + 'httpOnly' => false + ) + ); + + $result = $response->cookie(); + $this->assertEquals($expected, $result); + + $cookie = $expected['CakeTestCookie[Testing]']; + $cookie['value'] = 'test'; + $response->cookie($cookie); + $expected = array( + 'CakeTestCookie[Testing]' => array( + 'name' => 'CakeTestCookie[Testing]', + 'value' => 'test', + 'expire' => 0, + 'path' => '/', + 'domain' => '', + 'secure' => false, + 'httpOnly' => false + ), + 'CakeTestCookie[Testing2]' => array( + 'name' => 'CakeTestCookie[Testing2]', + 'value' => '[a,b,c]', + 'expire' => 1000, + 'path' => '/test', + 'domain' => '', + 'secure' => true, + 'httpOnly' => false + ) + ); + + $result = $response->cookie(); + $this->assertEquals($expected, $result); + } + +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Network/CakeSocketTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Network/CakeSocketTest.php new file mode 100644 index 0000000..abe6fca --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Network/CakeSocketTest.php @@ -0,0 +1,217 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Network + * @since CakePHP(tm) v 1.2.0.4206 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ + +App::uses('CakeSocket', 'Network'); + +/** + * SocketTest class + * + * @package Cake.Test.Case.Network + */ +class CakeSocketTest extends CakeTestCase { + +/** + * setUp method + * + * @return void + */ + public function setUp() { + parent::setUp(); + $this->Socket = new CakeSocket(array('timeout' => 1)); + } + +/** + * tearDown method + * + * @return void + */ + public function tearDown() { + parent::tearDown(); + unset($this->Socket); + } + +/** + * testConstruct method + * + * @return void + */ + public function testConstruct() { + $this->Socket = new CakeSocket(); + $config = $this->Socket->config; + $this->assertSame($config, array( + 'persistent' => false, + 'host' => 'localhost', + 'protocol' => getprotobyname('tcp'), + 'port' => 80, + 'timeout' => 30 + )); + + $this->Socket->reset(); + $this->Socket->__construct(array('host' => 'foo-bar')); + $config['host'] = 'foo-bar'; + $this->assertSame($this->Socket->config, $config); + + $this->Socket = new CakeSocket(array('host' => 'www.cakephp.org', 'port' => 23, 'protocol' => 'udp')); + $config = $this->Socket->config; + + $config['host'] = 'www.cakephp.org'; + $config['port'] = 23; + $config['protocol'] = 17; + + $this->assertSame($this->Socket->config, $config); + } + +/** + * testSocketConnection method + * + * @return void + */ + public function testSocketConnection() { + $this->assertFalse($this->Socket->connected); + $this->Socket->disconnect(); + $this->assertFalse($this->Socket->connected); + $this->Socket->connect(); + $this->assertTrue($this->Socket->connected); + $this->Socket->connect(); + $this->assertTrue($this->Socket->connected); + + $this->Socket->disconnect(); + $config = array('persistent' => true); + $this->Socket = new CakeSocket($config); + $this->Socket->connect(); + $this->assertTrue($this->Socket->connected); + } + +/** + * data provider function for testInvalidConnection + * + * @return array + */ + public static function invalidConnections() { + return array( + array(array('host' => 'invalid.host', 'port' => 9999, 'timeout' => 1)), + array(array('host' => '127.0.0.1', 'port' => '70000', 'timeout' => 1)) + ); + } + +/** + * testInvalidConnection method + * + * @dataProvider invalidConnections + * @expectedException SocketException + * return void + */ + public function testInvalidConnection($data) { + $this->Socket->config = array_merge($this->Socket->config, $data); + $this->Socket->connect(); + } + +/** + * testSocketHost method + * + * @return void + */ + public function testSocketHost() { + $this->Socket = new CakeSocket(); + $this->Socket->connect(); + $this->assertEquals('127.0.0.1', $this->Socket->address()); + $this->assertEquals(gethostbyaddr('127.0.0.1'), $this->Socket->host()); + $this->assertEquals(null, $this->Socket->lastError()); + $this->assertTrue(in_array('127.0.0.1', $this->Socket->addresses())); + + $this->Socket = new CakeSocket(array('host' => '127.0.0.1')); + $this->Socket->connect(); + $this->assertEquals('127.0.0.1', $this->Socket->address()); + $this->assertEquals(gethostbyaddr('127.0.0.1'), $this->Socket->host()); + $this->assertEquals(null, $this->Socket->lastError()); + $this->assertTrue(in_array('127.0.0.1', $this->Socket->addresses())); + } + +/** + * testSocketWriting method + * + * @return void + */ + public function testSocketWriting() { + $request = "GET / HTTP/1.1\r\nConnection: close\r\n\r\n"; + $this->assertTrue((bool)$this->Socket->write($request)); + } + +/** + * testSocketReading method + * + * @return void + */ + public function testSocketReading() { + $this->Socket = new CakeSocket(array('timeout' => 5)); + $this->Socket->connect(); + $this->assertEquals(null, $this->Socket->read(26)); + + $config = array('host' => 'google.com', 'port' => 80, 'timeout' => 1); + $this->Socket = new CakeSocket($config); + $this->assertTrue($this->Socket->connect()); + $this->assertEquals(null, $this->Socket->read(26)); + $this->assertEquals('2: ' . __d('cake_dev', 'Connection timed out'), $this->Socket->lastError()); + } + +/** + * testTimeOutConnection method + * + * @return void + */ + public function testTimeOutConnection() { + $config = array('host' => '127.0.0.1', 'timeout' => 0.5); + $this->Socket = new CakeSocket($config); + $this->assertTrue($this->Socket->connect()); + + $config = array('host' => '127.0.0.1', 'timeout' => 0.00001); + $this->Socket = new CakeSocket($config); + $this->assertFalse($this->Socket->read(1024 * 1024)); + $this->assertEquals('2: ' . __d('cake_dev', 'Connection timed out'), $this->Socket->lastError()); + } + +/** + * testLastError method + * + * @return void + */ + public function testLastError() { + $this->Socket = new CakeSocket(); + $this->Socket->setLastError(4, 'some error here'); + $this->assertEquals('4: some error here', $this->Socket->lastError()); + } + +/** + * testReset method + * + * @return void + */ + public function testReset() { + $config = array( + 'persistent' => true, + 'host' => '127.0.0.1', + 'protocol' => 'udp', + 'port' => 80, + 'timeout' => 20 + ); + $anotherSocket = new CakeSocket($config); + $anotherSocket->reset(); + $this->assertEquals(array(), $anotherSocket->config); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Network/Email/CakeEmailTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Network/Email/CakeEmailTest.php new file mode 100644 index 0000000..cde6495 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Network/Email/CakeEmailTest.php @@ -0,0 +1,1793 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Network.Email + * @since CakePHP(tm) v 2.0.0 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ +App::uses('CakeEmail', 'Network/Email'); + +/** + * Help to test CakeEmail + * + */ +class TestCakeEmail extends CakeEmail { + +/** + * Config + * + */ + protected $_config = array(); + +/** + * Wrap to protected method + * + */ + public function formatAddress($address) { + return parent::_formatAddress($address); + } + +/** + * Wrap to protected method + * + */ + public function wrap($text) { + return parent::_wrap($text); + } + +/** + * Get the boundary attribute + * + * @return string + */ + public function getBoundary() { + return $this->_boundary; + } + +/** + * Encode to protected method + * + */ + public function encode($text) { + return $this->_encode($text); + } + +} + +/* + * EmailConfig class + * + */ +class EmailConfig { + +/** + * test config + * + * @var string + */ + public $test = array( + 'from' => array('some@example.com' => 'My website'), + 'to' => array('test@example.com' => 'Testname'), + 'subject' => 'Test mail subject', + 'transport' => 'Debug', + 'theme' => 'TestTheme', + 'helpers' => array('Html', 'Form'), + ); + +} + +/* + * ExtendTransport class + * test class to ensure the class has send() method + * + */ +class ExtendTransport { + +} + +/** + * CakeEmailTest class + * + * @package Cake.Test.Case.Network.Email + */ +class CakeEmailTest extends CakeTestCase { + +/** + * setUp + * + * @return void + */ + public function setUp() { + parent::setUp(); + $this->CakeEmail = new TestCakeEmail(); + + App::build(array( + 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS) + )); + } + +/** + * tearDown method + * + * @return void + */ + public function tearDown() { + parent::tearDown(); + App::build(); + } + +/** + * testFrom method + * + * @return void + */ + public function testFrom() { + $this->assertSame($this->CakeEmail->from(), array()); + + $this->CakeEmail->from('cake@cakephp.org'); + $expected = array('cake@cakephp.org' => 'cake@cakephp.org'); + $this->assertSame($this->CakeEmail->from(), $expected); + + $this->CakeEmail->from(array('cake@cakephp.org')); + $this->assertSame($this->CakeEmail->from(), $expected); + + $this->CakeEmail->from('cake@cakephp.org', 'CakePHP'); + $expected = array('cake@cakephp.org' => 'CakePHP'); + $this->assertSame($this->CakeEmail->from(), $expected); + + $result = $this->CakeEmail->from(array('cake@cakephp.org' => 'CakePHP')); + $this->assertSame($this->CakeEmail->from(), $expected); + $this->assertSame($this->CakeEmail, $result); + + $this->setExpectedException('SocketException'); + $result = $this->CakeEmail->from(array('cake@cakephp.org' => 'CakePHP', 'fail@cakephp.org' => 'From can only be one address')); + } + +/** + * testSender method + * + * @return void + */ + public function testSender() { + $this->CakeEmail->reset(); + $this->assertSame($this->CakeEmail->sender(), array()); + + $this->CakeEmail->sender('cake@cakephp.org', 'Name'); + $expected = array('cake@cakephp.org' => 'Name'); + $this->assertSame($this->CakeEmail->sender(), $expected); + + $headers = $this->CakeEmail->getHeaders(array('from' => true, 'sender' => true)); + $this->assertSame($headers['From'], false); + $this->assertSame($headers['Sender'], 'Name '); + + $this->CakeEmail->from('cake@cakephp.org', 'CakePHP'); + $headers = $this->CakeEmail->getHeaders(array('from' => true, 'sender' => true)); + $this->assertSame($headers['From'], 'CakePHP '); + $this->assertSame($headers['Sender'], ''); + } + +/** + * testTo method + * + * @return void + */ + public function testTo() { + $this->assertSame($this->CakeEmail->to(), array()); + + $result = $this->CakeEmail->to('cake@cakephp.org'); + $expected = array('cake@cakephp.org' => 'cake@cakephp.org'); + $this->assertSame($this->CakeEmail->to(), $expected); + $this->assertSame($this->CakeEmail, $result); + + $this->CakeEmail->to('cake@cakephp.org', 'CakePHP'); + $expected = array('cake@cakephp.org' => 'CakePHP'); + $this->assertSame($this->CakeEmail->to(), $expected); + + $list = array( + 'cake@cakephp.org' => 'Cake PHP', + 'cake-php@googlegroups.com' => 'Cake Groups', + 'root@cakephp.org' + ); + $this->CakeEmail->to($list); + $expected = array( + 'cake@cakephp.org' => 'Cake PHP', + 'cake-php@googlegroups.com' => 'Cake Groups', + 'root@cakephp.org' => 'root@cakephp.org' + ); + $this->assertSame($this->CakeEmail->to(), $expected); + + $this->CakeEmail->addTo('jrbasso@cakephp.org'); + $this->CakeEmail->addTo('mark_story@cakephp.org', 'Mark Story'); + $result = $this->CakeEmail->addTo(array('phpnut@cakephp.org' => 'PhpNut', 'jose_zap@cakephp.org')); + $expected = array( + 'cake@cakephp.org' => 'Cake PHP', + 'cake-php@googlegroups.com' => 'Cake Groups', + 'root@cakephp.org' => 'root@cakephp.org', + 'jrbasso@cakephp.org' => 'jrbasso@cakephp.org', + 'mark_story@cakephp.org' => 'Mark Story', + 'phpnut@cakephp.org' => 'PhpNut', + 'jose_zap@cakephp.org' => 'jose_zap@cakephp.org' + ); + $this->assertSame($this->CakeEmail->to(), $expected); + $this->assertSame($this->CakeEmail, $result); + } + +/** + * Data provider function for testBuildInvalidData + * + * @return array + */ + public static function invalidEmails() { + return array( + array(1.0), + array(''), + array('string'), + array(''), + array('some@one.whereis'), + array('wrong@key' => 'Name'), + array(array('ok@cakephp.org', 1.0, '', 'string')) + ); + } + +/** + * testBuildInvalidData + * + * @dataProvider invalidEmails + * @expectedException SocketException + * @return void + */ + public function testInvalidEmail($value) { + $this->CakeEmail->to($value); + } + +/** + * testBuildInvalidData + * + * @dataProvider invalidEmails + * @expectedException SocketException + * @return void + */ + public function testInvalidEmailAdd($value) { + $this->CakeEmail->addTo($value); + } + +/** + * testFormatAddress method + * + * @return void + */ + public function testFormatAddress() { + $result = $this->CakeEmail->formatAddress(array('cake@cakephp.org' => 'cake@cakephp.org')); + $expected = array('cake@cakephp.org'); + $this->assertSame($expected, $result); + + $result = $this->CakeEmail->formatAddress(array('cake@cakephp.org' => 'cake@cakephp.org', 'php@cakephp.org' => 'php@cakephp.org')); + $expected = array('cake@cakephp.org', 'php@cakephp.org'); + $this->assertSame($expected, $result); + + $result = $this->CakeEmail->formatAddress(array('cake@cakephp.org' => 'CakePHP', 'php@cakephp.org' => 'Cake')); + $expected = array('CakePHP ', 'Cake '); + $this->assertSame($expected, $result); + + $result = $this->CakeEmail->formatAddress(array('me@example.com' => 'Last, First')); + $expected = array('"Last, First" '); + $this->assertSame($expected, $result); + + $result = $this->CakeEmail->formatAddress(array('me@example.com' => 'Last First')); + $expected = array('Last First '); + $this->assertSame($expected, $result); + + $result = $this->CakeEmail->formatAddress(array('cake@cakephp.org' => 'ÄÖÜTest')); + $expected = array('=?UTF-8?B?w4TDlsOcVGVzdA==?= '); + $this->assertSame($expected, $result); + + $result = $this->CakeEmail->formatAddress(array('cake@cakephp.org' => '日本語Test')); + $expected = array('=?UTF-8?B?5pel5pys6KqeVGVzdA==?= '); + $this->assertSame($expected, $result); + } + +/** + * testFormatAddressJapanese + * + * @return void + */ + public function testFormatAddressJapanese() { + $this->skipIf(!function_exists('mb_convert_encoding')); + + $this->CakeEmail->headerCharset = 'ISO-2022-JP'; + $result = $this->CakeEmail->formatAddress(array('cake@cakephp.org' => '日本語Test')); + $expected = array('=?ISO-2022-JP?B?GyRCRnxLXDhsGyhCVGVzdA==?= '); + $this->assertSame($expected, $result); + + $result = $this->CakeEmail->formatAddress(array('cake@cakephp.org' => '寿限無寿限無五劫の擦り切れ海砂利水魚の水行末雲来末風来末食う寝る処に住む処やぶら小路の藪柑子パイポパイポパイポのシューリンガンシューリンガンのグーリンダイグーリンダイのポンポコピーのポンポコナーの長久命の長助')); + $expected = array("=?ISO-2022-JP?B?GyRCPHc4Qkw1PHc4Qkw1OF45ZSROOyQkakBaJGwzJDo9TXg/ZTV7GyhC?=\r\n" . + " =?ISO-2022-JP?B?GyRCJE4/ZTlUS3YxQE1oS3ZJd01oS3Y/KSQmPzIkaz1oJEs9OyRgGyhC?=\r\n" . + " =?ISO-2022-JP?B?GyRCPWgkZCRWJGk+Lk8pJE5pLjQ7O1IlUSUkJV0lUSUkJV0lUSUkGyhC?=\r\n" . + " =?ISO-2022-JP?B?GyRCJV0kTiU3JWUhPCVqJXMlLCVzJTclZSE8JWolcyUsJXMkTiUwGyhC?=\r\n" . + " =?ISO-2022-JP?B?GyRCITwlaiVzJUAlJCUwITwlaiVzJUAlJCROJV0lcyVdJTMlVCE8GyhC?=\r\n" . + " =?ISO-2022-JP?B?GyRCJE4lXSVzJV0lMyVKITwkTkQ5NVdMPyRORDk9dRsoQg==?= "); + $this->assertSame($expected, $result); + } + +/** + * testAddresses method + * + * @return void + */ + public function testAddresses() { + $this->CakeEmail->reset(); + $this->CakeEmail->from('cake@cakephp.org', 'CakePHP'); + $this->CakeEmail->replyTo('replyto@cakephp.org', 'ReplyTo CakePHP'); + $this->CakeEmail->readReceipt('readreceipt@cakephp.org', 'ReadReceipt CakePHP'); + $this->CakeEmail->returnPath('returnpath@cakephp.org', 'ReturnPath CakePHP'); + $this->CakeEmail->to('to@cakephp.org', 'To CakePHP'); + $this->CakeEmail->cc('cc@cakephp.org', 'Cc CakePHP'); + $this->CakeEmail->bcc('bcc@cakephp.org', 'Bcc CakePHP'); + $this->CakeEmail->addTo('to2@cakephp.org', 'To2 CakePHP'); + $this->CakeEmail->addCc('cc2@cakephp.org', 'Cc2 CakePHP'); + $this->CakeEmail->addBcc('bcc2@cakephp.org', 'Bcc2 CakePHP'); + + $this->assertSame($this->CakeEmail->from(), array('cake@cakephp.org' => 'CakePHP')); + $this->assertSame($this->CakeEmail->replyTo(), array('replyto@cakephp.org' => 'ReplyTo CakePHP')); + $this->assertSame($this->CakeEmail->readReceipt(), array('readreceipt@cakephp.org' => 'ReadReceipt CakePHP')); + $this->assertSame($this->CakeEmail->returnPath(), array('returnpath@cakephp.org' => 'ReturnPath CakePHP')); + $this->assertSame($this->CakeEmail->to(), array('to@cakephp.org' => 'To CakePHP', 'to2@cakephp.org' => 'To2 CakePHP')); + $this->assertSame($this->CakeEmail->cc(), array('cc@cakephp.org' => 'Cc CakePHP', 'cc2@cakephp.org' => 'Cc2 CakePHP')); + $this->assertSame($this->CakeEmail->bcc(), array('bcc@cakephp.org' => 'Bcc CakePHP', 'bcc2@cakephp.org' => 'Bcc2 CakePHP')); + + $headers = $this->CakeEmail->getHeaders(array_fill_keys(array('from', 'replyTo', 'readReceipt', 'returnPath', 'to', 'cc', 'bcc'), true)); + $this->assertSame($headers['From'], 'CakePHP '); + $this->assertSame($headers['Reply-To'], 'ReplyTo CakePHP '); + $this->assertSame($headers['Disposition-Notification-To'], 'ReadReceipt CakePHP '); + $this->assertSame($headers['Return-Path'], 'ReturnPath CakePHP '); + $this->assertSame($headers['To'], 'To CakePHP , To2 CakePHP '); + $this->assertSame($headers['Cc'], 'Cc CakePHP , Cc2 CakePHP '); + $this->assertSame($headers['Bcc'], 'Bcc CakePHP , Bcc2 CakePHP '); + } + +/** + * testMessageId method + * + * @return void + */ + public function testMessageId() { + $this->CakeEmail->messageId(true); + $result = $this->CakeEmail->getHeaders(); + $this->assertTrue(isset($result['Message-ID'])); + + $this->CakeEmail->messageId(false); + $result = $this->CakeEmail->getHeaders(); + $this->assertFalse(isset($result['Message-ID'])); + + $result = $this->CakeEmail->messageId(''); + $this->assertSame($this->CakeEmail, $result); + $result = $this->CakeEmail->getHeaders(); + $this->assertSame($result['Message-ID'], ''); + + $result = $this->CakeEmail->messageId(); + $this->assertSame($result, ''); + } + +/** + * testMessageIdInvalid method + * + * @return void + * @expectedException SocketException + */ + public function testMessageIdInvalid() { + $this->CakeEmail->messageId('my-email@localhost'); + } + +/** + * testDomain method + * + * @return void + */ + public function testDomain() { + $result = $this->CakeEmail->domain(); + $expected = env('HTTP_HOST') ? env('HTTP_HOST') : php_uname('n'); + $this->assertSame($expected, $result); + + $this->CakeEmail->domain('example.org'); + $result = $this->CakeEmail->domain(); + $expected = 'example.org'; + $this->assertSame($expected, $result); + } + +/** + * testMessageIdWithDomain method + * + * @return void + */ + public function testMessageIdWithDomain() { + $result = $this->CakeEmail->getHeaders(); + $expected = '@' . (env('HTTP_HOST') ? env('HTTP_HOST') : php_uname('n')) . '>'; + $this->assertTextContains($expected, $result['Message-ID']); + + $this->CakeEmail->domain('example.org'); + $result = $this->CakeEmail->getHeaders(); + $expected = '@example.org>'; + $this->assertTextContains($expected, $result['Message-ID']); + } + +/** + * testSubject method + * + * @return void + */ + public function testSubject() { + $this->CakeEmail->subject('You have a new message.'); + $this->assertSame($this->CakeEmail->subject(), 'You have a new message.'); + + $this->CakeEmail->subject('You have a new message, I think.'); + $this->assertSame($this->CakeEmail->subject(), 'You have a new message, I think.'); + $this->CakeEmail->subject(1); + $this->assertSame($this->CakeEmail->subject(), '1'); + + $this->CakeEmail->subject('هذه رسالة بعنوان طويل مرسل للمستلم'); + $expected = '=?UTF-8?B?2YfYsNmHINix2LPYp9mE2Kkg2KjYudmG2YjYp9mGINi32YjZitmEINmF2LE=?=' . "\r\n" . ' =?UTF-8?B?2LPZhCDZhNmE2YXYs9iq2YTZhQ==?='; + $this->assertSame($this->CakeEmail->subject(), $expected); + } + +/** + * testSubjectJapanese + * + * @return void + */ + public function testSubjectJapanese() { + $this->skipIf(!function_exists('mb_convert_encoding')); + mb_internal_encoding('UTF-8'); + + $this->CakeEmail->headerCharset = 'ISO-2022-JP'; + $this->CakeEmail->subject('日本語のSubjectにも対応するよ'); + $expected = '=?ISO-2022-JP?B?GyRCRnxLXDhsJE4bKEJTdWJqZWN0GyRCJEskYkJQMX4kOSRrJGgbKEI=?='; + $this->assertSame($this->CakeEmail->subject(), $expected); + + $this->CakeEmail->subject('長い長い長いSubjectの場合はfoldingするのが正しいんだけどいったいどうなるんだろう?'); + $expected = "=?ISO-2022-JP?B?GyRCRDkkJEQ5JCREOSQkGyhCU3ViamVjdBskQiROPmw5ZyRPGyhCZm9s?=\r\n" . + " =?ISO-2022-JP?B?ZGluZxskQiQ5JGskTiQsQDUkNyQkJHMkQCQxJEkkJCRDJD8kJCRJGyhC?=\r\n" . + " =?ISO-2022-JP?B?GyRCJCYkSiRrJHMkQCRtJCYhKRsoQg==?="; + $this->assertSame($this->CakeEmail->subject(), $expected); + } + +/** + * testHeaders method + * + * @return void + */ + public function testHeaders() { + $this->CakeEmail->messageId(false); + $this->CakeEmail->setHeaders(array('X-Something' => 'nice')); + $expected = array( + 'X-Something' => 'nice', + 'X-Mailer' => 'CakePHP Email', + 'Date' => date(DATE_RFC2822), + 'MIME-Version' => '1.0', + 'Content-Type' => 'text/plain; charset=UTF-8', + 'Content-Transfer-Encoding' => '8bit' + ); + $this->assertSame($this->CakeEmail->getHeaders(), $expected); + + $this->CakeEmail->addHeaders(array('X-Something' => 'very nice', 'X-Other' => 'cool')); + $expected = array( + 'X-Something' => 'very nice', + 'X-Other' => 'cool', + 'X-Mailer' => 'CakePHP Email', + 'Date' => date(DATE_RFC2822), + 'MIME-Version' => '1.0', + 'Content-Type' => 'text/plain; charset=UTF-8', + 'Content-Transfer-Encoding' => '8bit' + ); + $this->assertSame($this->CakeEmail->getHeaders(), $expected); + + $this->CakeEmail->from('cake@cakephp.org'); + $this->assertSame($this->CakeEmail->getHeaders(), $expected); + + $expected = array( + 'From' => 'cake@cakephp.org', + 'X-Something' => 'very nice', + 'X-Other' => 'cool', + 'X-Mailer' => 'CakePHP Email', + 'Date' => date(DATE_RFC2822), + 'MIME-Version' => '1.0', + 'Content-Type' => 'text/plain; charset=UTF-8', + 'Content-Transfer-Encoding' => '8bit' + ); + $this->assertSame($this->CakeEmail->getHeaders(array('from' => true)), $expected); + + $this->CakeEmail->from('cake@cakephp.org', 'CakePHP'); + $expected['From'] = 'CakePHP '; + $this->assertSame($this->CakeEmail->getHeaders(array('from' => true)), $expected); + + $this->CakeEmail->to(array('cake@cakephp.org', 'php@cakephp.org' => 'CakePHP')); + $expected = array( + 'From' => 'CakePHP ', + 'To' => 'cake@cakephp.org, CakePHP ', + 'X-Something' => 'very nice', + 'X-Other' => 'cool', + 'X-Mailer' => 'CakePHP Email', + 'Date' => date(DATE_RFC2822), + 'MIME-Version' => '1.0', + 'Content-Type' => 'text/plain; charset=UTF-8', + 'Content-Transfer-Encoding' => '8bit' + ); + $this->assertSame($this->CakeEmail->getHeaders(array('from' => true, 'to' => true)), $expected); + + $this->CakeEmail->charset = 'ISO-2022-JP'; + $expected = array( + 'From' => 'CakePHP ', + 'To' => 'cake@cakephp.org, CakePHP ', + 'X-Something' => 'very nice', + 'X-Other' => 'cool', + 'X-Mailer' => 'CakePHP Email', + 'Date' => date(DATE_RFC2822), + 'MIME-Version' => '1.0', + 'Content-Type' => 'text/plain; charset=ISO-2022-JP', + 'Content-Transfer-Encoding' => '7bit' + ); + $this->assertSame($this->CakeEmail->getHeaders(array('from' => true, 'to' => true)), $expected); + + $result = $this->CakeEmail->setHeaders(array()); + $this->assertInstanceOf('CakeEmail', $result); + } + +/** + * Data provider function for testInvalidHeaders + * + * @return array + */ + public static function invalidHeaders() { + return array( + array(10), + array(''), + array('string'), + array(false), + array(null) + ); + } + +/** + * testInvalidHeaders + * + * @dataProvider invalidHeaders + * @expectedException SocketException + * @return void + */ + public function testInvalidHeaders($value) { + $this->CakeEmail->setHeaders($value); + } + +/** + * testInvalidAddHeaders + * + * @dataProvider invalidHeaders + * @expectedException SocketException + * @return void + */ + public function testInvalidAddHeaders($value) { + $this->CakeEmail->addHeaders($value); + } + +/** + * testTemplate method + * + * @return void + */ + public function testTemplate() { + $this->CakeEmail->template('template', 'layout'); + $expected = array('template' => 'template', 'layout' => 'layout'); + $this->assertSame($this->CakeEmail->template(), $expected); + + $this->CakeEmail->template('new_template'); + $expected = array('template' => 'new_template', 'layout' => 'layout'); + $this->assertSame($this->CakeEmail->template(), $expected); + + $this->CakeEmail->template('template', null); + $expected = array('template' => 'template', 'layout' => null); + $this->assertSame($this->CakeEmail->template(), $expected); + + $this->CakeEmail->template(null, null); + $expected = array('template' => null, 'layout' => null); + $this->assertSame($this->CakeEmail->template(), $expected); + } + +/** + * testTheme method + * + * @return void + */ + public function testTheme() { + $this->assertSame(null, $this->CakeEmail->theme()); + + $this->CakeEmail->theme('default'); + $expected = 'default'; + $this->assertSame($expected, $this->CakeEmail->theme()); + } + +/** + * testViewVars method + * + * @return void + */ + public function testViewVars() { + $this->assertSame($this->CakeEmail->viewVars(), array()); + + $this->CakeEmail->viewVars(array('value' => 12345)); + $this->assertSame($this->CakeEmail->viewVars(), array('value' => 12345)); + + $this->CakeEmail->viewVars(array('name' => 'CakePHP')); + $this->assertSame($this->CakeEmail->viewVars(), array('value' => 12345, 'name' => 'CakePHP')); + + $this->CakeEmail->viewVars(array('value' => 4567)); + $this->assertSame($this->CakeEmail->viewVars(), array('value' => 4567, 'name' => 'CakePHP')); + } + +/** + * testAttachments method + * + * @return void + */ + public function testAttachments() { + $this->CakeEmail->attachments(CAKE . 'basics.php'); + $expected = array('basics.php' => array('file' => CAKE . 'basics.php', 'mimetype' => 'application/octet-stream')); + $this->assertSame($this->CakeEmail->attachments(), $expected); + + $this->CakeEmail->attachments(array()); + $this->assertSame($this->CakeEmail->attachments(), array()); + + $this->CakeEmail->attachments(array(array('file' => CAKE . 'basics.php', 'mimetype' => 'text/plain'))); + $this->CakeEmail->addAttachments(CAKE . 'bootstrap.php'); + $this->CakeEmail->addAttachments(array(CAKE . 'bootstrap.php')); + $this->CakeEmail->addAttachments(array('other.txt' => CAKE . 'bootstrap.php', 'license' => CAKE . 'LICENSE.txt')); + $expected = array( + 'basics.php' => array('file' => CAKE . 'basics.php', 'mimetype' => 'text/plain'), + 'bootstrap.php' => array('file' => CAKE . 'bootstrap.php', 'mimetype' => 'application/octet-stream'), + 'other.txt' => array('file' => CAKE . 'bootstrap.php', 'mimetype' => 'application/octet-stream'), + 'license' => array('file' => CAKE . 'LICENSE.txt', 'mimetype' => 'application/octet-stream') + ); + $this->assertSame($this->CakeEmail->attachments(), $expected); + + $this->setExpectedException('SocketException'); + $this->CakeEmail->attachments(array(array('nofile' => CAKE . 'basics.php', 'mimetype' => 'text/plain'))); + } + +/** + * testTransport method + * + * @return void + */ + public function testTransport() { + $result = $this->CakeEmail->transport('Debug'); + $this->assertSame($this->CakeEmail, $result); + $this->assertSame($this->CakeEmail->transport(), 'Debug'); + + $result = $this->CakeEmail->transportClass(); + $this->assertInstanceOf('DebugTransport', $result); + + $this->setExpectedException('SocketException'); + $this->CakeEmail->transport('Invalid'); + $result = $this->CakeEmail->transportClass(); + } + +/** + * testExtendTransport method + * + * @return void + */ + public function testExtendTransport() { + $this->setExpectedException('SocketException'); + $this->CakeEmail->transport('Extend'); + $result = $this->CakeEmail->transportClass(); + } + +/** + * testConfig method + * + * @return void + */ + public function testConfig() { + $transportClass = $this->CakeEmail->transport('debug')->transportClass(); + + $config = array('test' => 'ok', 'test2' => true); + $this->CakeEmail->config($config); + $this->assertSame($transportClass->config(), $config); + $this->assertSame($this->CakeEmail->config(), $config); + + $this->CakeEmail->config(array()); + $this->assertSame($transportClass->config(), array()); + } + +/** + * testConfigString method + * + * @return void + */ + public function testConfigString() { + $configs = new EmailConfig(); + $this->CakeEmail->config('test'); + + $result = $this->CakeEmail->to(); + $this->assertEquals($configs->test['to'], $result); + + $result = $this->CakeEmail->from(); + $this->assertEquals($configs->test['from'], $result); + + $result = $this->CakeEmail->subject(); + $this->assertEquals($configs->test['subject'], $result); + + $result = $this->CakeEmail->theme(); + $this->assertEquals($configs->test['theme'], $result); + + $result = $this->CakeEmail->transport(); + $this->assertEquals($configs->test['transport'], $result); + + $result = $this->CakeEmail->transportClass(); + $this->assertInstanceOf('DebugTransport', $result); + + $result = $this->CakeEmail->helpers(); + $this->assertEquals($configs->test['helpers'], $result); + } + +/** + * testSendWithContent method + * + * @return void + */ + public function testSendWithContent() { + $this->CakeEmail->reset(); + $this->CakeEmail->transport('Debug'); + $this->CakeEmail->from('cake@cakephp.org'); + $this->CakeEmail->to(array('you@cakephp.org' => 'You')); + $this->CakeEmail->subject('My title'); + $this->CakeEmail->config(array('empty')); + + $result = $this->CakeEmail->send("Here is my body, with multi lines.\nThis is the second line.\r\n\r\nAnd the last."); + $expected = array('headers', 'message'); + $this->assertEquals($expected, array_keys($result)); + $expected = "Here is my body, with multi lines.\r\nThis is the second line.\r\n\r\nAnd the last.\r\n\r\n"; + + $this->assertEquals($expected, $result['message']); + $this->assertTrue((bool)strpos($result['headers'], 'Date: ')); + $this->assertTrue((bool)strpos($result['headers'], 'Message-ID: ')); + $this->assertTrue((bool)strpos($result['headers'], 'To: ')); + + $result = $this->CakeEmail->send("Other body"); + $expected = "Other body\r\n\r\n"; + $this->assertSame($result['message'], $expected); + $this->assertTrue((bool)strpos($result['headers'], 'Message-ID: ')); + $this->assertTrue((bool)strpos($result['headers'], 'To: ')); + + $this->CakeEmail->reset(); + $this->CakeEmail->transport('Debug'); + $this->CakeEmail->from('cake@cakephp.org'); + $this->CakeEmail->to(array('you@cakephp.org' => 'You')); + $this->CakeEmail->subject('My title'); + $this->CakeEmail->config(array('empty')); + $result = $this->CakeEmail->send(array('Sending content', 'As array')); + $expected = "Sending content\r\nAs array\r\n\r\n\r\n"; + $this->assertSame($result['message'], $expected); + } + +/** + * testSendWithoutFrom method + * + * @return void + */ + public function testSendWithoutFrom() { + $this->CakeEmail->transport('Debug'); + $this->CakeEmail->to('cake@cakephp.org'); + $this->CakeEmail->subject('My title'); + $this->CakeEmail->config(array('empty')); + $this->setExpectedException('SocketException'); + $this->CakeEmail->send("Forgot to set From"); + } + +/** + * testSendWithoutTo method + * + * @return void + */ + public function testSendWithoutTo() { + $this->CakeEmail->transport('Debug'); + $this->CakeEmail->from('cake@cakephp.org'); + $this->CakeEmail->subject('My title'); + $this->CakeEmail->config(array('empty')); + $this->setExpectedException('SocketException'); + $this->CakeEmail->send("Forgot to set To"); + } + +/** + * Test send() with no template. + * + * @return void + */ + public function testSendNoTemplateWithAttachments() { + $this->CakeEmail->transport('debug'); + $this->CakeEmail->from('cake@cakephp.org'); + $this->CakeEmail->to('cake@cakephp.org'); + $this->CakeEmail->subject('My title'); + $this->CakeEmail->emailFormat('text'); + $this->CakeEmail->attachments(array(CAKE . 'basics.php')); + $result = $this->CakeEmail->send('Hello'); + + $boundary = $this->CakeEmail->getBoundary(); + $this->assertContains('Content-Type: multipart/mixed; boundary="' . $boundary . '"', $result['headers']); + $expected = "--$boundary\r\n" . + "Content-Type: text/plain; charset=UTF-8\r\n" . + "Content-Transfer-Encoding: 8bit\r\n" . + "\r\n" . + "Hello" . + "\r\n" . + "\r\n" . + "\r\n" . + "--$boundary\r\n" . + "Content-Type: application/octet-stream\r\n" . + "Content-Transfer-Encoding: base64\r\n" . + "Content-Disposition: attachment; filename=\"basics.php\"\r\n\r\n"; + $this->assertContains($expected, $result['message']); + } + +/** + * Test send() with no template as both + * + * @return void + */ + public function testSendNoTemplateWithAttachmentsAsBoth() { + $this->CakeEmail->transport('debug'); + $this->CakeEmail->from('cake@cakephp.org'); + $this->CakeEmail->to('cake@cakephp.org'); + $this->CakeEmail->subject('My title'); + $this->CakeEmail->emailFormat('both'); + $this->CakeEmail->attachments(array(CAKE . 'VERSION.txt')); + $result = $this->CakeEmail->send('Hello'); + + $boundary = $this->CakeEmail->getBoundary(); + $this->assertContains('Content-Type: multipart/mixed; boundary="' . $boundary . '"', $result['headers']); + $expected = "--$boundary\r\n" . + "Content-Type: multipart/alternative; boundary=\"alt-$boundary\"\r\n" . + "\r\n" . + "--alt-$boundary\r\n" . + "Content-Type: text/plain; charset=UTF-8\r\n" . + "Content-Transfer-Encoding: 8bit\r\n" . + "\r\n" . + "Hello" . + "\r\n" . + "\r\n" . + "\r\n" . + "--alt-$boundary\r\n" . + "Content-Type: text/html; charset=UTF-8\r\n" . + "Content-Transfer-Encoding: 8bit\r\n" . + "\r\n" . + "Hello" . + "\r\n" . + "\r\n" . + "\r\n" . + "--alt-{$boundary}--\r\n" . + "\r\n" . + "--$boundary\r\n" . + "Content-Type: application/octet-stream\r\n" . + "Content-Transfer-Encoding: base64\r\n" . + "Content-Disposition: attachment; filename=\"VERSION.txt\"\r\n\r\n"; + $this->assertContains($expected, $result['message']); + } + +/** + * Test setting inline attachments and messages. + * + * @return void + */ + public function testSendWithInlineAttachments() { + $this->CakeEmail->transport('debug'); + $this->CakeEmail->from('cake@cakephp.org'); + $this->CakeEmail->to('cake@cakephp.org'); + $this->CakeEmail->subject('My title'); + $this->CakeEmail->emailFormat('both'); + $this->CakeEmail->attachments(array( + 'cake.png' => array( + 'file' => CAKE . 'VERSION.txt', + 'contentId' => 'abc123' + ) + )); + $result = $this->CakeEmail->send('Hello'); + + $boundary = $this->CakeEmail->getBoundary(); + $this->assertContains('Content-Type: multipart/mixed; boundary="' . $boundary . '"', $result['headers']); + $expected = "--$boundary\r\n" . + "Content-Type: multipart/related; boundary=\"rel-$boundary\"\r\n" . + "\r\n" . + "--rel-$boundary\r\n" . + "Content-Type: multipart/alternative; boundary=\"alt-$boundary\"\r\n" . + "\r\n" . + "--alt-$boundary\r\n" . + "Content-Type: text/plain; charset=UTF-8\r\n" . + "Content-Transfer-Encoding: 8bit\r\n" . + "\r\n" . + "Hello" . + "\r\n" . + "\r\n" . + "\r\n" . + "--alt-$boundary\r\n" . + "Content-Type: text/html; charset=UTF-8\r\n" . + "Content-Transfer-Encoding: 8bit\r\n" . + "\r\n" . + "Hello" . + "\r\n" . + "\r\n" . + "\r\n" . + "--alt-{$boundary}--\r\n" . + "\r\n" . + "--rel-$boundary\r\n" . + "Content-Type: application/octet-stream\r\n" . + "Content-Transfer-Encoding: base64\r\n" . + "Content-ID: \r\n" . + "Content-Disposition: inline; filename=\"cake.png\"\r\n\r\n"; + $this->assertContains($expected, $result['message']); + $this->assertContains('--rel-' . $boundary . '--', $result['message']); + $this->assertContains('--' . $boundary . '--', $result['message']); + } + +/** + * testSendWithLog method + * + * @return void + */ + public function testSendWithLog() { + $path = CAKE . 'Test' . DS . 'test_app' . DS . 'tmp' . DS; + CakeLog::config('email', array( + 'engine' => 'FileLog', + 'path' => TMP + )); + CakeLog::drop('default'); + $this->CakeEmail->transport('Debug'); + $this->CakeEmail->to('me@cakephp.org'); + $this->CakeEmail->from('cake@cakephp.org'); + $this->CakeEmail->subject('My title'); + $this->CakeEmail->config(array('log' => 'cake_test_emails')); + $result = $this->CakeEmail->send("Logging This"); + + App::uses('File', 'Utility'); + $File = new File(TMP . 'cake_test_emails.log'); + $log = $File->read(); + $this->assertTrue(strpos($log, $result['headers']) !== false); + $this->assertTrue(strpos($log, $result['message']) !== false); + $File->delete(); + CakeLog::drop('email'); + } + +/** + * testSendRender method + * + * @return void + */ + public function testSendRender() { + $this->CakeEmail->reset(); + $this->CakeEmail->transport('debug'); + + $this->CakeEmail->from('cake@cakephp.org'); + $this->CakeEmail->to(array('you@cakephp.org' => 'You')); + $this->CakeEmail->subject('My title'); + $this->CakeEmail->config(array('empty')); + $this->CakeEmail->template('default', 'default'); + $result = $this->CakeEmail->send(); + + $this->assertContains('This email was sent using the CakePHP Framework', $result['message']); + $this->assertContains('Message-ID: ', $result['headers']); + $this->assertContains('To: ', $result['headers']); + } + +/** + * testSendRender method for ISO-2022-JP + * + * @return void + */ + public function testSendRenderJapanese() { + $this->skipIf(!function_exists('mb_convert_encoding')); + + $this->CakeEmail->reset(); + $this->CakeEmail->transport('debug'); + + $this->CakeEmail->from('cake@cakephp.org'); + $this->CakeEmail->to(array('you@cakephp.org' => 'You')); + $this->CakeEmail->subject('My title'); + $this->CakeEmail->config(array('empty')); + $this->CakeEmail->template('default', 'japanese'); + $this->CakeEmail->charset = 'ISO-2022-JP'; + $result = $this->CakeEmail->send(); + + $expected = mb_convert_encoding('CakePHP Framework を使って送信したメールです。 http://cakephp.org.', 'ISO-2022-JP'); + $this->assertContains($expected, $result['message']); + $this->assertContains('Message-ID: ', $result['headers']); + $this->assertContains('To: ', $result['headers']); + } + +/** + * testSendRenderThemed method + * + * @return void + */ + public function testSendRenderThemed() { + $this->CakeEmail->reset(); + $this->CakeEmail->transport('debug'); + + $this->CakeEmail->from('cake@cakephp.org'); + $this->CakeEmail->to(array('you@cakephp.org' => 'You')); + $this->CakeEmail->subject('My title'); + $this->CakeEmail->config(array('empty')); + $this->CakeEmail->theme('TestTheme'); + $this->CakeEmail->template('themed', 'default'); + $result = $this->CakeEmail->send(); + + $this->assertContains('In TestTheme', $result['message']); + $this->assertContains('Message-ID: ', $result['headers']); + $this->assertContains('To: ', $result['headers']); + } + +/** + * testSendRenderWithVars method + * + * @return void + */ + public function testSendRenderWithVars() { + $this->CakeEmail->reset(); + $this->CakeEmail->transport('debug'); + + $this->CakeEmail->from('cake@cakephp.org'); + $this->CakeEmail->to(array('you@cakephp.org' => 'You')); + $this->CakeEmail->subject('My title'); + $this->CakeEmail->config(array('empty')); + $this->CakeEmail->template('custom', 'default'); + $this->CakeEmail->viewVars(array('value' => 12345)); + $result = $this->CakeEmail->send(); + + $this->assertContains('Here is your value: 12345', $result['message']); + } + +/** + * testSendRenderWithVars method for ISO-2022-JP + * + * @return void + */ + public function testSendRenderWithVarsJapanese() { + $this->skipIf(!function_exists('mb_convert_encoding')); + $this->CakeEmail->reset(); + $this->CakeEmail->transport('debug'); + + $this->CakeEmail->from('cake@cakephp.org'); + $this->CakeEmail->to(array('you@cakephp.org' => 'You')); + $this->CakeEmail->subject('My title'); + $this->CakeEmail->config(array('empty')); + $this->CakeEmail->template('japanese', 'default'); + $this->CakeEmail->viewVars(array('value' => '日本語の差し込み123')); + $this->CakeEmail->charset = 'ISO-2022-JP'; + $result = $this->CakeEmail->send(); + + $expected = mb_convert_encoding('ここにあなたの設定した値が入ります: 日本語の差し込み123', 'ISO-2022-JP'); + $this->assertTrue((bool)strpos($result['message'], $expected)); + } + +/** + * testSendRenderWithHelpers method + * + * @return void + */ + public function testSendRenderWithHelpers() { + $this->CakeEmail->reset(); + $this->CakeEmail->transport('debug'); + + $timestamp = time(); + $this->CakeEmail->from('cake@cakephp.org'); + $this->CakeEmail->to(array('you@cakephp.org' => 'You')); + $this->CakeEmail->subject('My title'); + $this->CakeEmail->config(array('empty')); + $this->CakeEmail->template('custom_helper', 'default'); + $this->CakeEmail->viewVars(array('time' => $timestamp)); + + $result = $this->CakeEmail->helpers(array('Time')); + $this->assertInstanceOf('CakeEmail', $result); + + $result = $this->CakeEmail->send(); + $this->assertTrue((bool)strpos($result['message'], 'Right now: ' . date('Y-m-d\TH:i:s\Z', $timestamp))); + + $result = $this->CakeEmail->helpers(); + $this->assertEquals(array('Time'), $result); + } + +/** + * testSendRenderWithImage method + * + * @return void + */ + public function testSendRenderWithImage() { + $this->CakeEmail->reset(); + $this->CakeEmail->transport('Debug'); + + $this->CakeEmail->from('cake@cakephp.org'); + $this->CakeEmail->to(array('you@cakephp.org' => 'You')); + $this->CakeEmail->subject('My title'); + $this->CakeEmail->config(array('empty')); + $this->CakeEmail->template('image'); + $this->CakeEmail->emailFormat('html'); + + $server = env('SERVER_NAME') ? env('SERVER_NAME') : 'localhost'; + $expected = 'cool image'; + $result = $this->CakeEmail->send(); + $this->assertContains($expected, $result['message']); + } + +/** + * testSendRenderPlugin method + * + * @return void + */ + public function testSendRenderPlugin() { + App::build(array( + 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS) + )); + CakePlugin::load('TestPlugin'); + + $this->CakeEmail->reset(); + $this->CakeEmail->transport('debug'); + $this->CakeEmail->from('cake@cakephp.org'); + $this->CakeEmail->to(array('you@cakephp.org' => 'You')); + $this->CakeEmail->subject('My title'); + $this->CakeEmail->config(array('empty')); + + $result = $this->CakeEmail->template('TestPlugin.test_plugin_tpl', 'default')->send(); + $this->assertContains('Into TestPlugin.', $result['message']); + $this->assertContains('This email was sent using the CakePHP Framework', $result['message']); + + $result = $this->CakeEmail->template('TestPlugin.test_plugin_tpl', 'TestPlugin.plug_default')->send(); + $this->assertContains('Into TestPlugin.', $result['message']); + $this->assertContains('This email was sent using the TestPlugin.', $result['message']); + + $result = $this->CakeEmail->template('TestPlugin.test_plugin_tpl', 'plug_default')->send(); + $this->assertContains('Into TestPlugin.', $result['message']); + $this->assertContains('This email was sent using the TestPlugin.', $result['message']); + + // test plugin template overridden by theme + $this->CakeEmail->theme('TestTheme'); + $result = $this->CakeEmail->send(); + + $this->assertContains('Into TestPlugin. (themed)', $result['message']); + + $this->CakeEmail->viewVars(array('value' => 12345)); + $result = $this->CakeEmail->template('custom', 'TestPlugin.plug_default')->send(); + $this->assertContains('Here is your value: 12345', $result['message']); + $this->assertContains('This email was sent using the TestPlugin.', $result['message']); + + $this->setExpectedException('MissingViewException'); + $this->CakeEmail->template('test_plugin_tpl', 'plug_default')->send(); + } + +/** + * testSendMultipleMIME method + * + * @return void + */ + public function testSendMultipleMIME() { + $this->CakeEmail->reset(); + $this->CakeEmail->transport('debug'); + + $this->CakeEmail->from('cake@cakephp.org'); + $this->CakeEmail->to(array('you@cakephp.org' => 'You')); + $this->CakeEmail->subject('My title'); + $this->CakeEmail->template('custom', 'default'); + $this->CakeEmail->config(array()); + $this->CakeEmail->viewVars(array('value' => 12345)); + $this->CakeEmail->emailFormat('both'); + $result = $this->CakeEmail->send(); + + $message = $this->CakeEmail->message(); + $boundary = $this->CakeEmail->getBoundary(); + $this->assertFalse(empty($boundary)); + $this->assertContains('--' . $boundary, $message); + $this->assertContains('--' . $boundary . '--', $message); + $this->assertContains('--alt-' . $boundary, $message); + $this->assertContains('--alt-' . $boundary . '--', $message); + + $this->CakeEmail->attachments(array('fake.php' => __FILE__)); + $this->CakeEmail->send(); + + $message = $this->CakeEmail->message(); + $boundary = $this->CakeEmail->getBoundary(); + $this->assertFalse(empty($boundary)); + $this->assertContains('--' . $boundary, $message); + $this->assertContains('--' . $boundary . '--', $message); + $this->assertContains('--alt-' . $boundary, $message); + $this->assertContains('--alt-' . $boundary . '--', $message); + } + +/** + * testSendAttachment method + * + * @return void + */ + public function testSendAttachment() { + $this->CakeEmail->reset(); + $this->CakeEmail->transport('debug'); + $this->CakeEmail->from('cake@cakephp.org'); + $this->CakeEmail->to(array('you@cakephp.org' => 'You')); + $this->CakeEmail->subject('My title'); + $this->CakeEmail->config(array()); + $this->CakeEmail->attachments(array(CAKE . 'basics.php')); + $result = $this->CakeEmail->send('body'); + $this->assertContains("Content-Type: application/octet-stream\r\nContent-Transfer-Encoding: base64\r\nContent-Disposition: attachment; filename=\"basics.php\"", $result['message']); + + $this->CakeEmail->attachments(array('my.file.txt' => CAKE . 'basics.php')); + $result = $this->CakeEmail->send('body'); + $this->assertContains("Content-Type: application/octet-stream\r\nContent-Transfer-Encoding: base64\r\nContent-Disposition: attachment; filename=\"my.file.txt\"", $result['message']); + + $this->CakeEmail->attachments(array('file.txt' => array('file' => CAKE . 'basics.php', 'mimetype' => 'text/plain'))); + $result = $this->CakeEmail->send('body'); + $this->assertContains("Content-Type: text/plain\r\nContent-Transfer-Encoding: base64\r\nContent-Disposition: attachment; filename=\"file.txt\"", $result['message']); + + $this->CakeEmail->attachments(array('file2.txt' => array('file' => CAKE . 'basics.php', 'mimetype' => 'text/plain', 'contentId' => 'a1b1c1'))); + $result = $this->CakeEmail->send('body'); + $this->assertContains("Content-Type: text/plain\r\nContent-Transfer-Encoding: base64\r\nContent-ID: \r\nContent-Disposition: inline; filename=\"file2.txt\"", $result['message']); + } + +/** + * testDeliver method + * + * @return void + */ + public function testDeliver() { + $instance = CakeEmail::deliver('all@cakephp.org', 'About', 'Everything ok', array('from' => 'root@cakephp.org'), false); + $this->assertInstanceOf('CakeEmail', $instance); + $this->assertSame($instance->to(), array('all@cakephp.org' => 'all@cakephp.org')); + $this->assertSame($instance->subject(), 'About'); + $this->assertSame($instance->from(), array('root@cakephp.org' => 'root@cakephp.org')); + + $config = array( + 'from' => 'cake@cakephp.org', + 'to' => 'debug@cakephp.org', + 'subject' => 'Update ok', + 'template' => 'custom', + 'layout' => 'custom_layout', + 'viewVars' => array('value' => 123), + 'cc' => array('cake@cakephp.org' => 'Myself') + ); + $instance = CakeEmail::deliver(null, null, array('name' => 'CakePHP'), $config, false); + $this->assertSame($instance->from(), array('cake@cakephp.org' => 'cake@cakephp.org')); + $this->assertSame($instance->to(), array('debug@cakephp.org' => 'debug@cakephp.org')); + $this->assertSame($instance->subject(), 'Update ok'); + $this->assertSame($instance->template(), array('template' => 'custom', 'layout' => 'custom_layout')); + $this->assertSame($instance->viewVars(), array('value' => 123, 'name' => 'CakePHP')); + $this->assertSame($instance->cc(), array('cake@cakephp.org' => 'Myself')); + + $configs = array('from' => 'root@cakephp.org', 'message' => 'Message from configs', 'transport' => 'Debug'); + $instance = CakeEmail::deliver('all@cakephp.org', 'About', null, $configs, true); + $message = $instance->message(); + $this->assertEquals($configs['message'], $message[0]); + } + +/** + * testMessage method + * + * @return void + */ + public function testMessage() { + $this->CakeEmail->reset(); + $this->CakeEmail->transport('debug'); + $this->CakeEmail->from('cake@cakephp.org'); + $this->CakeEmail->to(array('you@cakephp.org' => 'You')); + $this->CakeEmail->subject('My title'); + $this->CakeEmail->config(array('empty')); + $this->CakeEmail->template('default', 'default'); + $this->CakeEmail->emailFormat('both'); + $result = $this->CakeEmail->send(); + + $expected = '

This email was sent using the CakePHP Framework

'; + $this->assertContains($expected, $this->CakeEmail->message(CakeEmail::MESSAGE_HTML)); + + $expected = 'This email was sent using the CakePHP Framework, http://cakephp.org.'; + $this->assertContains($expected, $this->CakeEmail->message(CakeEmail::MESSAGE_TEXT)); + + $message = $this->CakeEmail->message(); + $this->assertContains('Content-Type: text/plain; charset=UTF-8', $message); + $this->assertContains('Content-Type: text/html; charset=UTF-8', $message); + + // UTF-8 is 8bit + $this->assertTrue($this->_checkContentTransferEncoding($message, '8bit')); + + $this->CakeEmail->charset = 'ISO-2022-JP'; + $this->CakeEmail->send(); + $message = $this->CakeEmail->message(); + $this->assertContains('Content-Type: text/plain; charset=ISO-2022-JP', $message); + $this->assertContains('Content-Type: text/html; charset=ISO-2022-JP', $message); + + // ISO-2022-JP is 7bit + $this->assertTrue($this->_checkContentTransferEncoding($message, '7bit')); + } + +/** + * testReset method + * + * @return void + */ + public function testReset() { + $this->CakeEmail->to('cake@cakephp.org'); + $this->CakeEmail->theme('TestTheme'); + $this->assertSame($this->CakeEmail->to(), array('cake@cakephp.org' => 'cake@cakephp.org')); + + $this->CakeEmail->reset(); + $this->assertSame($this->CakeEmail->to(), array()); + $this->assertSame(null, $this->CakeEmail->theme()); + } + +/** + * testReset with charset + * + * @return void + */ + public function testResetWithCharset() { + $this->CakeEmail->charset = 'ISO-2022-JP'; + $this->CakeEmail->reset(); + + $this->assertSame($this->CakeEmail->charset, 'utf-8', $this->CakeEmail->charset); + $this->assertSame($this->CakeEmail->headerCharset, null, $this->CakeEmail->headerCharset); + } + +/** + * testWrap method + * + * @return void + */ + public function testWrap() { + $text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ac turpis orci, non commodo odio. Morbi nibh nisi, vehicula pellentesque accumsan amet.'; + $result = $this->CakeEmail->wrap($text); + $expected = array( + 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ac turpis orci,', + 'non commodo odio. Morbi nibh nisi, vehicula pellentesque accumsan amet.', + '' + ); + $this->assertSame($expected, $result); + + $text = 'Lorem ipsum dolor sit amet, consectetur < adipiscing elit. Donec ac turpis orci, non commodo odio. Morbi nibh nisi, vehicula > pellentesque accumsan amet.'; + $result = $this->CakeEmail->wrap($text); + $expected = array( + 'Lorem ipsum dolor sit amet, consectetur < adipiscing elit. Donec ac turpis', + 'orci, non commodo odio. Morbi nibh nisi, vehicula > pellentesque accumsan', + 'amet.', + '' + ); + $this->assertSame($expected, $result); + + $text = '

Lorem ipsum dolor sit amet,
consectetur adipiscing elit.
Donec ac turpis orci, non commodo odio.
Morbi nibh nisi, vehicula pellentesque accumsan amet.


'; + $result = $this->CakeEmail->wrap($text); + $expected = array( + '

Lorem ipsum dolor sit amet,
consectetur adipiscing elit.
Donec ac', + 'turpis orci, non commodo odio.
Morbi nibh nisi, vehicula', + 'pellentesque accumsan amet.


', + '' + ); + $this->assertSame($expected, $result); + + $text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ac turpis orci, non commodo odio. Morbi nibh nisi, vehicula pellentesque accumsan amet.'; + $result = $this->CakeEmail->wrap($text); + $expected = array( + 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ac', + 'turpis orci, non commodo odio. Morbi nibh', + 'nisi, vehicula pellentesque accumsan amet.', + '' + ); + $this->assertSame($expected, $result); + + $text = 'Lorem ipsum ok'; + $result = $this->CakeEmail->wrap($text); + $expected = array( + 'Lorem ipsum', + '', + 'ok', + '' + ); + $this->assertSame($expected, $result); + + $text = 'Lorem ipsum withonewordverybigMorethanthelineshouldsizeofrfcspecificationbyieeeavailableonieeesite ok.'; + $result = $this->CakeEmail->wrap($text); + $expected = array( + 'Lorem ipsum', + 'withonewordverybigMorethanthelineshouldsizeofrfcspecificationbyieeeavailableonieeesite', + 'ok.', + '' + ); + $this->assertSame($expected, $result); + } + +/** + * testConstructWithConfigArray method + * + * @return void + */ + public function testConstructWithConfigArray() { + $configs = array( + 'from' => array('some@example.com' => 'My website'), + 'to' => 'test@example.com', + 'subject' => 'Test mail subject', + 'transport' => 'Debug', + ); + $this->CakeEmail = new CakeEmail($configs); + + $result = $this->CakeEmail->to(); + $this->assertEquals(array($configs['to'] => $configs['to']), $result); + + $result = $this->CakeEmail->from(); + $this->assertEquals($configs['from'], $result); + + $result = $this->CakeEmail->subject(); + $this->assertEquals($configs['subject'], $result); + + $result = $this->CakeEmail->transport(); + $this->assertEquals($configs['transport'], $result); + + $result = $this->CakeEmail->transportClass(); + $this->assertTrue($result instanceof DebugTransport); + + $result = $this->CakeEmail->send('This is the message'); + + $this->assertTrue((bool)strpos($result['headers'], 'Message-ID: ')); + $this->assertTrue((bool)strpos($result['headers'], 'To: ')); + } + +/** + * testConstructWithConfigString method + * + * @return void + */ + public function testConstructWithConfigString() { + $configs = new EmailConfig(); + $this->CakeEmail = new CakeEmail('test'); + + $result = $this->CakeEmail->to(); + $this->assertEquals($configs->test['to'], $result); + + $result = $this->CakeEmail->from(); + $this->assertEquals($configs->test['from'], $result); + + $result = $this->CakeEmail->subject(); + $this->assertEquals($configs->test['subject'], $result); + + $result = $this->CakeEmail->transport(); + $this->assertEquals($configs->test['transport'], $result); + + $result = $this->CakeEmail->transportClass(); + $this->assertTrue($result instanceof DebugTransport); + + $result = $this->CakeEmail->send('This is the message'); + + $this->assertTrue((bool)strpos($result['headers'], 'Message-ID: ')); + $this->assertTrue((bool)strpos($result['headers'], 'To: ')); + } + +/** + * testViewRender method + * + * @return void + */ + public function testViewRender() { + $result = $this->CakeEmail->viewRender(); + $this->assertEquals('View', $result); + + $result = $this->CakeEmail->viewRender('Theme'); + $this->assertInstanceOf('CakeEmail', $result); + + $result = $this->CakeEmail->viewRender(); + $this->assertEquals('Theme', $result); + } + +/** + * testEmailFormat method + * + * @return void + */ + public function testEmailFormat() { + $result = $this->CakeEmail->emailFormat(); + $this->assertEquals('text', $result); + + $result = $this->CakeEmail->emailFormat('html'); + $this->assertInstanceOf('CakeEmail', $result); + + $result = $this->CakeEmail->emailFormat(); + $this->assertEquals('html', $result); + + $this->setExpectedException('SocketException'); + $result = $this->CakeEmail->emailFormat('invalid'); + } + +/** + * Tests that it is possible to add charset configuration to a CakeEmail object + * + * @return void + */ + public function testConfigCharset() { + $email = new CakeEmail(); + $this->assertEquals(Configure::read('App.encoding'), $email->charset); + $this->assertEquals(Configure::read('App.encoding'), $email->headerCharset); + + $email = new CakeEmail(array('charset' => 'iso-2022-jp', 'headerCharset' => 'iso-2022-jp-ms')); + $this->assertEquals('iso-2022-jp', $email->charset); + $this->assertEquals('iso-2022-jp-ms', $email->headerCharset); + + $email = new CakeEmail(array('charset' => 'iso-2022-jp')); + $this->assertEquals('iso-2022-jp', $email->charset); + $this->assertEquals('iso-2022-jp', $email->headerCharset); + + $email = new CakeEmail(array('headerCharset' => 'iso-2022-jp-ms')); + $this->assertEquals(Configure::read('App.encoding'), $email->charset); + $this->assertEquals('iso-2022-jp-ms', $email->headerCharset); + } + +/** + * Tests that the header is encoded using the configured headerCharset + * + * @return void + */ + public function testHeaderEncoding() { + $this->skipIf(!function_exists('mb_convert_encoding')); + $email = new CakeEmail(array('headerCharset' => 'iso-2022-jp-ms', 'transport' => 'Debug')); + $email->subject('あれ?もしかしての前と'); + $headers = $email->getHeaders(array('subject')); + $expected = "?ISO-2022-JP?B?GyRCJCIkbCEpJGIkNyQrJDckRiROQTAkSBsoQg==?="; + $this->assertContains($expected, $headers['Subject']); + + $email->to('someone@example.com')->from('someone@example.com'); + $result = $email->send('ってテーブルを作ってやってたらう'); + $this->assertContains('ってテーブルを作ってやってたらう', $result['message']); + } + +/** + * Tests that the body is encoded using the configured charset + * + * @return void + */ + public function testBodyEncoding() { + $this->skipIf(!function_exists('mb_convert_encoding')); + $email = new CakeEmail(array( + 'charset' => 'iso-2022-jp', + 'headerCharset' => 'iso-2022-jp-ms', + 'transport' => 'Debug' + )); + $email->subject('あれ?もしかしての前と'); + $headers = $email->getHeaders(array('subject')); + $expected = "?ISO-2022-JP?B?GyRCJCIkbCEpJGIkNyQrJDckRiROQTAkSBsoQg==?="; + $this->assertContains($expected, $headers['Subject']); + + $email->to('someone@example.com')->from('someone@example.com'); + $result = $email->send('ってテーブルを作ってやってたらう'); + $this->assertContains('Content-Type: text/plain; charset=ISO-2022-JP', $result['headers']); + $this->assertContains(mb_convert_encoding('ってテーブルを作ってやってたらう','ISO-2022-JP'), $result['message']); + } + +/** + * Tests that the body is encoded using the configured charset (Japanese standard encoding) + * + * @return void + */ + public function testBodyEncodingIso2022Jp() { + $this->skipIf(!function_exists('mb_convert_encoding')); + $email = new CakeEmail(array( + 'charset' => 'iso-2022-jp', + 'headerCharset' => 'iso-2022-jp', + 'transport' => 'Debug' + )); + $email->subject('あれ?もしかしての前と'); + $headers = $email->getHeaders(array('subject')); + $expected = "?ISO-2022-JP?B?GyRCJCIkbCEpJGIkNyQrJDckRiROQTAkSBsoQg==?="; + $this->assertContains($expected, $headers['Subject']); + + $email->to('someone@example.com')->from('someone@example.com'); + $result = $email->send('①㈱'); + $this->assertTextContains("Content-Type: text/plain; charset=ISO-2022-JP", $result['headers']); + $this->assertTextNotContains("Content-Type: text/plain; charset=ISO-2022-JP-MS", $result['headers']); // not charset=iso-2022-jp-ms + $this->assertTextNotContains(mb_convert_encoding('①㈱','ISO-2022-JP-MS'), $result['message']); + } + +/** + * Tests that the body is encoded using the configured charset (Japanese irregular encoding, but sometime use this) + * + * @return void + */ + public function testBodyEncodingIso2022JpMs() { + $this->skipIf(!function_exists('mb_convert_encoding')); + $email = new CakeEmail(array( + 'charset' => 'iso-2022-jp-ms', + 'headerCharset' => 'iso-2022-jp-ms', + 'transport' => 'Debug' + )); + $email->subject('あれ?もしかしての前と'); + $headers = $email->getHeaders(array('subject')); + $expected = "?ISO-2022-JP?B?GyRCJCIkbCEpJGIkNyQrJDckRiROQTAkSBsoQg==?="; + $this->assertContains($expected, $headers['Subject']); + + $email->to('someone@example.com')->from('someone@example.com'); + $result = $email->send('①㈱'); + $this->assertTextContains("Content-Type: text/plain; charset=ISO-2022-JP", $result['headers']); + $this->assertTextNotContains("Content-Type: text/plain; charset=iso-2022-jp-ms", $result['headers']); // not charset=iso-2022-jp-ms + $this->assertContains(mb_convert_encoding('①㈱','ISO-2022-JP-MS'), $result['message']); + } + + protected function _checkContentTransferEncoding($message, $charset) { + $boundary = '--alt-' . $this->CakeEmail->getBoundary(); + $result['text'] = false; + $result['html'] = false; + $length = count($message); + for ($i = 0; $i < $length; ++$i) { + if ($message[$i] == $boundary) { + $flag = false; + $type = ''; + while (!preg_match('/^$/', $message[$i])) { + if (preg_match('/^Content-Type: text\/plain/', $message[$i])) { + $type = 'text'; + } + if (preg_match('/^Content-Type: text\/html/', $message[$i])) { + $type = 'html'; + } + if ($message[$i] === 'Content-Transfer-Encoding: ' . $charset) { + $flag = true; + } + ++$i; + } + $result[$type] = $flag; + } + } + return $result['text'] && $result['html']; + } + +/** + * Test CakeEmail::_encode function + * + * @return void + */ + public function testEncode() { + $this->skipIf(!function_exists('mb_convert_encoding')); + + $this->CakeEmail->headerCharset = 'ISO-2022-JP'; + $result = $this->CakeEmail->encode('日本語'); + $expected = '=?ISO-2022-JP?B?GyRCRnxLXDhsGyhC?='; + $this->assertSame($expected, $result); + + $this->CakeEmail->headerCharset = 'ISO-2022-JP'; + $result = $this->CakeEmail->encode('長い長い長いSubjectの場合はfoldingするのが正しいんだけどいったいどうなるんだろう?'); + $expected = "=?ISO-2022-JP?B?GyRCRDkkJEQ5JCREOSQkGyhCU3ViamVjdBskQiROPmw5ZyRPGyhCZm9s?=\r\n" . + " =?ISO-2022-JP?B?ZGluZxskQiQ5JGskTiQsQDUkNyQkJHMkQCQxJEkkJCRDJD8kJCRJGyhC?=\r\n" . + " =?ISO-2022-JP?B?GyRCJCYkSiRrJHMkQCRtJCYhKRsoQg==?="; + $this->assertSame($expected, $result); + } + +/** + * Tests charset setter/getter + * + * @return void + */ + public function testCharset() { + $this->CakeEmail->charset('UTF-8'); + $this->assertSame($this->CakeEmail->charset(), 'UTF-8'); + + $this->CakeEmail->charset('ISO-2022-JP'); + $this->assertSame($this->CakeEmail->charset(), 'ISO-2022-JP'); + + $charset = $this->CakeEmail->charset('Shift_JIS'); + $this->assertSame($charset, 'Shift_JIS'); + } + +/** + * Tests headerCharset setter/getter + * + * @return void + */ + public function testHeaderCharset() { + $this->CakeEmail->headerCharset('UTF-8'); + $this->assertSame($this->CakeEmail->headerCharset(), 'UTF-8'); + + $this->CakeEmail->headerCharset('ISO-2022-JP'); + $this->assertSame($this->CakeEmail->headerCharset(), 'ISO-2022-JP'); + + $charset = $this->CakeEmail->headerCharset('Shift_JIS'); + $this->assertSame($charset, 'Shift_JIS'); + } + +/** + * Tests for compatible check. + * charset property and charset() method. + * headerCharset property and headerCharset() method. + */ + public function testCharsetsCompatible() { + $this->skipIf(!function_exists('mb_convert_encoding')); + + $checkHeaders = array( + 'from' => true, + 'to' => true, + 'cc' => true, + 'subject' => true, + ); + + // Header Charset : null (used by default UTF-8) + // Body Charset : ISO-2022-JP + $oldStyleEmail = $this->_getEmailByOldStyleCharset('iso-2022-jp', null); + $oldStyleHeaders = $oldStyleEmail->getHeaders($checkHeaders); + + $newStyleEmail = $this->_getEmailByNewStyleCharset('iso-2022-jp', null); + $newStyleHeaders = $newStyleEmail->getHeaders($checkHeaders); + + $this->assertSame($oldStyleHeaders['From'], $newStyleHeaders['From']); + $this->assertSame($oldStyleHeaders['To'], $newStyleHeaders['To']); + $this->assertSame($oldStyleHeaders['Cc'], $newStyleHeaders['Cc']); + $this->assertSame($oldStyleHeaders['Subject'], $newStyleHeaders['Subject']); + + // Header Charset : UTF-8 + // Boby Charset : ISO-2022-JP + $oldStyleEmail = $this->_getEmailByOldStyleCharset('iso-2022-jp', 'utf-8'); + $oldStyleHeaders = $oldStyleEmail->getHeaders($checkHeaders); + + $newStyleEmail = $this->_getEmailByNewStyleCharset('iso-2022-jp', 'utf-8'); + $newStyleHeaders = $newStyleEmail->getHeaders($checkHeaders); + + $this->assertSame($oldStyleHeaders['From'], $newStyleHeaders['From']); + $this->assertSame($oldStyleHeaders['To'], $newStyleHeaders['To']); + $this->assertSame($oldStyleHeaders['Cc'], $newStyleHeaders['Cc']); + $this->assertSame($oldStyleHeaders['Subject'], $newStyleHeaders['Subject']); + + // Header Charset : ISO-2022-JP + // Boby Charset : UTF-8 + $oldStyleEmail = $this->_getEmailByOldStyleCharset('utf-8', 'iso-2022-jp'); + $oldStyleHeaders = $oldStyleEmail->getHeaders($checkHeaders); + + $newStyleEmail = $this->_getEmailByNewStyleCharset('utf-8', 'iso-2022-jp'); + $newStyleHeaders = $newStyleEmail->getHeaders($checkHeaders); + + $this->assertSame($oldStyleHeaders['From'], $newStyleHeaders['From']); + $this->assertSame($oldStyleHeaders['To'], $newStyleHeaders['To']); + $this->assertSame($oldStyleHeaders['Cc'], $newStyleHeaders['Cc']); + $this->assertSame($oldStyleHeaders['Subject'], $newStyleHeaders['Subject']); + } + + protected function _getEmailByOldStyleCharset($charset, $headerCharset) { + $email = new CakeEmail(array('transport' => 'Debug')); + + if (! empty($charset)) { + $email->charset = $charset; + } + if (! empty($headerCharset)) { + $email->headerCharset = $headerCharset; + } + + $email->from('someone@example.com', 'どこかの誰か'); + $email->to('someperson@example.jp', 'どこかのどなたか'); + $email->cc('miku@example.net', 'ミク'); + $email->subject('テストメール'); + $email->send('テストメールの本文'); + + return $email; + } + + protected function _getEmailByNewStyleCharset($charset, $headerCharset) { + $email = new CakeEmail(array('transport' => 'Debug')); + + if (! empty($charset)) { + $email->charset($charset); + } + if (! empty($headerCharset)) { + $email->headerCharset($headerCharset); + } + + $email->from('someone@example.com', 'どこかの誰か'); + $email->to('someperson@example.jp', 'どこかのどなたか'); + $email->cc('miku@example.net', 'ミク'); + $email->subject('テストメール'); + $email->send('テストメールの本文'); + + return $email; + } + +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Network/Email/DebugTransportTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Network/Email/DebugTransportTest.php new file mode 100644 index 0000000..11512fd --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Network/Email/DebugTransportTest.php @@ -0,0 +1,77 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Network.Email + * @since CakePHP(tm) v 2.0.0 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ +App::uses('CakeEmail', 'Network/Email'); +App::uses('AbstractTransport', 'Network/Email'); +App::uses('DebugTransport', 'Network/Email'); + +/** + * Test case + * + */ +class DebugTransportTest extends CakeTestCase { + +/** + * Setup + * + * @return void + */ + public function setUp() { + $this->DebugTransport = new DebugTransport(); + } + +/** + * testSend method + * + * @return void + */ + public function testSend() { + $this->getMock('CakeEmail', array('message'), array(), 'DebugCakeEmail'); + $email = new DebugCakeEmail(); + $email->from('noreply@cakephp.org', 'CakePHP Test'); + $email->to('cake@cakephp.org', 'CakePHP'); + $email->cc(array('mark@cakephp.org' => 'Mark Story', 'juan@cakephp.org' => 'Juan Basso')); + $email->bcc('phpnut@cakephp.org'); + $email->messageID('<4d9946cf-0a44-4907-88fe-1d0ccbdd56cb@localhost>'); + $email->subject('Testing Message'); + $date = date(DATE_RFC2822); + $email->setHeaders(array('X-Mailer' => DebugCakeEmail::EMAIL_CLIENT, 'Date' => $date)); + $email->expects($this->any())->method('message')->will($this->returnValue(array('First Line', 'Second Line', '.Third Line', ''))); + + $headers = "From: CakePHP Test \r\n"; + $headers .= "To: CakePHP \r\n"; + $headers .= "Cc: Mark Story , Juan Basso \r\n"; + $headers .= "X-Mailer: CakePHP Email\r\n"; + $headers .= "Date: " . $date . "\r\n"; + $headers .= "Message-ID: <4d9946cf-0a44-4907-88fe-1d0ccbdd56cb@localhost>\r\n"; + $headers .= "Subject: Testing Message\r\n"; + $headers .= "MIME-Version: 1.0\r\n"; + $headers .= "Content-Type: text/plain; charset=UTF-8\r\n"; + $headers .= "Content-Transfer-Encoding: 8bit"; + + $data = "First Line\r\n"; + $data .= "Second Line\r\n"; + $data .= ".Third Line\r\n"; // Not use 'RFC5321 4.5.2.Transparency' in DebugTransport. + + $result = $this->DebugTransport->send($email); + + $this->assertEquals($headers, $result['headers']); + $this->assertEquals($data, $result['message']); + } + +} \ No newline at end of file diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Network/Email/SmtpTransportTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Network/Email/SmtpTransportTest.php new file mode 100644 index 0000000..0310e53 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Network/Email/SmtpTransportTest.php @@ -0,0 +1,265 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Network.Email + * @since CakePHP(tm) v 2.0.0 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ +App::uses('CakeEmail', 'Network/Email'); +App::uses('AbstractTransport', 'Network/Email'); +App::uses('SmtpTransport', 'Network/Email'); + +/** + * Help to test SmtpTransport + * + */ +class SmtpTestTransport extends SmtpTransport { + +/** + * Helper to change the socket + * + * @param object $socket + * @return void + */ + public function setSocket(CakeSocket $socket) { + $this->_socket = $socket; + } + +/** + * Helper to change the CakeEmail + * + * @param object $cakeEmail + * @return void + */ + public function setCakeEmail($cakeEmail) { + $this->_cakeEmail = $cakeEmail; + } + +/** + * Disabled the socket change + * + * @return void + */ + protected function _generateSocket() { + } + +/** + * Magic function to call protected methods + * + * @param string $method + * @param string $args + * @return mixed + */ + public function __call($method, $args) { + $method = '_' . $method; + return $this->$method(); + } + +} + +/** + * Test case + * + */ +class SmtpTransportTest extends CakeTestCase { + +/** + * Setup + * + * @return void + */ + public function setUp() { + if (!class_exists('MockSocket')) { + $this->getMock('CakeSocket', array('read', 'write', 'connect'), array(), 'MockSocket'); + } + $this->socket = new MockSocket(); + + $this->SmtpTransport = new SmtpTestTransport(); + $this->SmtpTransport->setSocket($this->socket); + $this->SmtpTransport->config(array('client' => 'localhost')); + } + +/** + * testConnectEhlo method + * + * @return void + */ + public function testConnectEhlo() { + $this->socket->expects($this->any())->method('connect')->will($this->returnValue(true)); + $this->socket->expects($this->at(0))->method('read')->will($this->returnValue(false)); + $this->socket->expects($this->at(1))->method('read')->will($this->returnValue("220 Welcome message\r\n")); + $this->socket->expects($this->at(2))->method('write')->with("EHLO localhost\r\n"); + $this->socket->expects($this->at(3))->method('read')->will($this->returnValue(false)); + $this->socket->expects($this->at(4))->method('read')->will($this->returnValue("250 Accepted\r\n")); + $this->SmtpTransport->connect(); + } + +/** + * testConnectHelo method + * + * @return void + */ + public function testConnectHelo() { + $this->socket->expects($this->any())->method('connect')->will($this->returnValue(true)); + $this->socket->expects($this->at(0))->method('read')->will($this->returnValue(false)); + $this->socket->expects($this->at(1))->method('read')->will($this->returnValue("220 Welcome message\r\n")); + $this->socket->expects($this->at(2))->method('write')->with("EHLO localhost\r\n"); + $this->socket->expects($this->at(3))->method('read')->will($this->returnValue(false)); + $this->socket->expects($this->at(4))->method('read')->will($this->returnValue("200 Not Accepted\r\n")); + $this->socket->expects($this->at(5))->method('write')->with("HELO localhost\r\n"); + $this->socket->expects($this->at(6))->method('read')->will($this->returnValue(false)); + $this->socket->expects($this->at(7))->method('read')->will($this->returnValue("250 Accepted\r\n")); + $this->SmtpTransport->connect(); + } + +/** + * testConnectFail method + * + * @expectedException SocketException + * @return void + */ + public function testConnectFail() { + $this->socket->expects($this->any())->method('connect')->will($this->returnValue(true)); + $this->socket->expects($this->at(0))->method('read')->will($this->returnValue(false)); + $this->socket->expects($this->at(1))->method('read')->will($this->returnValue("220 Welcome message\r\n")); + $this->socket->expects($this->at(2))->method('write')->with("EHLO localhost\r\n"); + $this->socket->expects($this->at(3))->method('read')->will($this->returnValue(false)); + $this->socket->expects($this->at(4))->method('read')->will($this->returnValue("200 Not Accepted\r\n")); + $this->socket->expects($this->at(5))->method('write')->with("HELO localhost\r\n"); + $this->socket->expects($this->at(6))->method('read')->will($this->returnValue(false)); + $this->socket->expects($this->at(7))->method('read')->will($this->returnValue("200 Not Accepted\r\n")); + $this->SmtpTransport->connect(); + } + +/** + * testAuth method + * + * @return void + */ + public function testAuth() { + $this->socket->expects($this->at(0))->method('write')->with("AUTH LOGIN\r\n"); + $this->socket->expects($this->at(1))->method('read')->will($this->returnValue(false)); + $this->socket->expects($this->at(2))->method('read')->will($this->returnValue("334 Login\r\n")); + $this->socket->expects($this->at(3))->method('write')->with("bWFyaw==\r\n"); + $this->socket->expects($this->at(4))->method('read')->will($this->returnValue(false)); + $this->socket->expects($this->at(5))->method('read')->will($this->returnValue("334 Pass\r\n")); + $this->socket->expects($this->at(6))->method('write')->with("c3Rvcnk=\r\n"); + $this->socket->expects($this->at(7))->method('read')->will($this->returnValue(false)); + $this->socket->expects($this->at(8))->method('read')->will($this->returnValue("235 OK\r\n")); + $this->SmtpTransport->config(array('username' => 'mark', 'password' => 'story')); + $this->SmtpTransport->auth(); + } + +/** + * testAuthNoAuth method + * + * @return void + */ + public function testAuthNoAuth() { + $this->socket->expects($this->never())->method('write')->with("AUTH LOGIN\r\n"); + $this->SmtpTransport->config(array('username' => null, 'password' => null)); + $this->SmtpTransport->auth(); + } + +/** + * testRcpt method + * + * @return void + */ + public function testRcpt() { + $email = new CakeEmail(); + $email->from('noreply@cakephp.org', 'CakePHP Test'); + $email->to('cake@cakephp.org', 'CakePHP'); + $email->bcc('phpnut@cakephp.org'); + $email->cc(array('mark@cakephp.org' => 'Mark Story', 'juan@cakephp.org' => 'Juan Basso')); + + $this->socket->expects($this->at(0))->method('write')->with("MAIL FROM:\r\n"); + $this->socket->expects($this->at(1))->method('read')->will($this->returnValue(false)); + $this->socket->expects($this->at(2))->method('read')->will($this->returnValue("250 OK\r\n")); + $this->socket->expects($this->at(3))->method('write')->with("RCPT TO:\r\n"); + $this->socket->expects($this->at(4))->method('read')->will($this->returnValue(false)); + $this->socket->expects($this->at(5))->method('read')->will($this->returnValue("250 OK\r\n")); + $this->socket->expects($this->at(6))->method('write')->with("RCPT TO:\r\n"); + $this->socket->expects($this->at(7))->method('read')->will($this->returnValue(false)); + $this->socket->expects($this->at(8))->method('read')->will($this->returnValue("250 OK\r\n")); + $this->socket->expects($this->at(9))->method('write')->with("RCPT TO:\r\n"); + $this->socket->expects($this->at(10))->method('read')->will($this->returnValue(false)); + $this->socket->expects($this->at(11))->method('read')->will($this->returnValue("250 OK\r\n")); + $this->socket->expects($this->at(12))->method('write')->with("RCPT TO:\r\n"); + $this->socket->expects($this->at(13))->method('read')->will($this->returnValue(false)); + $this->socket->expects($this->at(14))->method('read')->will($this->returnValue("250 OK\r\n")); + + $this->SmtpTransport->setCakeEmail($email); + $this->SmtpTransport->sendRcpt(); + } + +/** + * testSendData method + * + * @return void + */ + public function testSendData() { + $this->getMock('CakeEmail', array('message'), array(), 'SmtpCakeEmail'); + $email = new SmtpCakeEmail(); + $email->from('noreply@cakephp.org', 'CakePHP Test'); + $email->returnPath('pleasereply@cakephp.org', 'CakePHP Return'); + $email->to('cake@cakephp.org', 'CakePHP'); + $email->cc(array('mark@cakephp.org' => 'Mark Story', 'juan@cakephp.org' => 'Juan Basso')); + $email->bcc('phpnut@cakephp.org'); + $email->messageID('<4d9946cf-0a44-4907-88fe-1d0ccbdd56cb@localhost>'); + $email->subject('Testing SMTP'); + $date = date(DATE_RFC2822); + $email->setHeaders(array('X-Mailer' => SmtpCakeEmail::EMAIL_CLIENT, 'Date' => $date)); + $email->expects($this->any())->method('message')->will($this->returnValue(array('First Line', 'Second Line', '.Third Line', ''))); + + $data = "From: CakePHP Test \r\n"; + $data .= "Return-Path: CakePHP Return \r\n"; + $data .= "To: CakePHP \r\n"; + $data .= "Cc: Mark Story , Juan Basso \r\n"; + $data .= "X-Mailer: CakePHP Email\r\n"; + $data .= "Date: " . $date . "\r\n"; + $data .= "Message-ID: <4d9946cf-0a44-4907-88fe-1d0ccbdd56cb@localhost>\r\n"; + $data .= "Subject: Testing SMTP\r\n"; + $data .= "MIME-Version: 1.0\r\n"; + $data .= "Content-Type: text/plain; charset=UTF-8\r\n"; + $data .= "Content-Transfer-Encoding: 8bit\r\n"; + $data .= "\r\n"; + $data .= "First Line\r\n"; + $data .= "Second Line\r\n"; + $data .= "..Third Line\r\n"; // RFC5321 4.5.2.Transparency + $data .= "\r\n"; + $data .= "\r\n\r\n.\r\n"; + + $this->socket->expects($this->at(0))->method('write')->with("DATA\r\n"); + $this->socket->expects($this->at(1))->method('read')->will($this->returnValue(false)); + $this->socket->expects($this->at(2))->method('read')->will($this->returnValue("354 OK\r\n")); + $this->socket->expects($this->at(3))->method('write')->with($data); + $this->socket->expects($this->at(4))->method('read')->will($this->returnValue(false)); + $this->socket->expects($this->at(5))->method('read')->will($this->returnValue("250 OK\r\n")); + + $this->SmtpTransport->setCakeEmail($email); + $this->SmtpTransport->sendData(); + } + +/** + * testQuit method + * + * @return void + */ + public function testQuit() { + $this->socket->expects($this->at(0))->method('write')->with("QUIT\r\n"); + $this->SmtpTransport->disconnect(); + } + +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Network/Http/BasicAuthenticationTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Network/Http/BasicAuthenticationTest.php new file mode 100644 index 0000000..6ea7789 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Network/Http/BasicAuthenticationTest.php @@ -0,0 +1,64 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Network.Http + * @since CakePHP(tm) v 2.0.0 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ + +App::uses('HttpSocket', 'Network/Http'); +App::uses('BasicAuthentication', 'Network/Http'); + +/** + * BasicMethodTest class + * + * @package Cake.Test.Case.Network.Http + */ +class BasicAuthenticationTest extends CakeTestCase { + +/** + * testAuthentication method + * + * @return void + */ + public function testAuthentication() { + $http = new HttpSocket(); + $auth = array( + 'method' => 'Basic', + 'user' => 'mark', + 'pass' => 'secret' + ); + + BasicAuthentication::authentication($http, $auth); + $this->assertEquals('Basic bWFyazpzZWNyZXQ=', $http->request['header']['Authorization']); + } + +/** + * testProxyAuthentication method + * + * @return void + */ + public function testProxyAuthentication() { + $http = new HttpSocket(); + $proxy = array( + 'method' => 'Basic', + 'user' => 'mark', + 'pass' => 'secret' + ); + + BasicAuthentication::proxyAuthentication($http, $proxy); + $this->assertEquals('Basic bWFyazpzZWNyZXQ=', $http->request['header']['Proxy-Authorization']); + } + +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Network/Http/DigestAuthenticationTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Network/Http/DigestAuthenticationTest.php new file mode 100644 index 0000000..a03a536 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Network/Http/DigestAuthenticationTest.php @@ -0,0 +1,195 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Network.Http + * @since CakePHP(tm) v 2.0.0 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ + +App::uses('HttpSocket', 'Network/Http'); +App::uses('DigestAuthentication', 'Network/Http'); + +class DigestHttpSocket extends HttpSocket { + +/** + * nextHeader attribute + * + * @var string + */ + public $nextHeader = ''; + +/** + * request method + * + * @param mixed $request + * @return void + */ + public function request($request = array()) { + if ($request === false) { + if (isset($this->response['header']['WWW-Authenticate'])) { + unset($this->response['header']['WWW-Authenticate']); + } + return; + } + $this->response['header']['WWW-Authenticate'] = $this->nextHeader; + } + +} + +/** + * DigestAuthenticationTest class + * + * @package Cake.Test.Case.Network.Http + */ +class DigestAuthenticationTest extends CakeTestCase { + +/** + * Socket property + * + * @var mixed null + */ + public $HttpSocket = null; + +/** + * This function sets up a HttpSocket instance we are going to use for testing + * + * @return void + */ + public function setUp() { + $this->HttpSocket = new DigestHttpSocket(); + $this->HttpSocket->request['method'] = 'GET'; + $this->HttpSocket->request['uri']['path'] = '/'; + } + +/** + * We use this function to clean up after the test case was executed + * + * @return void + */ + public function tearDown() { + unset($this->HttpSocket); + } + +/** + * testBasic method + * + * @return void + */ + public function testBasic() { + $this->HttpSocket->nextHeader = 'Digest realm="The batcave",nonce="4cded326c6c51"'; + $this->assertFalse(isset($this->HttpSocket->request['header']['Authorization'])); + + $auth = array('user' => 'admin', 'pass' => '1234'); + DigestAuthentication::authentication($this->HttpSocket, $auth); + $this->assertTrue(isset($this->HttpSocket->request['header']['Authorization'])); + $this->assertEquals('The batcave', $auth['realm']); + $this->assertEquals('4cded326c6c51', $auth['nonce']); + } + +/** + * testQop method + * + * @return void + */ + public function testQop() { + $this->HttpSocket->nextHeader = 'Digest realm="The batcave",nonce="4cded326c6c51"'; + $auth = array('user' => 'admin', 'pass' => '1234'); + DigestAuthentication::authentication($this->HttpSocket, $auth); + $expected = 'Digest username="admin", realm="The batcave", nonce="4cded326c6c51", uri="/", response="da7e2a46b471d77f70a9bb3698c8902b"'; + $this->assertEquals($expected, $this->HttpSocket->request['header']['Authorization']); + $this->assertFalse(isset($auth['qop'])); + $this->assertFalse(isset($auth['nc'])); + + $this->HttpSocket->nextHeader = 'Digest realm="The batcave",nonce="4cded326c6c51",qop="auth"'; + $auth = array('user' => 'admin', 'pass' => '1234'); + DigestAuthentication::authentication($this->HttpSocket, $auth); + $expected = '@Digest username="admin", realm="The batcave", nonce="4cded326c6c51", uri="/", response="[a-z0-9]{32}", qop="auth", nc=00000001, cnonce="[a-z0-9]+"@'; + $this->assertRegExp($expected, $this->HttpSocket->request['header']['Authorization']); + $this->assertEquals('auth', $auth['qop']); + $this->assertEquals(2, $auth['nc']); + } + +/** + * testOpaque method + * + * @return void + */ + public function testOpaque() { + $this->HttpSocket->nextHeader = 'Digest realm="The batcave",nonce="4cded326c6c51"'; + $auth = array('user' => 'admin', 'pass' => '1234'); + DigestAuthentication::authentication($this->HttpSocket, $auth); + $this->assertFalse(strpos($this->HttpSocket->request['header']['Authorization'], 'opaque="d8ea7aa61a1693024c4cc3a516f49b3c"')); + + $this->HttpSocket->nextHeader = 'Digest realm="The batcave",nonce="4cded326c6c51",opaque="d8ea7aa61a1693024c4cc3a516f49b3c"'; + $auth = array('user' => 'admin', 'pass' => '1234'); + DigestAuthentication::authentication($this->HttpSocket, $auth); + $this->assertTrue(strpos($this->HttpSocket->request['header']['Authorization'], 'opaque="d8ea7aa61a1693024c4cc3a516f49b3c"') > 0); + } + +/** + * testMultipleRequest method + * + * @return void + */ + public function testMultipleRequest() { + $this->HttpSocket->nextHeader = 'Digest realm="The batcave",nonce="4cded326c6c51",qop="auth"'; + $auth = array('user' => 'admin', 'pass' => '1234'); + DigestAuthentication::authentication($this->HttpSocket, $auth); + $this->assertTrue(strpos($this->HttpSocket->request['header']['Authorization'], 'nc=00000001') > 0); + $this->assertEquals(2, $auth['nc']); + + DigestAuthentication::authentication($this->HttpSocket, $auth); + $this->assertTrue(strpos($this->HttpSocket->request['header']['Authorization'], 'nc=00000002') > 0); + $this->assertEquals(3, $auth['nc']); + $responsePos = strpos($this->HttpSocket->request['header']['Authorization'], 'response='); + $response = substr($this->HttpSocket->request['header']['Authorization'], $responsePos + 10, 32); + + $this->HttpSocket->nextHeader = ''; + DigestAuthentication::authentication($this->HttpSocket, $auth); + $this->assertTrue(strpos($this->HttpSocket->request['header']['Authorization'], 'nc=00000003') > 0); + $this->assertEquals(4, $auth['nc']); + $responsePos = strpos($this->HttpSocket->request['header']['Authorization'], 'response='); + $responseB = substr($this->HttpSocket->request['header']['Authorization'], $responsePos + 10, 32); + $this->assertNotEquals($response, $responseB); + } + +/** + * testPathChanged method + * + * @return void + */ + public function testPathChanged() { + $this->HttpSocket->nextHeader = 'Digest realm="The batcave",nonce="4cded326c6c51"'; + $this->HttpSocket->request['uri']['path'] = '/admin'; + $auth = array('user' => 'admin', 'pass' => '1234'); + DigestAuthentication::authentication($this->HttpSocket, $auth); + $responsePos = strpos($this->HttpSocket->request['header']['Authorization'], 'response='); + $response = substr($this->HttpSocket->request['header']['Authorization'], $responsePos + 10, 32); + $this->assertNotEquals('da7e2a46b471d77f70a9bb3698c8902b', $response); + } + +/** + * testNoDigestResponse method + * + * @return void + */ + public function testNoDigestResponse() { + $this->HttpSocket->nextHeader = false; + $this->HttpSocket->request['uri']['path'] = '/admin'; + $auth = array('user' => 'admin', 'pass' => '1234'); + DigestAuthentication::authentication($this->HttpSocket, $auth); + $this->assertFalse(isset($this->HttpSocket->request['header']['Authorization'])); + } + +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Network/Http/HttpResponseTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Network/Http/HttpResponseTest.php new file mode 100644 index 0000000..2f98098 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Network/Http/HttpResponseTest.php @@ -0,0 +1,558 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Network.Http + * @since CakePHP(tm) v 1.2.0.4206 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ + +App::uses('HttpResponse', 'Network/Http'); + +/** + * TestHttpResponse class + * + * @package Cake.Test.Case.Network.Http + */ +class TestHttpResponse extends HttpResponse { + +/** + * Convenience method for testing protected method + * + * @param array $header Header as an indexed array (field => value) + * @return array Parsed header + */ + public function parseHeader($header) { + return parent::_parseHeader($header); + } + +/** + * Convenience method for testing protected method + * + * @param string $body A string containing the body to decode + * @param boolean|string $encoding Can be false in case no encoding is being used, or a string representing the encoding + * @return mixed Array or false + */ + public function decodeBody($body, $encoding = 'chunked') { + return parent::_decodeBody($body, $encoding); + } + +/** + * Convenience method for testing protected method + * + * @param string $body A string containing the chunked body to decode + * @return mixed Array or false + */ + public function decodeChunkedBody($body) { + return parent::_decodeChunkedBody($body); + } + +/** + * Convenience method for testing protected method + * + * @param string $token Token to unescape + * @return string Unescaped token + */ + public function unescapeToken($token, $chars = null) { + return parent::_unescapeToken($token, $chars); + } + +/** + * Convenience method for testing protected method + * + * @param boolean $hex true to get them as HEX values, false otherwise + * @return array Escape chars + */ + public function tokenEscapeChars($hex = true, $chars = null) { + return parent::_tokenEscapeChars($hex, $chars); + } + +} + +/** + * HttpResponseTest class + * + * @package Cake.Test.Case.Network.Http + */ +class HttpResponseTest extends CakeTestCase { + +/** + * This function sets up a HttpResponse + * + * @return void + */ + public function setUp() { + $this->HttpResponse = new TestHttpResponse(); + } + +/** + * testBody + * + * @return void + */ + public function testBody() { + $this->HttpResponse->body = 'testing'; + $this->assertEquals('testing', $this->HttpResponse->body()); + + $this->HttpResponse->body = null; + $this->assertSame($this->HttpResponse->body(), ''); + } + +/** + * testToString + * + * @return void + */ + public function testToString() { + $this->HttpResponse->body = 'other test'; + $this->assertEquals('other test', $this->HttpResponse->body()); + $this->assertEquals('other test', (string)$this->HttpResponse); + $this->assertTrue(strpos($this->HttpResponse, 'test') > 0); + + $this->HttpResponse->body = null; + $this->assertEquals('', (string)$this->HttpResponse); + } + +/** + * testGetHeader + * + * @return void + */ + public function testGetHeader() { + $this->HttpResponse->headers = array( + 'foo' => 'Bar', + 'Some' => 'ok', + 'HeAdEr' => 'value', + 'content-Type' => 'text/plain' + ); + + $this->assertEquals('Bar', $this->HttpResponse->getHeader('foo')); + $this->assertEquals('Bar', $this->HttpResponse->getHeader('Foo')); + $this->assertEquals('Bar', $this->HttpResponse->getHeader('FOO')); + $this->assertEquals('value', $this->HttpResponse->getHeader('header')); + $this->assertEquals('text/plain', $this->HttpResponse->getHeader('Content-Type')); + $this->assertSame($this->HttpResponse->getHeader(0), null); + + $this->assertEquals('Bar', $this->HttpResponse->getHeader('foo', false)); + $this->assertEquals('not from class', $this->HttpResponse->getHeader('foo', array('foo' => 'not from class'))); + } + +/** + * testIsOk + * + * @return void + */ + public function testIsOk() { + $this->HttpResponse->code = 0; + $this->assertFalse($this->HttpResponse->isOk()); + $this->HttpResponse->code = -1; + $this->assertFalse($this->HttpResponse->isOk()); + $this->HttpResponse->code = 201; + $this->assertFalse($this->HttpResponse->isOk()); + $this->HttpResponse->code = 'what?'; + $this->assertFalse($this->HttpResponse->isOk()); + $this->HttpResponse->code = 200; + $this->assertTrue($this->HttpResponse->isOk()); + } + +/** + * testIsRedirect + * + * @return void + */ + public function testIsRedirect() { + $this->HttpResponse->code = 0; + $this->assertFalse($this->HttpResponse->isRedirect()); + $this->HttpResponse->code = -1; + $this->assertFalse($this->HttpResponse->isRedirect()); + $this->HttpResponse->code = 201; + $this->assertFalse($this->HttpResponse->isRedirect()); + $this->HttpResponse->code = 'what?'; + $this->assertFalse($this->HttpResponse->isRedirect()); + $this->HttpResponse->code = 301; + $this->assertFalse($this->HttpResponse->isRedirect()); + $this->HttpResponse->code = 302; + $this->assertFalse($this->HttpResponse->isRedirect()); + $this->HttpResponse->code = 303; + $this->assertFalse($this->HttpResponse->isRedirect()); + $this->HttpResponse->code = 307; + $this->assertFalse($this->HttpResponse->isRedirect()); + $this->HttpResponse->code = 301; + $this->HttpResponse->headers['Location'] = 'http://somewhere/'; + $this->assertTrue($this->HttpResponse->isRedirect()); + $this->HttpResponse->code = 302; + $this->HttpResponse->headers['Location'] = 'http://somewhere/'; + $this->assertTrue($this->HttpResponse->isRedirect()); + $this->HttpResponse->code = 303; + $this->HttpResponse->headers['Location'] = 'http://somewhere/'; + $this->assertTrue($this->HttpResponse->isRedirect()); + $this->HttpResponse->code = 307; + $this->HttpResponse->headers['Location'] = 'http://somewhere/'; + $this->assertTrue($this->HttpResponse->isRedirect()); + } + +/** + * Test that HttpSocket::parseHeader can take apart a given (and valid) $header string and turn it into an array. + * + * @return void + */ + public function testParseHeader() { + $r = $this->HttpResponse->parseHeader(array('foo' => 'Bar', 'fOO-bAr' => 'quux')); + $this->assertEquals(array('foo' => 'Bar', 'fOO-bAr' => 'quux'), $r); + + $r = $this->HttpResponse->parseHeader(true); + $this->assertEquals(false, $r); + + $header = "Host: cakephp.org\t\r\n"; + $r = $this->HttpResponse->parseHeader($header); + $expected = array( + 'Host' => 'cakephp.org' + ); + $this->assertEquals($expected, $r); + + $header = "Date:Sat, 07 Apr 2007 10:10:25 GMT\r\nX-Powered-By: PHP/5.1.2\r\n"; + $r = $this->HttpResponse->parseHeader($header); + $expected = array( + 'Date' => 'Sat, 07 Apr 2007 10:10:25 GMT', + 'X-Powered-By' => 'PHP/5.1.2' + ); + $this->assertEquals($expected, $r); + + $header = "people: Jim,John\r\nfoo-LAND: Bar\r\ncAKe-PHP: rocks\r\n"; + $r = $this->HttpResponse->parseHeader($header); + $expected = array( + 'people' => 'Jim,John', + 'foo-LAND' => 'Bar', + 'cAKe-PHP' => 'rocks' + ); + $this->assertEquals($expected, $r); + + $header = "People: Jim,John,Tim\r\nPeople: Lisa,Tina,Chelsea\r\n"; + $r = $this->HttpResponse->parseHeader($header); + $expected = array( + 'People' => array('Jim,John,Tim', 'Lisa,Tina,Chelsea') + ); + $this->assertEquals($expected, $r); + + $header = "Multi-Line: I am a \r\nmulti line\t\r\nfield value.\r\nSingle-Line: I am not\r\n"; + $r = $this->HttpResponse->parseHeader($header); + $expected = array( + 'Multi-Line' => "I am a\r\nmulti line\r\nfield value.", + 'Single-Line' => 'I am not' + ); + $this->assertEquals($expected, $r); + + $header = "Esc\"@\"ped: value\r\n"; + $r = $this->HttpResponse->parseHeader($header); + $expected = array( + 'Esc@ped' => 'value' + ); + $this->assertEquals($expected, $r); + } + +/** + * testParseResponse method + * + * @return void + */ + public function testParseResponse() { + $tests = array( + 'simple-request' => array( + 'response' => array( + 'status-line' => "HTTP/1.x 200 OK\r\n", + 'header' => "Date: Mon, 16 Apr 2007 04:14:16 GMT\r\nServer: CakeHttp Server\r\n", + 'body' => "

Hello World

\r\n

It's good to be html

" + ), + 'expectations' => array( + 'httpVersion' => 'HTTP/1.x', + 'code' => 200, + 'reasonPhrase' => 'OK', + 'headers' => array('Date' => 'Mon, 16 Apr 2007 04:14:16 GMT', 'Server' => 'CakeHttp Server'), + 'body' => "

Hello World

\r\n

It's good to be html

" + ) + ), + 'no-header' => array( + 'response' => array( + 'status-line' => "HTTP/1.x 404 OK\r\n", + 'header' => null + ), + 'expectations' => array( + 'code' => 404, + 'headers' => array() + ) + ) + ); + + $testResponse = array(); + $expectations = array(); + + foreach ($tests as $name => $test) { + $testResponse = array_merge($testResponse, $test['response']); + $testResponse['response'] = $testResponse['status-line'] . $testResponse['header'] . "\r\n" . $testResponse['body']; + $this->HttpResponse->parseResponse($testResponse['response']); + $expectations = array_merge($expectations, $test['expectations']); + + foreach ($expectations as $property => $expectedVal) { + $this->assertEquals($expectedVal, $this->HttpResponse->{$property}, 'Test "' . $name . '": response.' . $property . ' - %s'); + } + + foreach (array('status-line', 'header', 'body', 'response') as $field) { + $this->assertEquals($this->HttpResponse['raw'][$field], $testResponse[$field], 'Test response.raw.' . $field . ': %s'); + } + } + } + +/** + * data provider function for testInvalidParseResponseData + * + * @return array + */ + public static function invalidParseResponseDataProvider() { + return array( + array(array('foo' => 'bar')), + array(true), + array("HTTP Foo\r\nBar: La"), + array('HTTP/1.1 TEST ERROR') + ); + } + +/** + * testInvalidParseResponseData + * + * @dataProvider invalidParseResponseDataProvider + * @expectedException SocketException + * return void + */ + public function testInvalidParseResponseData($value) { + $this->HttpResponse->parseResponse($value); + } + +/** + * testDecodeBody method + * + * @return void + */ + public function testDecodeBody() { + $r = $this->HttpResponse->decodeBody(true); + $this->assertEquals(false, $r); + + $r = $this->HttpResponse->decodeBody('Foobar', false); + $this->assertEquals(array('body' => 'Foobar', 'header' => false), $r); + + $encoding = 'chunked'; + $sample = array( + 'encoded' => "19\r\nThis is a chunked message\r\n0\r\n", + 'decoded' => array('body' => "This is a chunked message", 'header' => false) + ); + + $r = $this->HttpResponse->decodeBody($sample['encoded'], $encoding); + $this->assertEquals($r, $sample['decoded']); + + $encoding = 'chunked'; + $sample = array( + 'encoded' => "19\nThis is a chunked message\r\n0\n", + 'decoded' => array('body' => "This is a chunked message", 'header' => false) + ); + + $r = $this->HttpResponse->decodeBody($sample['encoded'], $encoding); + $this->assertEquals($r, $sample['decoded'], 'Inconsistent line terminators should be tolerated.'); + } + +/** + * testDecodeFooCoded + * + * @return void + */ + public function testDecodeFooCoded() { + $r = $this->HttpResponse->decodeBody(true); + $this->assertEquals(false, $r); + + $r = $this->HttpResponse->decodeBody('Foobar', false); + $this->assertEquals(array('body' => 'Foobar', 'header' => false), $r); + + $encoding = 'foo-bar'; + $sample = array( + 'encoded' => '!Foobar!', + 'decoded' => array('body' => '!Foobar!', 'header' => false), + ); + + $r = $this->HttpResponse->decodeBody($sample['encoded'], $encoding); + $this->assertEquals($r, $sample['decoded']); + } + +/** + * testDecodeChunkedBody method + * + * @return void + */ + public function testDecodeChunkedBody() { + $r = $this->HttpResponse->decodeChunkedBody(true); + $this->assertEquals(false, $r); + + $encoded = "19\r\nThis is a chunked message\r\n0\r\n"; + $decoded = "This is a chunked message"; + $r = $this->HttpResponse->decodeChunkedBody($encoded); + $this->assertEquals($r['body'], $decoded); + $this->assertEquals(false, $r['header']); + + $encoded = "19 \r\nThis is a chunked message\r\n0\r\n"; + $r = $this->HttpResponse->decodeChunkedBody($encoded); + $this->assertEquals($r['body'], $decoded); + + $encoded = "19\r\nThis is a chunked message\r\nE\r\n\nThat is cool\n\r\n0\r\n"; + $decoded = "This is a chunked message\nThat is cool\n"; + $r = $this->HttpResponse->decodeChunkedBody($encoded); + $this->assertEquals($r['body'], $decoded); + $this->assertEquals(false, $r['header']); + + $encoded = "19\r\nThis is a chunked message\r\nE;foo-chunk=5\r\n\nThat is cool\n\r\n0\r\n"; + $r = $this->HttpResponse->decodeChunkedBody($encoded); + $this->assertEquals($r['body'], $decoded); + $this->assertEquals(false, $r['header']); + + $encoded = "19\r\nThis is a chunked message\r\nE\r\n\nThat is cool\n\r\n0\r\nfoo-header: bar\r\ncake: PHP\r\n\r\n"; + $r = $this->HttpResponse->decodeChunkedBody($encoded); + $this->assertEquals($r['body'], $decoded); + $this->assertEquals(array('foo-header' => 'bar', 'cake' => 'PHP'), $r['header']); + } + +/** + * testDecodeChunkedBodyError method + * + * @expectedException SocketException + * @return void + */ + public function testDecodeChunkedBodyError() { + $encoded = "19\r\nThis is a chunked message\r\nE\r\n\nThat is cool\n\r\n"; + $r = $this->HttpResponse->decodeChunkedBody($encoded); + } + +/** + * testParseCookies method + * + * @return void + */ + public function testParseCookies() { + $header = array( + 'Set-Cookie' => array( + 'foo=bar', + 'people=jim,jack,johnny";";Path=/accounts', + 'google=not=nice' + ), + 'Transfer-Encoding' => 'chunked', + 'Date' => 'Sun, 18 Nov 2007 18:57:42 GMT', + ); + $cookies = $this->HttpResponse->parseCookies($header); + $expected = array( + 'foo' => array( + 'value' => 'bar' + ), + 'people' => array( + 'value' => 'jim,jack,johnny";"', + 'path' => '/accounts', + ), + 'google' => array( + 'value' => 'not=nice', + ) + ); + $this->assertEquals($expected, $cookies); + + $header['Set-Cookie'][] = 'cakephp=great; Secure'; + $expected['cakephp'] = array('value' => 'great', 'secure' => true); + $cookies = $this->HttpResponse->parseCookies($header); + $this->assertEquals($expected, $cookies); + + $header['Set-Cookie'] = 'foo=bar'; + unset($expected['people'], $expected['cakephp'], $expected['google']); + $cookies = $this->HttpResponse->parseCookies($header); + $this->assertEquals($expected, $cookies); + } + +/** + * Test that escaped token strings are properly unescaped by HttpSocket::unescapeToken + * + * @return void + */ + public function testUnescapeToken() { + $this->assertEquals('Foo', $this->HttpResponse->unescapeToken('Foo')); + + $escape = $this->HttpResponse->tokenEscapeChars(false); + foreach ($escape as $char) { + $token = 'My-special-"' . $char . '"-Token'; + $unescapedToken = $this->HttpResponse->unescapeToken($token); + $expectedToken = 'My-special-' . $char . '-Token'; + + $this->assertEquals($expectedToken, $unescapedToken, 'Test token unescaping for ASCII ' . ord($char)); + } + + $token = 'Extreme-":"Token-" "-""""@"-test'; + $escapedToken = $this->HttpResponse->unescapeToken($token); + $expectedToken = 'Extreme-:Token- -"@-test'; + $this->assertEquals($expectedToken, $escapedToken); + } + +/** + * testArrayAccess + * + * @return void + */ + public function testArrayAccess() { + $this->HttpResponse->httpVersion = 'HTTP/1.1'; + $this->HttpResponse->code = 200; + $this->HttpResponse->reasonPhrase = 'OK'; + $this->HttpResponse->headers = array( + 'Server' => 'CakePHP', + 'ContEnt-Type' => 'text/plain' + ); + $this->HttpResponse->cookies = array( + 'foo' => array('value' => 'bar'), + 'bar' => array('value' => 'foo') + ); + $this->HttpResponse->body = 'This is a test!'; + $this->HttpResponse->raw = "HTTP/1.1 200 OK\r\nServer: CakePHP\r\nContEnt-Type: text/plain\r\n\r\nThis is a test!"; + $expectedOne = "HTTP/1.1 200 OK\r\n"; + $this->assertEquals($expectedOne, $this->HttpResponse['raw']['status-line']); + $expectedTwo = "Server: CakePHP\r\nContEnt-Type: text/plain\r\n"; + $this->assertEquals($expectedTwo, $this->HttpResponse['raw']['header']); + $expectedThree = 'This is a test!'; + $this->assertEquals($expectedThree, $this->HttpResponse['raw']['body']); + $expected = $expectedOne . $expectedTwo . "\r\n" . $expectedThree; + $this->assertEquals($expected, $this->HttpResponse['raw']['response']); + + $expected = 'HTTP/1.1'; + $this->assertEquals($expected, $this->HttpResponse['status']['http-version']); + $expected = 200; + $this->assertEquals($expected, $this->HttpResponse['status']['code']); + $expected = 'OK'; + $this->assertEquals($expected, $this->HttpResponse['status']['reason-phrase']); + + $expected = array( + 'Server' => 'CakePHP', + 'ContEnt-Type' => 'text/plain' + ); + $this->assertEquals($expected, $this->HttpResponse['header']); + + $expected = 'This is a test!'; + $this->assertEquals($expected, $this->HttpResponse['body']); + + $expected = array( + 'foo' => array('value' => 'bar'), + 'bar' => array('value' => 'foo') + ); + $this->assertEquals($expected, $this->HttpResponse['cookies']); + + $this->HttpResponse->raw = "HTTP/1.1 200 OK\r\n\r\nThis is a test!"; + $this->assertSame($this->HttpResponse['raw']['header'], null); + } + +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Network/Http/HttpSocketTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Network/Http/HttpSocketTest.php new file mode 100644 index 0000000..dfd7db9 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Network/Http/HttpSocketTest.php @@ -0,0 +1,1629 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Network.Http + * @since CakePHP(tm) v 1.2.0.4206 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ + +App::uses('HttpSocket', 'Network/Http'); +App::uses('HttpResponse', 'Network/Http'); + +/** + * TestAuthentication class + * + * @package Cake.Test.Case.Network.Http + * @package Cake.Test.Case.Network.Http + */ +class TestAuthentication { + +/** + * authentication method + * + * @param HttpSocket $http + * @param array $authInfo + * @return void + */ + public static function authentication(HttpSocket $http, &$authInfo) { + $http->request['header']['Authorization'] = 'Test ' . $authInfo['user'] . '.' . $authInfo['pass']; + } + +/** + * proxyAuthentication method + * + * @param HttpSocket $http + * @param array $proxyInfo + * @return void + */ + public static function proxyAuthentication(HttpSocket $http, &$proxyInfo) { + $http->request['header']['Proxy-Authorization'] = 'Test ' . $proxyInfo['user'] . '.' . $proxyInfo['pass']; + } + +} + +/** + * CustomResponse + * + */ +class CustomResponse { + +/** + * First 10 chars + * + * @var string + */ + public $first10; + +/** + * Constructor + * + */ + public function __construct($message) { + $this->first10 = substr($message, 0, 10); + } + +} + +/** + * TestHttpSocket + * + */ +class TestHttpSocket extends HttpSocket { + +/** + * Convenience method for testing protected method + * + * @param string|array $uri URI (see {@link _parseUri()}) + * @return array Current configuration settings + */ + public function configUri($uri = null) { + return parent::_configUri($uri); + } + +/** + * Convenience method for testing protected method + * + * @param string|array $uri URI to parse + * @param boolean|array $base If true use default URI config, otherwise indexed array to set 'scheme', 'host', 'port', etc. + * @return array Parsed URI + */ + public function parseUri($uri = null, $base = array()) { + return parent::_parseUri($uri, $base); + } + +/** + * Convenience method for testing protected method + * + * @param array $uri A $uri array, or uses $this->config if left empty + * @param string $uriTemplate The Uri template/format to use + * @return string A fully qualified URL formatted according to $uriTemplate + */ + public function buildUri($uri = array(), $uriTemplate = '%scheme://%user:%pass@%host:%port/%path?%query#%fragment') { + return parent::_buildUri($uri, $uriTemplate); + } + +/** + * Convenience method for testing protected method + * + * @param array $header Header to build + * @return string Header built from array + */ + public function buildHeader($header, $mode = 'standard') { + return parent::_buildHeader($header, $mode); + } + +/** + * Convenience method for testing protected method + * + * @param string|array $query A query string to parse into an array or an array to return directly "as is" + * @return array The $query parsed into a possibly multi-level array. If an empty $query is given, an empty array is returned. + */ + public function parseQuery($query) { + return parent::_parseQuery($query); + } + +/** + * Convenience method for testing protected method + * + * @param array $request Needs to contain a 'uri' key. Should also contain a 'method' key, otherwise defaults to GET. + * @param string $versionToken The version token to use, defaults to HTTP/1.1 + * @return string Request line + */ + public function buildRequestLine($request = array(), $versionToken = 'HTTP/1.1') { + return parent::_buildRequestLine($request, $versionToken); + } + +/** + * Convenience method for testing protected method + * + * @param boolean $hex true to get them as HEX values, false otherwise + * @return array Escape chars + */ + public function tokenEscapeChars($hex = true, $chars = null) { + return parent::_tokenEscapeChars($hex, $chars); + } + +/** + * Convenience method for testing protected method + * + * @param string $token Token to escape + * @return string Escaped token + */ + public function escapeToken($token, $chars = null) { + return parent::_escapeToken($token, $chars); + } + +} + +/** + * HttpSocketTest class + * + * @package Cake.Test.Case.Network.Http + */ +class HttpSocketTest extends CakeTestCase { + +/** + * Socket property + * + * @var mixed null + */ + public $Socket = null; + +/** + * RequestSocket property + * + * @var mixed null + */ + public $RequestSocket = null; + +/** + * This function sets up a TestHttpSocket instance we are going to use for testing + * + * @return void + */ + public function setUp() { + if (!class_exists('MockHttpSocket')) { + $this->getMock('TestHttpSocket', array('read', 'write', 'connect'), array(), 'MockHttpSocket'); + $this->getMock('TestHttpSocket', array('read', 'write', 'connect', 'request'), array(), 'MockHttpSocketRequests'); + } + + $this->Socket = new MockHttpSocket(); + $this->RequestSocket = new MockHttpSocketRequests(); + } + +/** + * We use this function to clean up after the test case was executed + * + * @return void + */ + public function tearDown() { + unset($this->Socket, $this->RequestSocket); + } + +/** + * Test that HttpSocket::__construct does what one would expect it to do + * + * @return void + */ + public function testConstruct() { + $this->Socket->reset(); + $baseConfig = $this->Socket->config; + $this->Socket->expects($this->never())->method('connect'); + $this->Socket->__construct(array('host' => 'foo-bar')); + $baseConfig['host'] = 'foo-bar'; + $baseConfig['protocol'] = getprotobyname($baseConfig['protocol']); + $this->assertEquals($this->Socket->config, $baseConfig); + + $this->Socket->reset(); + $baseConfig = $this->Socket->config; + $this->Socket->__construct('http://www.cakephp.org:23/'); + $baseConfig['host'] = $baseConfig['request']['uri']['host'] = 'www.cakephp.org'; + $baseConfig['port'] = $baseConfig['request']['uri']['port'] = 23; + $baseConfig['request']['uri']['scheme'] = 'http'; + $baseConfig['protocol'] = getprotobyname($baseConfig['protocol']); + $this->assertEquals($this->Socket->config, $baseConfig); + + $this->Socket->reset(); + $this->Socket->__construct(array('request' => array('uri' => 'http://www.cakephp.org:23/'))); + $this->assertEquals($this->Socket->config, $baseConfig); + } + +/** + * Test that HttpSocket::configUri works properly with different types of arguments + * + * @return void + */ + public function testConfigUri() { + $this->Socket->reset(); + $r = $this->Socket->configUri('https://bob:secret@www.cakephp.org:23/?query=foo'); + $expected = array( + 'persistent' => false, + 'host' => 'www.cakephp.org', + 'protocol' => 'tcp', + 'port' => 23, + 'timeout' => 30, + 'request' => array( + 'uri' => array( + 'scheme' => 'https', + 'host' => 'www.cakephp.org', + 'port' => 23 + ), + 'redirect' => false, + 'cookies' => array() + ) + ); + $this->assertEquals($expected, $this->Socket->config); + $this->assertTrue($r); + $r = $this->Socket->configUri(array('host' => 'www.foo-bar.org')); + $expected['host'] = 'www.foo-bar.org'; + $expected['request']['uri']['host'] = 'www.foo-bar.org'; + $this->assertEquals($expected, $this->Socket->config); + $this->assertTrue($r); + + $r = $this->Socket->configUri('http://www.foo.com'); + $expected = array( + 'persistent' => false, + 'host' => 'www.foo.com', + 'protocol' => 'tcp', + 'port' => 80, + 'timeout' => 30, + 'request' => array( + 'uri' => array( + 'scheme' => 'http', + 'host' => 'www.foo.com', + 'port' => 80 + ), + 'redirect' => false, + 'cookies' => array() + ) + ); + $this->assertEquals($expected, $this->Socket->config); + $this->assertTrue($r); + + $r = $this->Socket->configUri('/this-is-broken'); + $this->assertEquals($expected, $this->Socket->config); + $this->assertFalse($r); + + $r = $this->Socket->configUri(false); + $this->assertEquals($expected, $this->Socket->config); + $this->assertFalse($r); + } + +/** + * Tests that HttpSocket::request (the heart of the HttpSocket) is working properly. + * + * @return void + */ + public function testRequest() { + $this->Socket->reset(); + + $response = $this->Socket->request(true); + $this->assertFalse($response); + + $tests = array( + array( + 'request' => 'http://www.cakephp.org/?foo=bar', + 'expectation' => array( + 'config' => array( + 'persistent' => false, + 'host' => 'www.cakephp.org', + 'protocol' => 'tcp', + 'port' => 80, + 'timeout' => 30, + 'request' => array( + 'uri' => array( + 'scheme' => 'http', + 'host' => 'www.cakephp.org', + 'port' => 80 + ), + 'redirect' => false, + 'cookies' => array() + ) + ), + 'request' => array( + 'method' => 'GET', + 'uri' => array( + 'scheme' => 'http', + 'host' => 'www.cakephp.org', + 'port' => 80, + 'user' => null, + 'pass' => null, + 'path' => '/', + 'query' => array('foo' => 'bar'), + 'fragment' => null + ), + 'version' => '1.1', + 'body' => '', + 'line' => "GET /?foo=bar HTTP/1.1\r\n", + 'header' => "Host: www.cakephp.org\r\nConnection: close\r\nUser-Agent: CakePHP\r\n", + 'raw' => "", + 'redirect' => false, + 'cookies' => array(), + 'proxy' => array(), + 'auth' => array() + ) + ) + ), + array( + 'request' => array( + 'uri' => array( + 'host' => 'www.cakephp.org', + 'query' => '?foo=bar' + ) + ) + ), + array( + 'request' => 'www.cakephp.org/?foo=bar' + ), + array( + 'request' => array( + 'host' => '192.168.0.1', + 'uri' => 'http://www.cakephp.org/?foo=bar' + ), + 'expectation' => array( + 'request' => array( + 'uri' => array('host' => 'www.cakephp.org') + ), + 'config' => array( + 'request' => array( + 'uri' => array('host' => 'www.cakephp.org') + ), + 'host' => '192.168.0.1' + ) + ) + ), + 'reset4' => array( + 'request.uri.query' => array() + ), + array( + 'request' => array( + 'header' => array('Foo@woo' => 'bar-value') + ), + 'expectation' => array( + 'request' => array( + 'header' => "Host: www.cakephp.org\r\nConnection: close\r\nUser-Agent: CakePHP\r\nFoo\"@\"woo: bar-value\r\n", + 'line' => "GET / HTTP/1.1\r\n" + ) + ) + ), + array( + 'request' => array('header' => array('Foo@woo' => 'bar-value', 'host' => 'foo.com'), 'uri' => 'http://www.cakephp.org/'), + 'expectation' => array( + 'request' => array( + 'header' => "Host: foo.com\r\nConnection: close\r\nUser-Agent: CakePHP\r\nFoo\"@\"woo: bar-value\r\n" + ), + 'config' => array( + 'host' => 'www.cakephp.org' + ) + ) + ), + array( + 'request' => array('header' => "Foo: bar\r\n"), + 'expectation' => array( + 'request' => array( + 'header' => "Foo: bar\r\n" + ) + ) + ), + array( + 'request' => array('header' => "Foo: bar\r\n", 'uri' => 'http://www.cakephp.org/search?q=http_socket#ignore-me'), + 'expectation' => array( + 'request' => array( + 'uri' => array( + 'path' => '/search', + 'query' => array('q' => 'http_socket'), + 'fragment' => 'ignore-me' + ), + 'line' => "GET /search?q=http_socket HTTP/1.1\r\n" + ) + ) + ), + 'reset8' => array( + 'request.uri.query' => array() + ), + array( + 'request' => array( + 'method' => 'POST', + 'uri' => 'http://www.cakephp.org/posts/add', + 'body' => array( + 'name' => 'HttpSocket-is-released', + 'date' => 'today' + ) + ), + 'expectation' => array( + 'request' => array( + 'method' => 'POST', + 'uri' => array( + 'path' => '/posts/add', + 'fragment' => null + ), + 'body' => "name=HttpSocket-is-released&date=today", + 'line' => "POST /posts/add HTTP/1.1\r\n", + 'header' => "Host: www.cakephp.org\r\nConnection: close\r\nUser-Agent: CakePHP\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: 38\r\n", + 'raw' => "name=HttpSocket-is-released&date=today" + ) + ) + ), + array( + 'request' => array( + 'method' => 'POST', + 'uri' => 'http://www.cakephp.org:8080/posts/add', + 'body' => array( + 'name' => 'HttpSocket-is-released', + 'date' => 'today' + ) + ), + 'expectation' => array( + 'config' => array( + 'port' => 8080, + 'request' => array( + 'uri' => array( + 'port' => 8080 + ) + ) + ), + 'request' => array( + 'uri' => array( + 'port' => 8080 + ), + 'header' => "Host: www.cakephp.org:8080\r\nConnection: close\r\nUser-Agent: CakePHP\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: 38\r\n" + ) + ) + ), + array( + 'request' => array( + 'method' => 'POST', + 'uri' => 'https://www.cakephp.org/posts/add', + 'body' => array( + 'name' => 'HttpSocket-is-released', + 'date' => 'today' + ) + ), + 'expectation' => array( + 'config' => array( + 'port' => 443, + 'request' => array( + 'uri' => array( + 'scheme' => 'https', + 'port' => 443 + ) + ) + ), + 'request' => array( + 'uri' => array( + 'scheme' => 'https', + 'port' => 443 + ), + 'header' => "Host: www.cakephp.org\r\nConnection: close\r\nUser-Agent: CakePHP\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: 38\r\n" + ) + ) + ), + array( + 'request' => array( + 'method' => 'POST', + 'uri' => 'https://www.cakephp.org/posts/add', + 'body' => array('name' => 'HttpSocket-is-released', 'date' => 'today'), + 'cookies' => array('foo' => array('value' => 'bar')) + ), + 'expectation' => array( + 'request' => array( + 'header' => "Host: www.cakephp.org\r\nConnection: close\r\nUser-Agent: CakePHP\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: 38\r\nCookie: foo=bar\r\n", + 'cookies' => array( + 'foo' => array('value' => 'bar'), + ) + ) + ) + ) + ); + + $expectation = array(); + foreach ($tests as $i => $test) { + if (strpos($i, 'reset') === 0) { + foreach ($test as $path => $val) { + $expectation = Hash::insert($expectation, $path, $val); + } + continue; + } + + if (isset($test['expectation'])) { + $expectation = Hash::merge($expectation, $test['expectation']); + } + $this->Socket->request($test['request']); + + $raw = $expectation['request']['raw']; + $expectation['request']['raw'] = $expectation['request']['line'] . $expectation['request']['header'] . "\r\n" . $raw; + + $r = array('config' => $this->Socket->config, 'request' => $this->Socket->request); + $v = $this->assertEquals($r, $expectation, 'Failed test #' . $i . ' '); + $expectation['request']['raw'] = $raw; + } + + $this->Socket->reset(); + $request = array('method' => 'POST', 'uri' => 'http://www.cakephp.org/posts/add', 'body' => array('name' => 'HttpSocket-is-released', 'date' => 'today')); + $response = $this->Socket->request($request); + $this->assertEquals("name=HttpSocket-is-released&date=today", $this->Socket->request['body']); + } + +/** + * Test the scheme + port keys + * + * @return void + */ + public function testGetWithSchemeAndPort() { + $this->Socket->reset(); + $request = array( + 'uri' => array( + 'scheme' => 'http', + 'host' => 'cakephp.org', + 'port' => 8080, + 'path' => '/', + ), + 'method' => 'GET' + ); + $response = $this->Socket->request($request); + $this->assertContains('Host: cakephp.org:8080', $this->Socket->request['header']); + } + +/** + * Test urls like http://cakephp.org/index.php?somestring without key/value pair for query + * + * @return void + */ + public function testRequestWithStringQuery() { + $this->Socket->reset(); + $request = array( + 'uri' => array( + 'scheme' => 'http', + 'host' => 'cakephp.org', + 'path' => 'index.php', + 'query' => 'somestring' + ), + 'method' => 'GET' + ); + $response = $this->Socket->request($request); + $this->assertContains("GET /index.php?somestring HTTP/1.1", $this->Socket->request['line']); + } + +/** + * The "*" asterisk character is only allowed for the following methods: OPTIONS. + * + * @expectedException SocketException + * @return void + */ + public function testRequestNotAllowedUri() { + $this->Socket->reset(); + $request = array('uri' => '*', 'method' => 'GET'); + $response = $this->Socket->request($request); + } + +/** + * testRequest2 method + * + * @return void + */ + public function testRequest2() { + $this->Socket->reset(); + $request = array('uri' => 'htpp://www.cakephp.org/'); + $number = mt_rand(0, 9999999); + $this->Socket->expects($this->once())->method('connect')->will($this->returnValue(true)); + $serverResponse = "HTTP/1.x 200 OK\r\nDate: Mon, 16 Apr 2007 04:14:16 GMT\r\nServer: CakeHttp Server\r\nContent-Type: text/html\r\n\r\n

Hello, your lucky number is " . $number . "

"; + $this->Socket->expects($this->at(0))->method('read')->will($this->returnValue(false)); + $this->Socket->expects($this->at(1))->method('read')->will($this->returnValue($serverResponse)); + $this->Socket->expects($this->once())->method('write') + ->with("GET / HTTP/1.1\r\nHost: www.cakephp.org\r\nConnection: close\r\nUser-Agent: CakePHP\r\n\r\n"); + $response = (string)$this->Socket->request($request); + $this->assertEquals($response, "

Hello, your lucky number is " . $number . "

"); + } + +/** + * testRequest3 method + * + * @return void + */ + public function testRequest3() { + $request = array('uri' => 'htpp://www.cakephp.org/'); + $serverResponse = "HTTP/1.x 200 OK\r\nSet-Cookie: foo=bar\r\nDate: Mon, 16 Apr 2007 04:14:16 GMT\r\nServer: CakeHttp Server\r\nContent-Type: text/html\r\n\r\n

This is a cookie test!

"; + $this->Socket->expects($this->at(1))->method('read')->will($this->returnValue($serverResponse)); + $this->Socket->connected = true; + $this->Socket->request($request); + $result = $this->Socket->response['cookies']; + $expect = array( + 'foo' => array( + 'value' => 'bar' + ) + ); + $this->assertEquals($expect, $result); + $this->assertEquals($this->Socket->config['request']['cookies']['www.cakephp.org'], $expect); + $this->assertFalse($this->Socket->connected); + } + +/** + * testRequestWithConstructor method + * + * @return void + */ + public function testRequestWithConstructor() { + $request = array( + 'request' => array( + 'uri' => array( + 'scheme' => 'http', + 'host' => 'localhost', + 'port' => '5984', + 'user' => null, + 'pass' => null + ) + ) + ); + $http = new MockHttpSocketRequests($request); + + $expected = array('method' => 'GET', 'uri' => '/_test'); + $http->expects($this->at(0))->method('request')->with($expected); + $http->get('/_test'); + + $expected = array('method' => 'GET', 'uri' => 'http://localhost:5984/_test?count=4'); + $http->expects($this->at(0))->method('request')->with($expected); + $http->get('/_test', array('count' => 4)); + } + +/** + * testRequestWithResource + * + * @return void + */ + public function testRequestWithResource() { + $serverResponse = "HTTP/1.x 200 OK\r\nDate: Mon, 16 Apr 2007 04:14:16 GMT\r\nServer: CakeHttp Server\r\nContent-Type: text/html\r\n\r\n

This is a test!

"; + $this->Socket->expects($this->at(1))->method('read')->will($this->returnValue($serverResponse)); + $this->Socket->expects($this->at(2))->method('read')->will($this->returnValue(false)); + $this->Socket->expects($this->at(4))->method('read')->will($this->returnValue($serverResponse)); + $this->Socket->connected = true; + + $f = fopen(TMP . 'download.txt', 'w'); + if (!$f) { + $this->markTestSkipped('Can not write in TMP directory.'); + } + + $this->Socket->setContentResource($f); + $result = (string)$this->Socket->request('http://www.cakephp.org/'); + $this->assertEquals('', $result); + $this->assertEquals('CakeHttp Server', $this->Socket->response['header']['Server']); + fclose($f); + $this->assertEquals(file_get_contents(TMP . 'download.txt'), '

This is a test!

'); + unlink(TMP . 'download.txt'); + + $this->Socket->setContentResource(false); + $result = (string)$this->Socket->request('http://www.cakephp.org/'); + $this->assertEquals('

This is a test!

', $result); + } + +/** + * testRequestWithCrossCookie + * + * @return void + */ + public function testRequestWithCrossCookie() { + $this->Socket->connected = true; + $this->Socket->config['request']['cookies'] = array(); + + $serverResponse = "HTTP/1.x 200 OK\r\nSet-Cookie: foo=bar\r\nDate: Mon, 16 Apr 2007 04:14:16 GMT\r\nServer: CakeHttp Server\r\nContent-Type: text/html\r\n\r\n

This is a test!

"; + $this->Socket->expects($this->at(1))->method('read')->will($this->returnValue($serverResponse)); + $this->Socket->expects($this->at(2))->method('read')->will($this->returnValue(false)); + $expected = array('www.cakephp.org' => array('foo' => array('value' => 'bar'))); + $this->Socket->request('http://www.cakephp.org/'); + $this->assertEquals($expected, $this->Socket->config['request']['cookies']); + + $serverResponse = "HTTP/1.x 200 OK\r\nSet-Cookie: bar=foo\r\nDate: Mon, 16 Apr 2007 04:14:16 GMT\r\nServer: CakeHttp Server\r\nContent-Type: text/html\r\n\r\n

This is a test!

"; + $this->Socket->expects($this->at(1))->method('read')->will($this->returnValue($serverResponse)); + $this->Socket->expects($this->at(2))->method('read')->will($this->returnValue(false)); + $this->Socket->request('http://www.cakephp.org/other'); + $this->assertEquals(array('foo' => array('value' => 'bar')), $this->Socket->request['cookies']); + $expected['www.cakephp.org'] += array('bar' => array('value' => 'foo')); + $this->assertEquals($expected, $this->Socket->config['request']['cookies']); + + $serverResponse = "HTTP/1.x 200 OK\r\nDate: Mon, 16 Apr 2007 04:14:16 GMT\r\nServer: CakeHttp Server\r\nContent-Type: text/html\r\n\r\n

This is a test!

"; + $this->Socket->expects($this->at(1))->method('read')->will($this->returnValue($serverResponse)); + $this->Socket->expects($this->at(2))->method('read')->will($this->returnValue(false)); + $this->Socket->request('/other2'); + $this->assertEquals($expected, $this->Socket->config['request']['cookies']); + + $serverResponse = "HTTP/1.x 200 OK\r\nSet-Cookie: foobar=ok\r\nDate: Mon, 16 Apr 2007 04:14:16 GMT\r\nServer: CakeHttp Server\r\nContent-Type: text/html\r\n\r\n

This is a test!

"; + $this->Socket->expects($this->at(1))->method('read')->will($this->returnValue($serverResponse)); + $this->Socket->expects($this->at(2))->method('read')->will($this->returnValue(false)); + $this->Socket->request('http://www.cake.com'); + $this->assertTrue(empty($this->Socket->request['cookies'])); + $expected['www.cake.com'] = array('foobar' => array('value' => 'ok')); + $this->assertEquals($expected, $this->Socket->config['request']['cookies']); + } + +/** + * testRequestCustomResponse + * + * @return void + */ + public function testRequestCustomResponse() { + $this->Socket->connected = true; + $serverResponse = "HTTP/1.x 200 OK\r\nDate: Mon, 16 Apr 2007 04:14:16 GMT\r\nServer: CakeHttp Server\r\nContent-Type: text/html\r\n\r\n

This is a test!

"; + $this->Socket->expects($this->at(1))->method('read')->will($this->returnValue($serverResponse)); + $this->Socket->expects($this->at(2))->method('read')->will($this->returnValue(false)); + + $this->Socket->responseClass = 'CustomResponse'; + $response = $this->Socket->request('http://www.cakephp.org/'); + $this->assertInstanceOf('CustomResponse', $response); + $this->assertEquals('HTTP/1.x 2', $response->first10); + } + +/** + * testRequestWithRedirect method + * + * @return void + */ + public function testRequestWithRedirectAsTrue() { + $request = array( + 'uri' => 'http://localhost/oneuri', + 'redirect' => true + ); + $serverResponse1 = "HTTP/1.x 302 Found\r\nDate: Mon, 16 Apr 2007 04:14:16 GMT\r\nServer: CakeHttp Server\r\nContent-Type: text/html\r\nLocation: http://localhost/anotheruri\r\n\r\n"; + $serverResponse2 = "HTTP/1.x 200 OK\r\nDate: Mon, 16 Apr 2007 04:14:16 GMT\r\nServer: CakeHttp Server\r\nContent-Type: text/html\r\n\r\n

You have been redirected

"; + $this->Socket->expects($this->at(1))->method('read')->will($this->returnValue($serverResponse1)); + $this->Socket->expects($this->at(4))->method('read')->will($this->returnValue($serverResponse2)); + + $response = $this->Socket->request($request); + $this->assertEquals('

You have been redirected

', $response->body()); + } + + public function testRequestWithRedirectAsInt() { + $request = array( + 'uri' => 'http://localhost/oneuri', + 'redirect' => 2 + ); + $serverResponse1 = "HTTP/1.x 302 Found\r\nDate: Mon, 16 Apr 2007 04:14:16 GMT\r\nServer: CakeHttp Server\r\nContent-Type: text/html\r\nLocation: http://localhost/anotheruri\r\n\r\n"; + $serverResponse2 = "HTTP/1.x 200 OK\r\nDate: Mon, 16 Apr 2007 04:14:16 GMT\r\nServer: CakeHttp Server\r\nContent-Type: text/html\r\n\r\n

You have been redirected

"; + $this->Socket->expects($this->at(1))->method('read')->will($this->returnValue($serverResponse1)); + $this->Socket->expects($this->at(4))->method('read')->will($this->returnValue($serverResponse2)); + + $response = $this->Socket->request($request); + $this->assertEquals(1, $this->Socket->request['redirect']); + } + + public function testRequestWithRedirectAsIntReachingZero() { + $request = array( + 'uri' => 'http://localhost/oneuri', + 'redirect' => 1 + ); + $serverResponse1 = "HTTP/1.x 302 Found\r\nDate: Mon, 16 Apr 2007 04:14:16 GMT\r\nServer: CakeHttp Server\r\nContent-Type: text/html\r\nLocation: http://localhost/oneruri\r\n\r\n"; + $serverResponse2 = "HTTP/1.x 302 Found\r\nDate: Mon, 16 Apr 2007 04:14:16 GMT\r\nServer: CakeHttp Server\r\nContent-Type: text/html\r\nLocation: http://localhost/anotheruri\r\n\r\n"; + $this->Socket->expects($this->at(1))->method('read')->will($this->returnValue($serverResponse1)); + $this->Socket->expects($this->at(4))->method('read')->will($this->returnValue($serverResponse2)); + + $response = $this->Socket->request($request); + $this->assertEquals(0, $this->Socket->request['redirect']); + $this->assertEquals(302, $response->code); + $this->assertEquals('http://localhost/anotheruri', $response->getHeader('Location')); + } + +/** + * testProxy method + * + * @return void + */ + public function testProxy() { + $this->Socket->reset(); + $this->Socket->expects($this->any())->method('connect')->will($this->returnValue(true)); + $this->Socket->expects($this->any())->method('read')->will($this->returnValue(false)); + + $this->Socket->configProxy('proxy.server', 123); + $expected = "GET http://www.cakephp.org/ HTTP/1.1\r\nHost: www.cakephp.org\r\nConnection: close\r\nUser-Agent: CakePHP\r\n\r\n"; + $this->Socket->request('http://www.cakephp.org/'); + $this->assertEquals($expected, $this->Socket->request['raw']); + $this->assertEquals('proxy.server', $this->Socket->config['host']); + $this->assertEquals(123, $this->Socket->config['port']); + $expected = array( + 'host' => 'proxy.server', + 'port' => 123, + 'method' => null, + 'user' => null, + 'pass' => null + ); + $this->assertEquals($expected, $this->Socket->request['proxy']); + + $expected = "GET http://www.cakephp.org/bakery HTTP/1.1\r\nHost: www.cakephp.org\r\nConnection: close\r\nUser-Agent: CakePHP\r\n\r\n"; + $this->Socket->request('/bakery'); + $this->assertEquals($expected, $this->Socket->request['raw']); + $this->assertEquals('proxy.server', $this->Socket->config['host']); + $this->assertEquals(123, $this->Socket->config['port']); + $expected = array( + 'host' => 'proxy.server', + 'port' => 123, + 'method' => null, + 'user' => null, + 'pass' => null + ); + $this->assertEquals($expected, $this->Socket->request['proxy']); + + $expected = "GET http://www.cakephp.org/ HTTP/1.1\r\nHost: www.cakephp.org\r\nConnection: close\r\nUser-Agent: CakePHP\r\nProxy-Authorization: Test mark.secret\r\n\r\n"; + $this->Socket->configProxy('proxy.server', 123, 'Test', 'mark', 'secret'); + $this->Socket->request('http://www.cakephp.org/'); + $this->assertEquals($expected, $this->Socket->request['raw']); + $this->assertEquals('proxy.server', $this->Socket->config['host']); + $this->assertEquals(123, $this->Socket->config['port']); + $expected = array( + 'host' => 'proxy.server', + 'port' => 123, + 'method' => 'Test', + 'user' => 'mark', + 'pass' => 'secret' + ); + $this->assertEquals($expected, $this->Socket->request['proxy']); + + $this->Socket->configAuth('Test', 'login', 'passwd'); + $expected = "GET http://www.cakephp.org/ HTTP/1.1\r\nHost: www.cakephp.org\r\nConnection: close\r\nUser-Agent: CakePHP\r\nProxy-Authorization: Test mark.secret\r\nAuthorization: Test login.passwd\r\n\r\n"; + $this->Socket->request('http://www.cakephp.org/'); + $this->assertEquals($expected, $this->Socket->request['raw']); + $expected = array( + 'host' => 'proxy.server', + 'port' => 123, + 'method' => 'Test', + 'user' => 'mark', + 'pass' => 'secret' + ); + $this->assertEquals($expected, $this->Socket->request['proxy']); + $expected = array( + 'Test' => array( + 'user' => 'login', + 'pass' => 'passwd' + ) + ); + $this->assertEquals($expected, $this->Socket->request['auth']); + } + +/** + * testUrl method + * + * @return void + */ + public function testUrl() { + $this->Socket->reset(true); + + $this->assertEquals(false, $this->Socket->url(true)); + + $url = $this->Socket->url('www.cakephp.org'); + $this->assertEquals('http://www.cakephp.org/', $url); + + $url = $this->Socket->url('https://www.cakephp.org/posts/add'); + $this->assertEquals('https://www.cakephp.org/posts/add', $url); + $url = $this->Socket->url('http://www.cakephp/search?q=socket', '/%path?%query'); + $this->assertEquals('/search?q=socket', $url); + + $this->Socket->config['request']['uri']['host'] = 'bakery.cakephp.org'; + $url = $this->Socket->url(); + $this->assertEquals('http://bakery.cakephp.org/', $url); + + $this->Socket->configUri('http://www.cakephp.org'); + $url = $this->Socket->url('/search?q=bar'); + $this->assertEquals('http://www.cakephp.org/search?q=bar', $url); + + $url = $this->Socket->url(array('host' => 'www.foobar.org', 'query' => array('q' => 'bar'))); + $this->assertEquals('http://www.foobar.org/?q=bar', $url); + + $url = $this->Socket->url(array('path' => '/supersearch', 'query' => array('q' => 'bar'))); + $this->assertEquals('http://www.cakephp.org/supersearch?q=bar', $url); + + $this->Socket->configUri('http://www.google.com'); + $url = $this->Socket->url('/search?q=socket'); + $this->assertEquals('http://www.google.com/search?q=socket', $url); + + $url = $this->Socket->url(); + $this->assertEquals('http://www.google.com/', $url); + + $this->Socket->configUri('https://www.google.com'); + $url = $this->Socket->url('/search?q=socket'); + $this->assertEquals('https://www.google.com/search?q=socket', $url); + + $this->Socket->reset(); + $this->Socket->configUri('www.google.com:443'); + $url = $this->Socket->url('/search?q=socket'); + $this->assertEquals('https://www.google.com/search?q=socket', $url); + + $this->Socket->reset(); + $this->Socket->configUri('www.google.com:8080'); + $url = $this->Socket->url('/search?q=socket'); + $this->assertEquals('http://www.google.com:8080/search?q=socket', $url); + } + +/** + * testGet method + * + * @return void + */ + public function testGet() { + $this->RequestSocket->reset(); + + $this->RequestSocket->expects($this->at(0)) + ->method('request') + ->with(array('method' => 'GET', 'uri' => 'http://www.google.com/')); + + $this->RequestSocket->expects($this->at(1)) + ->method('request') + ->with(array('method' => 'GET', 'uri' => 'http://www.google.com/?foo=bar')); + + $this->RequestSocket->expects($this->at(2)) + ->method('request') + ->with(array('method' => 'GET', 'uri' => 'http://www.google.com/?foo=bar')); + + $this->RequestSocket->expects($this->at(3)) + ->method('request') + ->with(array('method' => 'GET', 'uri' => 'http://www.google.com/?foo=23&foobar=42')); + + $this->RequestSocket->expects($this->at(4)) + ->method('request') + ->with(array('method' => 'GET', 'uri' => 'http://www.google.com/', 'version' => '1.0')); + + $this->RequestSocket->expects($this->at(5)) + ->method('request') + ->with(array('method' => 'GET', 'uri' => 'https://secure.example.com/test.php?one=two')); + + $this->RequestSocket->expects($this->at(6)) + ->method('request') + ->with(array('method' => 'GET', 'uri' => 'https://example.com/oauth/access?clientid=123&redirect_uri=http%3A%2F%2Fexample.com&code=456')); + + $this->RequestSocket->get('http://www.google.com/'); + $this->RequestSocket->get('http://www.google.com/', array('foo' => 'bar')); + $this->RequestSocket->get('http://www.google.com/', 'foo=bar'); + $this->RequestSocket->get('http://www.google.com/?foo=bar', array('foobar' => '42', 'foo' => '23')); + $this->RequestSocket->get('http://www.google.com/', null, array('version' => '1.0')); + $this->RequestSocket->get('https://secure.example.com/test.php', array('one' => 'two')); + $this->RequestSocket->get('https://example.com/oauth/access', array( + 'clientid' => '123', + 'redirect_uri' => 'http://example.com', + 'code' => 456 + )); + } + +/** + * Test authentication + * + * @return void + */ + public function testAuth() { + $socket = new MockHttpSocket(); + $socket->get('http://mark:secret@example.com/test'); + $this->assertTrue(strpos($socket->request['header'], 'Authorization: Basic bWFyazpzZWNyZXQ=') !== false); + + $socket->configAuth(false); + $socket->get('http://example.com/test'); + $this->assertFalse(strpos($socket->request['header'], 'Authorization:')); + + $socket->configAuth('Test', 'mark', 'passwd'); + $socket->get('http://example.com/test'); + $this->assertTrue(strpos($socket->request['header'], 'Authorization: Test mark.passwd') !== false); + } + +/** + * test that two consecutive get() calls reset the authentication credentials. + * + * @return void + */ + public function testConsecutiveGetResetsAuthCredentials() { + $socket = new MockHttpSocket(); + $socket->get('http://mark:secret@example.com/test'); + $this->assertEquals('mark', $socket->request['uri']['user']); + $this->assertEquals('secret', $socket->request['uri']['pass']); + $this->assertTrue(strpos($socket->request['header'], 'Authorization: Basic bWFyazpzZWNyZXQ=') !== false); + + $socket->get('/test2'); + $this->assertTrue(strpos($socket->request['header'], 'Authorization: Basic bWFyazpzZWNyZXQ=') !== false); + + $socket->get('/test3'); + $this->assertTrue(strpos($socket->request['header'], 'Authorization: Basic bWFyazpzZWNyZXQ=') !== false); + } + +/** + * testPostPutDelete method + * + * @return void + */ + public function testPost() { + $this->RequestSocket->reset(); + $this->RequestSocket->expects($this->at(0)) + ->method('request') + ->with(array('method' => 'POST', 'uri' => 'http://www.google.com/', 'body' => array())); + + $this->RequestSocket->expects($this->at(1)) + ->method('request') + ->with(array('method' => 'POST', 'uri' => 'http://www.google.com/', 'body' => array('Foo' => 'bar'))); + + $this->RequestSocket->expects($this->at(2)) + ->method('request') + ->with(array('method' => 'POST', 'uri' => 'http://www.google.com/', 'body' => null, 'line' => 'Hey Server')); + + $this->RequestSocket->post('http://www.google.com/'); + $this->RequestSocket->post('http://www.google.com/', array('Foo' => 'bar')); + $this->RequestSocket->post('http://www.google.com/', null, array('line' => 'Hey Server')); + } + +/** + * testPut + * + * @return void + */ + public function testPut() { + $this->RequestSocket->reset(); + $this->RequestSocket->expects($this->at(0)) + ->method('request') + ->with(array('method' => 'PUT', 'uri' => 'http://www.google.com/', 'body' => array())); + + $this->RequestSocket->expects($this->at(1)) + ->method('request') + ->with(array('method' => 'PUT', 'uri' => 'http://www.google.com/', 'body' => array('Foo' => 'bar'))); + + $this->RequestSocket->expects($this->at(2)) + ->method('request') + ->with(array('method' => 'PUT', 'uri' => 'http://www.google.com/', 'body' => null, 'line' => 'Hey Server')); + + $this->RequestSocket->put('http://www.google.com/'); + $this->RequestSocket->put('http://www.google.com/', array('Foo' => 'bar')); + $this->RequestSocket->put('http://www.google.com/', null, array('line' => 'Hey Server')); + } + +/** + * testDelete + * + * @return void + */ + public function testDelete() { + $this->RequestSocket->reset(); + $this->RequestSocket->expects($this->at(0)) + ->method('request') + ->with(array('method' => 'DELETE', 'uri' => 'http://www.google.com/', 'body' => array())); + + $this->RequestSocket->expects($this->at(1)) + ->method('request') + ->with(array('method' => 'DELETE', 'uri' => 'http://www.google.com/', 'body' => array('Foo' => 'bar'))); + + $this->RequestSocket->expects($this->at(2)) + ->method('request') + ->with(array('method' => 'DELETE', 'uri' => 'http://www.google.com/', 'body' => null, 'line' => 'Hey Server')); + + $this->RequestSocket->delete('http://www.google.com/'); + $this->RequestSocket->delete('http://www.google.com/', array('Foo' => 'bar')); + $this->RequestSocket->delete('http://www.google.com/', null, array('line' => 'Hey Server')); + } + +/** + * testBuildRequestLine method + * + * @return void + */ + public function testBuildRequestLine() { + $this->Socket->reset(); + + $this->Socket->quirksMode = true; + $r = $this->Socket->buildRequestLine('Foo'); + $this->assertEquals('Foo', $r); + $this->Socket->quirksMode = false; + + $r = $this->Socket->buildRequestLine(true); + $this->assertEquals(false, $r); + + $r = $this->Socket->buildRequestLine(array('foo' => 'bar', 'method' => 'foo')); + $this->assertEquals(false, $r); + + $r = $this->Socket->buildRequestLine(array('method' => 'GET', 'uri' => 'http://www.cakephp.org/search?q=socket')); + $this->assertEquals("GET /search?q=socket HTTP/1.1\r\n", $r); + + $request = array( + 'method' => 'GET', + 'uri' => array( + 'path' => '/search', + 'query' => array('q' => 'socket') + ) + ); + $r = $this->Socket->buildRequestLine($request); + $this->assertEquals("GET /search?q=socket HTTP/1.1\r\n", $r); + + unset($request['method']); + $r = $this->Socket->buildRequestLine($request); + $this->assertEquals("GET /search?q=socket HTTP/1.1\r\n", $r); + + $r = $this->Socket->buildRequestLine($request, 'CAKE-HTTP/0.1'); + $this->assertEquals("GET /search?q=socket CAKE-HTTP/0.1\r\n", $r); + + $request = array('method' => 'OPTIONS', 'uri' => '*'); + $r = $this->Socket->buildRequestLine($request); + $this->assertEquals("OPTIONS * HTTP/1.1\r\n", $r); + + $request['method'] = 'GET'; + $this->Socket->quirksMode = true; + $r = $this->Socket->buildRequestLine($request); + $this->assertEquals("GET * HTTP/1.1\r\n", $r); + + $r = $this->Socket->buildRequestLine("GET * HTTP/1.1\r\n"); + $this->assertEquals("GET * HTTP/1.1\r\n", $r); + } + +/** + * testBadBuildRequestLine method + * + * @expectedException SocketException + * @return void + */ + public function testBadBuildRequestLine() { + $r = $this->Socket->buildRequestLine('Foo'); + } + +/** + * testBadBuildRequestLine2 method + * + * @expectedException SocketException + * @return void + */ + public function testBadBuildRequestLine2() { + $r = $this->Socket->buildRequestLine("GET * HTTP/1.1\r\n"); + } + +/** + * Asserts that HttpSocket::parseUri is working properly + * + * @return void + */ + public function testParseUri() { + $this->Socket->reset(); + + $uri = $this->Socket->parseUri(array('invalid' => 'uri-string')); + $this->assertEquals(false, $uri); + + $uri = $this->Socket->parseUri(array('invalid' => 'uri-string'), array('host' => 'somehost')); + $this->assertEquals(array('host' => 'somehost', 'invalid' => 'uri-string'), $uri); + + $uri = $this->Socket->parseUri(false); + $this->assertEquals(false, $uri); + + $uri = $this->Socket->parseUri('/my-cool-path'); + $this->assertEquals(array('path' => '/my-cool-path'), $uri); + + $uri = $this->Socket->parseUri('http://bob:foo123@www.cakephp.org:40/search?q=dessert#results'); + $this->assertEquals($uri, array( + 'scheme' => 'http', + 'host' => 'www.cakephp.org', + 'port' => 40, + 'user' => 'bob', + 'pass' => 'foo123', + 'path' => '/search', + 'query' => array('q' => 'dessert'), + 'fragment' => 'results' + )); + + $uri = $this->Socket->parseUri('http://www.cakephp.org/'); + $this->assertEquals($uri, array( + 'scheme' => 'http', + 'host' => 'www.cakephp.org', + 'path' => '/' + )); + + $uri = $this->Socket->parseUri('http://www.cakephp.org', true); + $this->assertEquals($uri, array( + 'scheme' => 'http', + 'host' => 'www.cakephp.org', + 'port' => 80, + 'user' => null, + 'pass' => null, + 'path' => '/', + 'query' => array(), + 'fragment' => null + )); + + $uri = $this->Socket->parseUri('https://www.cakephp.org', true); + $this->assertEquals($uri, array( + 'scheme' => 'https', + 'host' => 'www.cakephp.org', + 'port' => 443, + 'user' => null, + 'pass' => null, + 'path' => '/', + 'query' => array(), + 'fragment' => null + )); + + $uri = $this->Socket->parseUri('www.cakephp.org:443/query?foo', true); + $this->assertEquals($uri, array( + 'scheme' => 'https', + 'host' => 'www.cakephp.org', + 'port' => 443, + 'user' => null, + 'pass' => null, + 'path' => '/query', + 'query' => array('foo' => ""), + 'fragment' => null + )); + + $uri = $this->Socket->parseUri('http://www.cakephp.org', array('host' => 'piephp.org', 'user' => 'bob', 'fragment' => 'results')); + $this->assertEquals($uri, array( + 'host' => 'www.cakephp.org', + 'user' => 'bob', + 'fragment' => 'results', + 'scheme' => 'http' + )); + + $uri = $this->Socket->parseUri('https://www.cakephp.org', array('scheme' => 'http', 'port' => 23)); + $this->assertEquals($uri, array( + 'scheme' => 'https', + 'port' => 23, + 'host' => 'www.cakephp.org' + )); + + $uri = $this->Socket->parseUri('www.cakephp.org:59', array('scheme' => array('http', 'https'), 'port' => 80)); + $this->assertEquals($uri, array( + 'scheme' => 'http', + 'port' => 59, + 'host' => 'www.cakephp.org' + )); + + $uri = $this->Socket->parseUri(array('scheme' => 'http', 'host' => 'www.google.com', 'port' => 8080), array('scheme' => array('http', 'https'), 'host' => 'www.google.com', 'port' => array(80, 443))); + $this->assertEquals($uri, array( + 'scheme' => 'http', + 'host' => 'www.google.com', + 'port' => 8080 + )); + + $uri = $this->Socket->parseUri('http://www.cakephp.org/?param1=value1¶m2=value2%3Dvalue3'); + $this->assertEquals($uri, array( + 'scheme' => 'http', + 'host' => 'www.cakephp.org', + 'path' => '/', + 'query' => array( + 'param1' => 'value1', + 'param2' => 'value2=value3' + ) + )); + + $uri = $this->Socket->parseUri('http://www.cakephp.org/?param1=value1¶m2=value2=value3'); + $this->assertEquals($uri, array( + 'scheme' => 'http', + 'host' => 'www.cakephp.org', + 'path' => '/', + 'query' => array( + 'param1' => 'value1', + 'param2' => 'value2=value3' + ) + )); + } + +/** + * Tests that HttpSocket::buildUri can turn all kinds of uri arrays (and strings) into fully or partially qualified URI's + * + * @return void + */ + public function testBuildUri() { + $this->Socket->reset(); + + $r = $this->Socket->buildUri(true); + $this->assertEquals(false, $r); + + $r = $this->Socket->buildUri('foo.com'); + $this->assertEquals('http://foo.com/', $r); + + $r = $this->Socket->buildUri(array('host' => 'www.cakephp.org')); + $this->assertEquals('http://www.cakephp.org/', $r); + + $r = $this->Socket->buildUri(array('host' => 'www.cakephp.org', 'scheme' => 'https')); + $this->assertEquals('https://www.cakephp.org/', $r); + + $r = $this->Socket->buildUri(array('host' => 'www.cakephp.org', 'port' => 23)); + $this->assertEquals('http://www.cakephp.org:23/', $r); + + $r = $this->Socket->buildUri(array('path' => 'www.google.com/search', 'query' => 'q=cakephp')); + $this->assertEquals('http://www.google.com/search?q=cakephp', $r); + + $r = $this->Socket->buildUri(array('host' => 'www.cakephp.org', 'scheme' => 'https', 'port' => 79)); + $this->assertEquals('https://www.cakephp.org:79/', $r); + + $r = $this->Socket->buildUri(array('host' => 'www.cakephp.org', 'path' => 'foo')); + $this->assertEquals('http://www.cakephp.org/foo', $r); + + $r = $this->Socket->buildUri(array('host' => 'www.cakephp.org', 'path' => '/foo')); + $this->assertEquals('http://www.cakephp.org/foo', $r); + + $r = $this->Socket->buildUri(array('host' => 'www.cakephp.org', 'path' => '/search', 'query' => array('q' => 'HttpSocket'))); + $this->assertEquals('http://www.cakephp.org/search?q=HttpSocket', $r); + + $r = $this->Socket->buildUri(array('host' => 'www.cakephp.org', 'fragment' => 'bar')); + $this->assertEquals('http://www.cakephp.org/#bar', $r); + + $r = $this->Socket->buildUri(array( + 'scheme' => 'https', + 'host' => 'www.cakephp.org', + 'port' => 25, + 'user' => 'bob', + 'pass' => 'secret', + 'path' => '/cool', + 'query' => array('foo' => 'bar'), + 'fragment' => 'comment' + )); + $this->assertEquals('https://bob:secret@www.cakephp.org:25/cool?foo=bar#comment', $r); + + $r = $this->Socket->buildUri(array('host' => 'www.cakephp.org', 'fragment' => 'bar'), '%fragment?%host'); + $this->assertEquals('bar?www.cakephp.org', $r); + + $r = $this->Socket->buildUri(array('host' => 'www.cakephp.org'), '%fragment???%host'); + $this->assertEquals('???www.cakephp.org', $r); + + $r = $this->Socket->buildUri(array('path' => '*'), '/%path?%query'); + $this->assertEquals('*', $r); + + $r = $this->Socket->buildUri(array('scheme' => 'foo', 'host' => 'www.cakephp.org')); + $this->assertEquals('foo://www.cakephp.org:80/', $r); + } + +/** + * Asserts that HttpSocket::parseQuery is working properly + * + * @return void + */ + public function testParseQuery() { + $this->Socket->reset(); + + $query = $this->Socket->parseQuery(array('framework' => 'cakephp')); + $this->assertEquals(array('framework' => 'cakephp'), $query); + + $query = $this->Socket->parseQuery(''); + $this->assertEquals(array(), $query); + + $query = $this->Socket->parseQuery('framework=cakephp'); + $this->assertEquals(array('framework' => 'cakephp'), $query); + + $query = $this->Socket->parseQuery('?framework=cakephp'); + $this->assertEquals(array('framework' => 'cakephp'), $query); + + $query = $this->Socket->parseQuery('a&b&c'); + $this->assertEquals(array('a' => '', 'b' => '', 'c' => ''), $query); + + $query = $this->Socket->parseQuery('value=12345'); + $this->assertEquals(array('value' => '12345'), $query); + + $query = $this->Socket->parseQuery('a[0]=foo&a[1]=bar&a[2]=cake'); + $this->assertEquals(array('a' => array(0 => 'foo', 1 => 'bar', 2 => 'cake')), $query); + + $query = $this->Socket->parseQuery('a[]=foo&a[]=bar&a[]=cake'); + $this->assertEquals(array('a' => array(0 => 'foo', 1 => 'bar', 2 => 'cake')), $query); + + $query = $this->Socket->parseQuery('a[][]=foo&a[][]=bar&a[][]=cake'); + $expectedQuery = array( + 'a' => array( + 0 => array( + 0 => 'foo' + ), + 1 => array( + 0 => 'bar' + ), + array( + 0 => 'cake' + ) + ) + ); + $this->assertEquals($expectedQuery, $query); + + $query = $this->Socket->parseQuery('a[][]=foo&a[bar]=php&a[][]=bar&a[][]=cake'); + $expectedQuery = array( + 'a' => array( + array('foo'), + 'bar' => 'php', + array('bar'), + array('cake') + ) + ); + $this->assertEquals($expectedQuery, $query); + + $query = $this->Socket->parseQuery('user[]=jim&user[3]=tom&user[]=bob'); + $expectedQuery = array( + 'user' => array( + 0 => 'jim', + 3 => 'tom', + 4 => 'bob' + ) + ); + $this->assertEquals($expectedQuery, $query); + + $queryStr = 'user[0]=foo&user[0][items][]=foo&user[0][items][]=bar&user[][name]=jim&user[1][items][personal][]=book&user[1][items][personal][]=pen&user[1][items][]=ball&user[count]=2&empty'; + $query = $this->Socket->parseQuery($queryStr); + $expectedQuery = array( + 'user' => array( + 0 => array( + 'items' => array( + 'foo', + 'bar' + ) + ), + 1 => array( + 'name' => 'jim', + 'items' => array( + 'personal' => array( + 'book' + , 'pen' + ), + 'ball' + ) + ), + 'count' => '2' + ), + 'empty' => '' + ); + $this->assertEquals($expectedQuery, $query); + + $query = 'openid.ns=example.com&foo=bar&foo=baz'; + $result = $this->Socket->parseQuery($query); + $expected = array( + 'openid.ns' => 'example.com', + 'foo' => array('bar', 'baz') + ); + $this->assertEquals($expected, $result); + } + +/** + * Tests that HttpSocket::buildHeader can turn a given $header array into a proper header string according to + * HTTP 1.1 specs. + * + * @return void + */ + public function testBuildHeader() { + $this->Socket->reset(); + + $r = $this->Socket->buildHeader(true); + $this->assertEquals(false, $r); + + $r = $this->Socket->buildHeader('My raw header'); + $this->assertEquals('My raw header', $r); + + $r = $this->Socket->buildHeader(array('Host' => 'www.cakephp.org')); + $this->assertEquals("Host: www.cakephp.org\r\n", $r); + + $r = $this->Socket->buildHeader(array('Host' => 'www.cakephp.org', 'Connection' => 'Close')); + $this->assertEquals("Host: www.cakephp.org\r\nConnection: Close\r\n", $r); + + $r = $this->Socket->buildHeader(array('People' => array('Bob', 'Jim', 'John'))); + $this->assertEquals("People: Bob,Jim,John\r\n", $r); + + $r = $this->Socket->buildHeader(array('Multi-Line-Field' => "This is my\r\nMulti Line field")); + $this->assertEquals("Multi-Line-Field: This is my\r\n Multi Line field\r\n", $r); + + $r = $this->Socket->buildHeader(array('Multi-Line-Field' => "This is my\r\n Multi Line field")); + $this->assertEquals("Multi-Line-Field: This is my\r\n Multi Line field\r\n", $r); + + $r = $this->Socket->buildHeader(array('Multi-Line-Field' => "This is my\r\n\tMulti Line field")); + $this->assertEquals("Multi-Line-Field: This is my\r\n\tMulti Line field\r\n", $r); + + $r = $this->Socket->buildHeader(array('Test@Field' => "My value")); + $this->assertEquals("Test\"@\"Field: My value\r\n", $r); + } + +/** + * testBuildCookies method + * + * @return void + * @todo Test more scenarios + */ + public function testBuildCookies() { + $cookies = array( + 'foo' => array( + 'value' => 'bar' + ), + 'people' => array( + 'value' => 'jim,jack,johnny;', + 'path' => '/accounts' + ) + ); + $expect = "Cookie: foo=bar; people=jim,jack,johnny\";\"\r\n"; + $result = $this->Socket->buildCookies($cookies); + $this->assertEquals($expect, $result); + } + +/** + * Tests that HttpSocket::_tokenEscapeChars() returns the right characters. + * + * @return void + */ + public function testTokenEscapeChars() { + $this->Socket->reset(); + + $expected = array( + '\x22','\x28','\x29','\x3c','\x3e','\x40','\x2c','\x3b','\x3a','\x5c','\x2f','\x5b','\x5d','\x3f','\x3d','\x7b', + '\x7d','\x20','\x00','\x01','\x02','\x03','\x04','\x05','\x06','\x07','\x08','\x09','\x0a','\x0b','\x0c','\x0d', + '\x0e','\x0f','\x10','\x11','\x12','\x13','\x14','\x15','\x16','\x17','\x18','\x19','\x1a','\x1b','\x1c','\x1d', + '\x1e','\x1f','\x7f' + ); + $r = $this->Socket->tokenEscapeChars(); + $this->assertEquals($expected, $r); + + foreach ($expected as $key => $char) { + $expected[$key] = chr(hexdec(substr($char, 2))); + } + + $r = $this->Socket->tokenEscapeChars(false); + $this->assertEquals($expected, $r); + } + +/** + * Test that HttpSocket::escapeToken is escaping all characters as described in RFC 2616 (HTTP 1.1 specs) + * + * @return void + */ + public function testEscapeToken() { + $this->Socket->reset(); + + $this->assertEquals('Foo', $this->Socket->escapeToken('Foo')); + + $escape = $this->Socket->tokenEscapeChars(false); + foreach ($escape as $char) { + $token = 'My-special-' . $char . '-Token'; + $escapedToken = $this->Socket->escapeToken($token); + $expectedToken = 'My-special-"' . $char . '"-Token'; + + $this->assertEquals($expectedToken, $escapedToken, 'Test token escaping for ASCII ' . ord($char)); + } + + $token = 'Extreme-:Token- -"@-test'; + $escapedToken = $this->Socket->escapeToken($token); + $expectedToken = 'Extreme-":"Token-" "-""""@"-test'; + $this->assertEquals($expectedToken, $escapedToken); + } + +/** + * This tests asserts HttpSocket::reset() resets a HttpSocket instance to it's initial state (before Object::__construct + * got executed) + * + * @return void + */ + public function testReset() { + $this->Socket->reset(); + + $initialState = get_class_vars('HttpSocket'); + foreach ($initialState as $property => $value) { + $this->Socket->{$property} = 'Overwritten'; + } + + $return = $this->Socket->reset(); + + foreach ($initialState as $property => $value) { + $this->assertEquals($this->Socket->{$property}, $value); + } + + $this->assertEquals(true, $return); + } + +/** + * This tests asserts HttpSocket::reset(false) resets certain HttpSocket properties to their initial state (before + * Object::__construct got executed). + * + * @return void + */ + public function testPartialReset() { + $this->Socket->reset(); + + $partialResetProperties = array('request', 'response'); + $initialState = get_class_vars('HttpSocket'); + + foreach ($initialState as $property => $value) { + $this->Socket->{$property} = 'Overwritten'; + } + + $return = $this->Socket->reset(false); + + foreach ($initialState as $property => $originalValue) { + if (in_array($property, $partialResetProperties)) { + $this->assertEquals($this->Socket->{$property}, $originalValue); + } else { + $this->assertEquals('Overwritten', $this->Socket->{$property}); + } + } + $this->assertEquals(true, $return); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Routing/DispatcherTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Routing/DispatcherTest.php new file mode 100644 index 0000000..a0e3df7 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Routing/DispatcherTest.php @@ -0,0 +1,1746 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Routing + * @since CakePHP(tm) v 1.2.0.4206 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ +App::uses('Dispatcher', 'Routing'); + +if (!class_exists('AppController', false)) { + require_once CAKE . 'Test' . DS . 'test_app' . DS . 'Controller' . DS . 'AppController.php'; +} elseif (!defined('APP_CONTROLLER_EXISTS')) { + define('APP_CONTROLLER_EXISTS', true); +} + +/** + * A testing stub that doesn't send headers. + * + * @package Cake.Test.Case.Routing + */ +class DispatcherMockCakeResponse extends CakeResponse { + + protected function _sendHeader($name, $value = null) { + return $name . ' ' . $value; + } + +} + +/** + * TestDispatcher class + * + * @package Cake.Test.Case.Routing + */ +class TestDispatcher extends Dispatcher { + +/** + * Controller instance, made publicly available for testing + * + * @var Controller + */ + public $controller; + +/** + * invoke method + * + * @param Controller $controller + * @param CakeRequest $request + * @param CakeResponse $response + * @return void + */ + protected function _invoke(Controller $controller, CakeRequest $request, CakeResponse $response) { + $this->controller = $controller; + return parent::_invoke($controller, $request, $response); + } + +/** + * Helper function to test single method attaching for dispatcher filters + * + * @param CakeEvent $event + * @return void + */ + public function filterTest($event) { + $event->data['request']->params['eventName'] = $event->name(); + } + +/** + * Helper function to test single method attaching for dispatcher filters + * + * @param CakeEvent + * @return void + */ + public function filterTest2($event) { + $event->stopPropagation(); + return $event->data['response']; + } + +} + +/** + * MyPluginAppController class + * + * @package Cake.Test.Case.Routing + */ +class MyPluginAppController extends AppController { +} + +abstract class DispatcherTestAbstractController extends Controller { + + abstract public function index(); + +} + +interface DispatcherTestInterfaceController { + + public function index(); + +} + +/** + * MyPluginController class + * + * @package Cake.Test.Case.Routing + */ +class MyPluginController extends MyPluginAppController { + +/** + * name property + * + * @var string 'MyPlugin' + */ + public $name = 'MyPlugin'; + +/** + * uses property + * + * @var array + */ + public $uses = array(); + +/** + * index method + * + * @return void + */ + public function index() { + return true; + } + +/** + * add method + * + * @return void + */ + public function add() { + return true; + } + +/** + * admin_add method + * + * @param mixed $id + * @return void + */ + public function admin_add($id = null) { + return $id; + } + +} + +/** + * SomePagesController class + * + * @package Cake.Test.Case.Routing + */ +class SomePagesController extends AppController { + +/** + * name property + * + * @var string 'SomePages' + */ + public $name = 'SomePages'; + +/** + * uses property + * + * @var array + */ + public $uses = array(); + +/** + * display method + * + * @param string $page + * @return void + */ + public function display($page = null) { + return $page; + } + +/** + * index method + * + * @return void + */ + public function index() { + return true; + } + +/** + * Test method for returning responses. + * + * @return CakeResponse + */ + public function responseGenerator() { + return new CakeResponse(array('body' => 'new response')); + } + +} + +/** + * OtherPagesController class + * + * @package Cake.Test.Case.Routing + */ +class OtherPagesController extends MyPluginAppController { + +/** + * name property + * + * @var string 'OtherPages' + */ + public $name = 'OtherPages'; + +/** + * uses property + * + * @var array + */ + public $uses = array(); + +/** + * display method + * + * @param string $page + * @return void + */ + public function display($page = null) { + return $page; + } + +/** + * index method + * + * @return void + */ + public function index() { + return true; + } + +} + +/** + * TestDispatchPagesController class + * + * @package Cake.Test.Case.Routing + */ +class TestDispatchPagesController extends AppController { + +/** + * name property + * + * @var string 'TestDispatchPages' + */ + public $name = 'TestDispatchPages'; + +/** + * uses property + * + * @var array + */ + public $uses = array(); + +/** + * admin_index method + * + * @return void + */ + public function admin_index() { + return true; + } + +/** + * camelCased method + * + * @return void + */ + public function camelCased() { + return true; + } + +} + +/** + * ArticlesTestAppController class + * + * @package Cake.Test.Case.Routing + */ +class ArticlesTestAppController extends AppController { +} + +/** + * ArticlesTestController class + * + * @package Cake.Test.Case.Routing + */ +class ArticlesTestController extends ArticlesTestAppController { + +/** + * name property + * + * @var string 'ArticlesTest' + */ + public $name = 'ArticlesTest'; + +/** + * uses property + * + * @var array + */ + public $uses = array(); + +/** + * admin_index method + * + * @return void + */ + public function admin_index() { + return true; + } + +/** + * fake index method. + * + * @return void + */ + public function index() { + return true; + } + +} + +/** + * SomePostsController class + * + * @package Cake.Test.Case.Routing + */ +class SomePostsController extends AppController { + +/** + * name property + * + * @var string 'SomePosts' + */ + public $name = 'SomePosts'; + +/** + * uses property + * + * @var array + */ + public $uses = array(); + +/** + * autoRender property + * + * @var bool false + */ + public $autoRender = false; + +/** + * beforeFilter method + * + * @return void + */ + public function beforeFilter() { + if ($this->params['action'] == 'index') { + $this->params['action'] = 'view'; + } else { + $this->params['action'] = 'change'; + } + $this->params['pass'] = array('changed'); + } + +/** + * index method + * + * @return void + */ + public function index() { + return true; + } + +/** + * change method + * + * @return void + */ + public function change() { + return true; + } + +} + +/** + * TestCachedPagesController class + * + * @package Cake.Test.Case.Routing + */ +class TestCachedPagesController extends Controller { + +/** + * name property + * + * @var string 'TestCachedPages' + */ + public $name = 'TestCachedPages'; + +/** + * uses property + * + * @var array + */ + public $uses = array(); + +/** + * helpers property + * + * @var array + */ + public $helpers = array('Cache', 'Html'); + +/** + * cacheAction property + * + * @var array + */ + public $cacheAction = array( + 'index' => '+2 sec', + 'test_nocache_tags' => '+2 sec', + 'view' => '+2 sec' + ); + +/** + * Mock out the response object so it doesn't send headers. + * + * @var string + */ + protected $_responseClass = 'DispatcherMockCakeResponse'; + +/** + * viewPath property + * + * @var string 'posts' + */ + public $viewPath = 'Posts'; + +/** + * index method + * + * @return void + */ + public function index() { + $this->render(); + } + +/** + * test_nocache_tags method + * + * @return void + */ + public function test_nocache_tags() { + $this->render(); + } + +/** + * view method + * + * @return void + */ + public function view($id = null) { + $this->render('index'); + } + +/** + * test cached forms / tests view object being registered + * + * @return void + */ + public function cache_form() { + $this->cacheAction = 10; + $this->helpers[] = 'Form'; + } + +/** + * Test cached views with themes. + */ + public function themed() { + $this->cacheAction = 10; + $this->viewClass = 'Theme'; + $this->theme = 'TestTheme'; + } + +} + +/** + * TimesheetsController class + * + * @package Cake.Test.Case.Routing + */ +class TimesheetsController extends Controller { + +/** + * name property + * + * @var string 'Timesheets' + */ + public $name = 'Timesheets'; + +/** + * uses property + * + * @var array + */ + public $uses = array(); + +/** + * index method + * + * @return void + */ + public function index() { + return true; + } + +} + +/** + * DispatcherTest class + * + * @package Cake.Test.Case.Routing + */ +class DispatcherTest extends CakeTestCase { + +/** + * setUp method + * + * @return void + */ + public function setUp() { + $this->_get = $_GET; + $_GET = array(); + $this->_post = $_POST; + $this->_files = $_FILES; + $this->_server = $_SERVER; + + $this->_app = Configure::read('App'); + Configure::write('App.base', false); + Configure::write('App.baseUrl', false); + Configure::write('App.dir', 'app'); + Configure::write('App.webroot', 'webroot'); + + $this->_cache = Configure::read('Cache'); + Configure::write('Cache.disable', true); + + $this->_debug = Configure::read('debug'); + + App::build(); + App::objects('plugin', null, false); + } + +/** + * tearDown method + * + * @return void + */ + public function tearDown() { + $_GET = $this->_get; + $_POST = $this->_post; + $_FILES = $this->_files; + $_SERVER = $this->_server; + App::build(); + CakePlugin::unload(); + Configure::write('App', $this->_app); + Configure::write('Cache', $this->_cache); + Configure::write('debug', $this->_debug); + Configure::write('Dispatcher.filters', array()); + } + +/** + * testParseParamsWithoutZerosAndEmptyPost method + * + * @return void + */ + public function testParseParamsWithoutZerosAndEmptyPost() { + $Dispatcher = new Dispatcher(); + $request = new CakeRequest("/testcontroller/testaction/params1/params2/params3"); + $event = new CakeEvent('DispatcherTest', $Dispatcher, array('request' => $request)); + $Dispatcher->parseParams($event); + $this->assertSame($request['controller'], 'testcontroller'); + $this->assertSame($request['action'], 'testaction'); + $this->assertSame($request['pass'][0], 'params1'); + $this->assertSame($request['pass'][1], 'params2'); + $this->assertSame($request['pass'][2], 'params3'); + $this->assertFalse(!empty($request['form'])); + } + +/** + * testParseParamsReturnsPostedData method + * + * @return void + */ + public function testParseParamsReturnsPostedData() { + $_POST['testdata'] = "My Posted Content"; + $Dispatcher = new Dispatcher(); + $request = new CakeRequest("/"); + $event = new CakeEvent('DispatcherTest', $Dispatcher, array('request' => $request)); + $Dispatcher->parseParams($event); + $test = $Dispatcher->parseParams($event); + $this->assertEquals("My Posted Content", $request['data']['testdata']); + } + +/** + * testParseParamsWithSingleZero method + * + * @return void + */ + public function testParseParamsWithSingleZero() { + $Dispatcher = new Dispatcher(); + $test = new CakeRequest("/testcontroller/testaction/1/0/23"); + $event = new CakeEvent('DispatcherTest', $Dispatcher, array('request' => $test)); + $Dispatcher->parseParams($event); + + $this->assertSame($test['controller'], 'testcontroller'); + $this->assertSame($test['action'], 'testaction'); + $this->assertSame($test['pass'][0], '1'); + $this->assertRegExp('/\\A(?:0)\\z/', $test['pass'][1]); + $this->assertSame($test['pass'][2], '23'); + } + +/** + * testParseParamsWithManySingleZeros method + * + * @return void + */ + public function testParseParamsWithManySingleZeros() { + $Dispatcher = new Dispatcher(); + $test = new CakeRequest("/testcontroller/testaction/0/0/0/0/0/0"); + $event = new CakeEvent('DispatcherTest', $Dispatcher, array('request' => $test)); + $Dispatcher->parseParams($event); + + $this->assertRegExp('/\\A(?:0)\\z/', $test['pass'][0]); + $this->assertRegExp('/\\A(?:0)\\z/', $test['pass'][1]); + $this->assertRegExp('/\\A(?:0)\\z/', $test['pass'][2]); + $this->assertRegExp('/\\A(?:0)\\z/', $test['pass'][3]); + $this->assertRegExp('/\\A(?:0)\\z/', $test['pass'][4]); + $this->assertRegExp('/\\A(?:0)\\z/', $test['pass'][5]); + } + +/** + * testParseParamsWithManyZerosInEachSectionOfUrl method + * + * @return void + */ + public function testParseParamsWithManyZerosInEachSectionOfUrl() { + $Dispatcher = new Dispatcher(); + $test = new CakeRequest("/testcontroller/testaction/000/0000/00000/000000/000000/0000000"); + $event = new CakeEvent('DispatcherTest', $Dispatcher, array('request' => $test)); + $Dispatcher->parseParams($event); + + $this->assertRegExp('/\\A(?:000)\\z/', $test['pass'][0]); + $this->assertRegExp('/\\A(?:0000)\\z/', $test['pass'][1]); + $this->assertRegExp('/\\A(?:00000)\\z/', $test['pass'][2]); + $this->assertRegExp('/\\A(?:000000)\\z/', $test['pass'][3]); + $this->assertRegExp('/\\A(?:000000)\\z/', $test['pass'][4]); + $this->assertRegExp('/\\A(?:0000000)\\z/', $test['pass'][5]); + } + +/** + * testParseParamsWithMixedOneToManyZerosInEachSectionOfUrl method + * + * @return void + */ + public function testParseParamsWithMixedOneToManyZerosInEachSectionOfUrl() { + $Dispatcher = new Dispatcher(); + $test = new CakeRequest("/testcontroller/testaction/01/0403/04010/000002/000030/0000400"); + $event = new CakeEvent('DispatcherTest', $Dispatcher, array('request' => $test)); + $Dispatcher->parseParams($event); + + $this->assertRegExp('/\\A(?:01)\\z/', $test['pass'][0]); + $this->assertRegExp('/\\A(?:0403)\\z/', $test['pass'][1]); + $this->assertRegExp('/\\A(?:04010)\\z/', $test['pass'][2]); + $this->assertRegExp('/\\A(?:000002)\\z/', $test['pass'][3]); + $this->assertRegExp('/\\A(?:000030)\\z/', $test['pass'][4]); + $this->assertRegExp('/\\A(?:0000400)\\z/', $test['pass'][5]); + } + +/** + * testQueryStringOnRoot method + * + * @return void + */ + public function testQueryStringOnRoot() { + Router::reload(); + Router::connect('/', array('controller' => 'pages', 'action' => 'display', 'home')); + Router::connect('/pages/*', array('controller' => 'pages', 'action' => 'display')); + Router::connect('/:controller/:action/*'); + + $_GET = array('coffee' => 'life', 'sleep' => 'sissies'); + $Dispatcher = new Dispatcher(); + $request = new CakeRequest('posts/home/?coffee=life&sleep=sissies'); + $event = new CakeEvent('DispatcherTest', $Dispatcher, array('request' => $request)); + $Dispatcher->parseParams($event); + + $this->assertRegExp('/posts/', $request['controller']); + $this->assertRegExp('/home/', $request['action']); + $this->assertTrue(isset($request['url']['sleep'])); + $this->assertTrue(isset($request['url']['coffee'])); + + $Dispatcher = new Dispatcher(); + $request = new CakeRequest('/?coffee=life&sleep=sissy'); + + $event = new CakeEvent('DispatcherTest', $Dispatcher, array('request' => $request)); + $Dispatcher->parseParams($event); + $this->assertRegExp('/pages/', $request['controller']); + $this->assertRegExp('/display/', $request['action']); + $this->assertTrue(isset($request['url']['sleep'])); + $this->assertTrue(isset($request['url']['coffee'])); + $this->assertEquals('life', $request['url']['coffee']); + } + +/** + * testMissingController method + * + * @expectedException MissingControllerException + * @expectedExceptionMessage Controller class SomeControllerController could not be found. + * @return void + */ + public function testMissingController() { + Router::connect('/:controller/:action/*'); + + $Dispatcher = new TestDispatcher(); + Configure::write('App.baseUrl', '/index.php'); + $url = new CakeRequest('some_controller/home/param:value/param2:value2'); + $response = $this->getMock('CakeResponse'); + + $Dispatcher->dispatch($url, $response, array('return' => 1)); + } + +/** + * testMissingControllerInterface method + * + * @expectedException MissingControllerException + * @expectedExceptionMessage Controller class DispatcherTestInterfaceController could not be found. + * @return void + */ + public function testMissingControllerInterface() { + Router::connect('/:controller/:action/*'); + + $Dispatcher = new TestDispatcher(); + Configure::write('App.baseUrl', '/index.php'); + $url = new CakeRequest('dispatcher_test_interface/index'); + $response = $this->getMock('CakeResponse'); + + $Dispatcher->dispatch($url, $response, array('return' => 1)); + } + +/** + * testMissingControllerInterface method + * + * @expectedException MissingControllerException + * @expectedExceptionMessage Controller class DispatcherTestAbstractController could not be found. + * @return void + */ + public function testMissingControllerAbstract() { + Router::connect('/:controller/:action/*'); + + $Dispatcher = new TestDispatcher(); + Configure::write('App.baseUrl', '/index.php'); + $url = new CakeRequest('dispatcher_test_abstract/index'); + $response = $this->getMock('CakeResponse'); + + $Dispatcher->dispatch($url, $response, array('return' => 1)); + } + +/** + * testDispatch method + * + * @return void + */ + public function testDispatchBasic() { + App::build(array( + 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS) + )); + $Dispatcher = new TestDispatcher(); + Configure::write('App.baseUrl', '/index.php'); + $url = new CakeRequest('pages/home/param:value/param2:value2'); + $response = $this->getMock('CakeResponse'); + + $Dispatcher->dispatch($url, $response, array('return' => 1)); + $expected = 'Pages'; + $this->assertEquals($expected, $Dispatcher->controller->name); + + $expected = array('0' => 'home', 'param' => 'value', 'param2' => 'value2'); + $this->assertSame($expected, $Dispatcher->controller->passedArgs); + + Configure::write('App.baseUrl', '/pages/index.php'); + + $url = new CakeRequest('pages/home'); + $Dispatcher->dispatch($url, $response, array('return' => 1)); + + $expected = 'Pages'; + $this->assertEquals($expected, $Dispatcher->controller->name); + + $url = new CakeRequest('pages/home/'); + $Dispatcher->dispatch($url, $response, array('return' => 1)); + $this->assertNull($Dispatcher->controller->plugin); + + $expected = 'Pages'; + $this->assertEquals($expected, $Dispatcher->controller->name); + + unset($Dispatcher); + + require CAKE . 'Config' . DS . 'routes.php'; + $Dispatcher = new TestDispatcher(); + Configure::write('App.baseUrl', '/timesheets/index.php'); + + $url = new CakeRequest('timesheets'); + $Dispatcher->dispatch($url, $response, array('return' => 1)); + + $expected = 'Timesheets'; + $this->assertEquals($expected, $Dispatcher->controller->name); + + $url = new CakeRequest('timesheets/'); + $Dispatcher->dispatch($url, $response, array('return' => 1)); + + $this->assertEquals('Timesheets', $Dispatcher->controller->name); + $this->assertEquals('/timesheets/index.php', $url->base); + + $url = new CakeRequest('test_dispatch_pages/camelCased'); + $Dispatcher->dispatch($url, $response, array('return' => 1)); + $this->assertEquals('TestDispatchPages', $Dispatcher->controller->name); + + $url = new CakeRequest('test_dispatch_pages/camelCased/something. .'); + $Dispatcher->dispatch($url, $response, array('return' => 1)); + $this->assertEquals('something. .', $Dispatcher->controller->params['pass'][0], 'Period was chopped off. %s'); + } + +/** + * Test that Dispatcher handles actions that return response objects. + * + * @return void + */ + public function testDispatchActionReturnsResponse() { + Router::connect('/:controller/:action'); + $Dispatcher = new Dispatcher(); + $request = new CakeRequest('some_pages/responseGenerator'); + $response = $this->getMock('CakeResponse', array('_sendHeader')); + + ob_start(); + $Dispatcher->dispatch($request, $response); + $result = ob_get_clean(); + + $this->assertEquals('new response', $result); + } + +/** + * testAdminDispatch method + * + * @return void + */ + public function testAdminDispatch() { + $_POST = array(); + $Dispatcher = new TestDispatcher(); + Configure::write('Routing.prefixes', array('admin')); + Configure::write('App.baseUrl','/cake/repo/branches/1.2.x.x/index.php'); + $url = new CakeRequest('admin/test_dispatch_pages/index/param:value/param2:value2'); + $response = $this->getMock('CakeResponse'); + + Router::reload(); + $Dispatcher->dispatch($url, $response, array('return' => 1)); + + $this->assertEquals('TestDispatchPages', $Dispatcher->controller->name); + + $this->assertSame($Dispatcher->controller->passedArgs, array('param' => 'value', 'param2' => 'value2')); + $this->assertTrue($Dispatcher->controller->params['admin']); + + $expected = '/cake/repo/branches/1.2.x.x/index.php/admin/test_dispatch_pages/index/param:value/param2:value2'; + $this->assertSame($expected, $Dispatcher->controller->here); + + $expected = '/cake/repo/branches/1.2.x.x/index.php'; + $this->assertSame($expected, $Dispatcher->controller->base); + } + +/** + * testPluginDispatch method + * + * @return void + */ + public function testPluginDispatch() { + $_POST = array(); + + Router::reload(); + $Dispatcher = new TestDispatcher(); + Router::connect( + '/my_plugin/:controller/*', + array('plugin' => 'my_plugin', 'controller' => 'pages', 'action' => 'display') + ); + + $url = new CakeRequest('my_plugin/some_pages/home/param:value/param2:value2'); + $response = $this->getMock('CakeResponse'); + $Dispatcher->dispatch($url, $response, array('return' => 1)); + + $event = new CakeEvent('DispatcherTest', $Dispatcher, array('request' => $url)); + $Dispatcher->parseParams($event); + $expected = array( + 'pass' => array('home'), + 'named' => array('param' => 'value', 'param2' => 'value2'), 'plugin' => 'my_plugin', + 'controller' => 'some_pages', 'action' => 'display' + ); + foreach ($expected as $key => $value) { + $this->assertEquals($value, $url[$key], 'Value mismatch ' . $key . ' %'); + } + + $this->assertSame($Dispatcher->controller->plugin, 'MyPlugin'); + $this->assertSame($Dispatcher->controller->name, 'SomePages'); + $this->assertSame($Dispatcher->controller->params['controller'], 'some_pages'); + $this->assertSame($Dispatcher->controller->passedArgs, array('0' => 'home', 'param' => 'value', 'param2' => 'value2')); + } + +/** + * testAutomaticPluginDispatch method + * + * @return void + */ + public function testAutomaticPluginDispatch() { + $_POST = array(); + $_SERVER['PHP_SELF'] = '/cake/repo/branches/1.2.x.x/index.php'; + + Router::reload(); + $Dispatcher = new TestDispatcher(); + Router::connect( + '/my_plugin/:controller/:action/*', + array('plugin' => 'my_plugin', 'controller' => 'pages', 'action' => 'display') + ); + + $Dispatcher->base = false; + + $url = new CakeRequest('my_plugin/other_pages/index/param:value/param2:value2'); + $response = $this->getMock('CakeResponse'); + $Dispatcher->dispatch($url, $response, array('return' => 1)); + + $this->assertSame($Dispatcher->controller->plugin, 'MyPlugin'); + $this->assertSame($Dispatcher->controller->name, 'OtherPages'); + $this->assertSame($Dispatcher->controller->action, 'index'); + $this->assertSame($Dispatcher->controller->passedArgs, array('param' => 'value', 'param2' => 'value2')); + + $expected = '/cake/repo/branches/1.2.x.x/my_plugin/other_pages/index/param:value/param2:value2'; + $this->assertSame($expected, $url->here); + + $expected = '/cake/repo/branches/1.2.x.x'; + $this->assertSame($expected, $url->base); + } + +/** + * testAutomaticPluginControllerDispatch method + * + * @return void + */ + public function testAutomaticPluginControllerDispatch() { + $plugins = App::objects('plugin'); + $plugins[] = 'MyPlugin'; + $plugins[] = 'ArticlesTest'; + + CakePlugin::load('MyPlugin', array('path' => '/fake/path')); + + Router::reload(); + $Dispatcher = new TestDispatcher(); + $Dispatcher->base = false; + + $url = new CakeRequest('my_plugin/my_plugin/add/param:value/param2:value2'); + $response = $this->getMock('CakeResponse'); + + $Dispatcher->dispatch($url, $response, array('return' => 1)); + + $this->assertSame($Dispatcher->controller->plugin, 'MyPlugin'); + $this->assertSame($Dispatcher->controller->name, 'MyPlugin'); + $this->assertSame($Dispatcher->controller->action, 'add'); + $this->assertEquals(array('param' => 'value', 'param2' => 'value2'), $Dispatcher->controller->params['named']); + + Router::reload(); + require CAKE . 'Config' . DS . 'routes.php'; + $Dispatcher = new TestDispatcher(); + $Dispatcher->base = false; + + // Simulates the Route for a real plugin, installed in APP/plugins + Router::connect('/my_plugin/:controller/:action/*', array('plugin' => 'my_plugin')); + + $plugin = 'MyPlugin'; + $pluginUrl = Inflector::underscore($plugin); + + $url = new CakeRequest($pluginUrl); + $Dispatcher->dispatch($url, $response, array('return' => 1)); + $this->assertSame($Dispatcher->controller->plugin, 'MyPlugin'); + $this->assertSame($Dispatcher->controller->name, 'MyPlugin'); + $this->assertSame($Dispatcher->controller->action, 'index'); + + $expected = $pluginUrl; + $this->assertEquals($expected, $Dispatcher->controller->params['controller']); + + Configure::write('Routing.prefixes', array('admin')); + + Router::reload(); + require CAKE . 'Config' . DS . 'routes.php'; + $Dispatcher = new TestDispatcher(); + + $url = new CakeRequest('admin/my_plugin/my_plugin/add/5/param:value/param2:value2'); + $response = $this->getMock('CakeResponse'); + + $Dispatcher->dispatch($url, $response, array('return' => 1)); + + $this->assertEquals('my_plugin', $Dispatcher->controller->params['plugin']); + $this->assertEquals('my_plugin', $Dispatcher->controller->params['controller']); + $this->assertEquals('admin_add', $Dispatcher->controller->params['action']); + $this->assertEquals(array(5), $Dispatcher->controller->params['pass']); + $this->assertEquals(array('param' => 'value', 'param2' => 'value2'), $Dispatcher->controller->params['named']); + $this->assertSame($Dispatcher->controller->plugin, 'MyPlugin'); + $this->assertSame($Dispatcher->controller->name, 'MyPlugin'); + $this->assertSame($Dispatcher->controller->action, 'admin_add'); + + $expected = array(0 => 5, 'param' => 'value', 'param2' => 'value2'); + $this->assertEquals($expected, $Dispatcher->controller->passedArgs); + + Configure::write('Routing.prefixes', array('admin')); + CakePlugin::load('ArticlesTest', array('path' => '/fake/path')); + Router::reload(); + require CAKE . 'Config' . DS . 'routes.php'; + + $Dispatcher = new TestDispatcher(); + + $Dispatcher->dispatch(new CakeRequest('admin/articles_test'), $response, array('return' => 1)); + $this->assertSame($Dispatcher->controller->plugin, 'ArticlesTest'); + $this->assertSame($Dispatcher->controller->name, 'ArticlesTest'); + $this->assertSame($Dispatcher->controller->action, 'admin_index'); + + $expected = array( + 'pass' => array(), + 'named' => array(), + 'controller' => 'articles_test', + 'plugin' => 'articles_test', + 'action' => 'admin_index', + 'prefix' => 'admin', + 'admin' => true, + 'return' => 1 + ); + foreach ($expected as $key => $value) { + $this->assertEquals($expected[$key], $Dispatcher->controller->request[$key], 'Value mismatch ' . $key); + } + } + +/** + * test Plugin dispatching without controller name and using + * plugin short form instead. + * + * @return void + */ + public function testAutomaticPluginDispatchWithShortAccess() { + CakePlugin::load('MyPlugin', array('path' => '/fake/path')); + Router::reload(); + + $Dispatcher = new TestDispatcher(); + $Dispatcher->base = false; + + $url = new CakeRequest('my_plugin/'); + $response = $this->getMock('CakeResponse'); + + $Dispatcher->dispatch($url, $response, array('return' => 1)); + $this->assertEquals('my_plugin', $Dispatcher->controller->params['controller']); + $this->assertEquals('my_plugin', $Dispatcher->controller->params['plugin']); + $this->assertEquals('index', $Dispatcher->controller->params['action']); + $this->assertFalse(isset($Dispatcher->controller->params['pass'][0])); + } + +/** + * test plugin shortcut urls with controllers that need to be loaded, + * the above test uses a controller that has already been included. + * + * @return void + */ + public function testPluginShortCutUrlsWithControllerThatNeedsToBeLoaded() { + $loaded = class_exists('TestPluginController', false); + $this->skipIf($loaded, 'TestPluginController already loaded.'); + + Router::reload(); + App::build(array( + 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS) + ), App::RESET); + CakePlugin::load(array('TestPlugin', 'TestPluginTwo')); + + $Dispatcher = new TestDispatcher(); + $Dispatcher->base = false; + + $url = new CakeRequest('test_plugin/'); + $response = $this->getMock('CakeResponse'); + + $Dispatcher->dispatch($url, $response, array('return' => 1)); + $this->assertEquals('test_plugin', $Dispatcher->controller->params['controller']); + $this->assertEquals('test_plugin', $Dispatcher->controller->params['plugin']); + $this->assertEquals('index', $Dispatcher->controller->params['action']); + $this->assertFalse(isset($Dispatcher->controller->params['pass'][0])); + + $url = new CakeRequest('/test_plugin/tests/index'); + $Dispatcher->dispatch($url, $response, array('return' => 1)); + $this->assertEquals('tests', $Dispatcher->controller->params['controller']); + $this->assertEquals('test_plugin', $Dispatcher->controller->params['plugin']); + $this->assertEquals('index', $Dispatcher->controller->params['action']); + $this->assertFalse(isset($Dispatcher->controller->params['pass'][0])); + + $url = new CakeRequest('/test_plugin/tests/index/some_param'); + $Dispatcher->dispatch($url, $response, array('return' => 1)); + $this->assertEquals('tests', $Dispatcher->controller->params['controller']); + $this->assertEquals('test_plugin', $Dispatcher->controller->params['plugin']); + $this->assertEquals('index', $Dispatcher->controller->params['action']); + $this->assertEquals('some_param', $Dispatcher->controller->params['pass'][0]); + + App::build(); + } + +/** + * testAutomaticPluginControllerMissingActionDispatch method + * + * @expectedException MissingActionException + * @expectedExceptionMessage Action MyPluginController::not_here() could not be found. + * @return void + */ + public function testAutomaticPluginControllerMissingActionDispatch() { + Router::reload(); + $Dispatcher = new TestDispatcher(); + + $url = new CakeRequest('my_plugin/not_here/param:value/param2:value2'); + $response = $this->getMock('CakeResponse'); + + $Dispatcher->dispatch($url, $response, array('return' => 1)); + } + +/** + * testAutomaticPluginControllerMissingActionDispatch method + * + * @expectedException MissingActionException + * @expectedExceptionMessage Action MyPluginController::param:value() could not be found. + * @return void + */ + + public function testAutomaticPluginControllerIndexMissingAction() { + Router::reload(); + $Dispatcher = new TestDispatcher(); + + $url = new CakeRequest('my_plugin/param:value/param2:value2'); + $response = $this->getMock('CakeResponse'); + + $Dispatcher->dispatch($url, $response, array('return' => 1)); + } + +/** + * Test dispatching into the TestPlugin in the test_app + * + * @return void + */ + public function testTestPluginDispatch() { + $Dispatcher = new TestDispatcher(); + App::build(array( + 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS) + ), App::RESET); + CakePlugin::load(array('TestPlugin', 'TestPluginTwo')); + Router::reload(); + Router::parse('/'); + + $url = new CakeRequest('/test_plugin/tests/index'); + $response = $this->getMock('CakeResponse'); + $Dispatcher->dispatch($url, $response, array('return' => 1)); + $this->assertTrue(class_exists('TestsController')); + $this->assertTrue(class_exists('TestPluginAppController')); + $this->assertTrue(class_exists('PluginsComponent')); + + $this->assertEquals('tests', $Dispatcher->controller->params['controller']); + $this->assertEquals('test_plugin', $Dispatcher->controller->params['plugin']); + $this->assertEquals('index', $Dispatcher->controller->params['action']); + + App::build(); + } + +/** + * Tests that it is possible to attach filter classes to the dispatch cycle + * + * @return void + */ + public function testDispatcherFilterSuscriber() { + App::build(array( + 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS), + 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS) + ), App::RESET); + + CakePlugin::load('TestPlugin'); + Configure::write('Dispatcher.filters', array( + array('callable' => 'TestPlugin.TestDispatcherFilter') + )); + $dispatcher = new TestDispatcher(); + $request = new CakeRequest('/'); + $request->params['altered'] = false; + $response = $this->getMock('CakeResponse', array('send')); + + $dispatcher->dispatch($request, $response); + $this->assertTrue($request->params['altered']); + $this->assertEquals(304, $response->statusCode()); + + Configure::write('Dispatcher.filters', array( + 'TestPlugin.Test2DispatcherFilter', + 'TestPlugin.TestDispatcherFilter' + )); + $dispatcher = new TestDispatcher(); + $request = new CakeRequest('/'); + $request->params['altered'] = false; + $response = $this->getMock('CakeResponse', array('send')); + + $dispatcher->dispatch($request, $response); + $this->assertFalse($request->params['altered']); + $this->assertEquals(500, $response->statusCode()); + $this->assertNull($dispatcher->controller); + } + +/** + * Tests that attaching an inexistent class as filter will throw an exception + * + * @expectedException MissingDispatcherFilterException + * @return void + */ + public function testDispatcherFilterSuscriberMissing() { + App::build(array( + 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS) + ), App::RESET); + + CakePlugin::load('TestPlugin'); + Configure::write('Dispatcher.filters', array( + array('callable' => 'TestPlugin.NotAFilter') + )); + $dispatcher = new TestDispatcher(); + $request = new CakeRequest('/'); + $response = $this->getMock('CakeResponse', array('send')); + $dispatcher->dispatch($request, $response); + } + +/** + * Tests it is possible to attach single callables as filters + * + * @return void + */ + public function testDispatcherFilterCallable() { + App::build(array( + 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS) + ), App::RESET); + + $dispatcher = new TestDispatcher(); + Configure::write('Dispatcher.filters', array( + array('callable' => array($dispatcher, 'filterTest'), 'on' => 'before') + )); + + $request = new CakeRequest('/'); + $response = $this->getMock('CakeResponse', array('send')); + $dispatcher->dispatch($request, $response); + $this->assertEquals('Dispatcher.beforeDispatch', $request->params['eventName']); + + $dispatcher = new TestDispatcher(); + Configure::write('Dispatcher.filters', array( + array('callable' => array($dispatcher, 'filterTest'), 'on' => 'after') + )); + + $request = new CakeRequest('/'); + $response = $this->getMock('CakeResponse', array('send')); + $dispatcher->dispatch($request, $response); + $this->assertEquals('Dispatcher.afterDispatch', $request->params['eventName']); + + // Test that it is possible to skip the route connection process + $dispatcher = new TestDispatcher(); + Configure::write('Dispatcher.filters', array( + array('callable' => array($dispatcher, 'filterTest2'), 'on' => 'before', 'priority' => 1) + )); + + $request = new CakeRequest('/'); + $response = $this->getMock('CakeResponse', array('send')); + $dispatcher->dispatch($request, $response); + $this->assertEmpty($dispatcher->controller); + $expected = array('controller' => null, 'action' => null, 'plugin' => null, 'named' => array(), 'pass' => array()); + $this->assertEquals($expected, $request->params); + + $dispatcher = new TestDispatcher(); + Configure::write('Dispatcher.filters', array( + array('callable' => array($dispatcher, 'filterTest2'), 'on' => 'before', 'priority' => 1) + )); + + $request = new CakeRequest('/'); + $request->params['return'] = true; + $response = $this->getMock('CakeResponse', array('send')); + $response->body('this is a body'); + $result = $dispatcher->dispatch($request, $response); + $this->assertEquals('this is a body', $result); + + $request = new CakeRequest('/'); + $response = $this->getMock('CakeResponse', array('send')); + $response->expects($this->once())->method('send'); + $response->body('this is a body'); + $result = $dispatcher->dispatch($request, $response); + $this->assertNull($result); + } + +/** + * testChangingParamsFromBeforeFilter method + * + * @return void + */ + public function testChangingParamsFromBeforeFilter() { + $Dispatcher = new TestDispatcher(); + $response = $this->getMock('CakeResponse'); + $url = new CakeRequest('some_posts/index/param:value/param2:value2'); + + try { + $Dispatcher->dispatch($url, $response, array('return' => 1)); + $this->fail('No exception.'); + } catch (MissingActionException $e) { + $this->assertEquals('Action SomePostsController::view() could not be found.', $e->getMessage()); + } + + $url = new CakeRequest('some_posts/something_else/param:value/param2:value2'); + $Dispatcher->dispatch($url, $response, array('return' => 1)); + + $expected = 'SomePosts'; + $this->assertEquals($expected, $Dispatcher->controller->name); + + $expected = 'change'; + $this->assertEquals($expected, $Dispatcher->controller->action); + + $expected = array('changed'); + $this->assertSame($expected, $Dispatcher->controller->params['pass']); + } + +/** + * testStaticAssets method + * + * @return void + */ + public function testAssets() { + Router::reload(); + + App::build(array( + 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS), + 'Vendor' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Vendor' . DS), + 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS) + )); + CakePlugin::load(array('TestPlugin', 'TestPluginTwo')); + Configure::write('Dispatcher.filters', array('AssetDispatcher')); + + $Dispatcher = new TestDispatcher(); + $response = $this->getMock('CakeResponse', array('_sendHeader')); + + try { + $Dispatcher->dispatch(new CakeRequest('theme/test_theme/../webroot/css/test_asset.css'), $response); + $this->fail('No exception'); + } catch (MissingControllerException $e) { + $this->assertEquals('Controller class ThemeController could not be found.', $e->getMessage()); + } + + try { + $Dispatcher->dispatch(new CakeRequest('theme/test_theme/pdfs'), $response); + $this->fail('No exception'); + } catch (MissingControllerException $e) { + $this->assertEquals('Controller class ThemeController could not be found.', $e->getMessage()); + } + } + +/** + * Data provider for asset filter + * + * - theme assets. + * - plugin assets. + * - plugin assets in sub directories. + * - unknown plugin assets. + * + * @return array + */ + public static function assetProvider() { + return array( + array( + 'theme/test_theme/flash/theme_test.swf', + 'View/Themed/TestTheme/webroot/flash/theme_test.swf' + ), + array( + 'theme/test_theme/pdfs/theme_test.pdf', + 'View/Themed/TestTheme/webroot/pdfs/theme_test.pdf' + ), + array( + 'theme/test_theme/img/test.jpg', + 'View/Themed/TestTheme/webroot/img/test.jpg' + ), + array( + 'theme/test_theme/css/test_asset.css', + 'View/Themed/TestTheme/webroot/css/test_asset.css' + ), + array( + 'theme/test_theme/js/theme.js', + 'View/Themed/TestTheme/webroot/js/theme.js' + ), + array( + 'theme/test_theme/js/one/theme_one.js', + 'View/Themed/TestTheme/webroot/js/one/theme_one.js' + ), + array( + 'theme/test_theme/space%20image.text', + 'View/Themed/TestTheme/webroot/space image.text' + ), + array( + 'test_plugin/root.js', + 'Plugin/TestPlugin/webroot/root.js' + ), + array( + 'test_plugin/flash/plugin_test.swf', + 'Plugin/TestPlugin/webroot/flash/plugin_test.swf' + ), + array( + 'test_plugin/pdfs/plugin_test.pdf', + 'Plugin/TestPlugin/webroot/pdfs/plugin_test.pdf' + ), + array( + 'test_plugin/js/test_plugin/test.js', + 'Plugin/TestPlugin/webroot/js/test_plugin/test.js' + ), + array( + 'test_plugin/css/test_plugin_asset.css', + 'Plugin/TestPlugin/webroot/css/test_plugin_asset.css' + ), + array( + 'test_plugin/img/cake.icon.gif', + 'Plugin/TestPlugin/webroot/img/cake.icon.gif' + ), + array( + 'plugin_js/js/plugin_js.js', + 'Plugin/PluginJs/webroot/js/plugin_js.js' + ), + array( + 'plugin_js/js/one/plugin_one.js', + 'Plugin/PluginJs/webroot/js/one/plugin_one.js' + ), + array( + 'test_plugin/css/unknown.extension', + 'Plugin/TestPlugin/webroot/css/unknown.extension' + ), + array( + 'test_plugin/css/theme_one.htc', + 'Plugin/TestPlugin/webroot/css/theme_one.htc' + ), + ); + } + +/** + * Test assets + * + * @dataProvider assetProvider + * @outputBuffering enabled + * @return void + */ + public function testAsset($url, $file) { + Router::reload(); + + App::build(array( + 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS), + 'Vendor' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Vendor' . DS), + 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS) + )); + CakePlugin::load(array('TestPlugin', 'PluginJs')); + Configure::write('Dispatcher.filters', array('AssetDispatcher')); + + $Dispatcher = new TestDispatcher(); + $response = $this->getMock('CakeResponse', array('_sendHeader')); + + $Dispatcher->dispatch(new CakeRequest($url), $response); + $result = ob_get_clean(); + + $path = CAKE . 'Test' . DS . 'test_app' . DS . str_replace('/', DS, $file); + $file = file_get_contents($path); + $this->assertEquals($file, $result); + + $expected = filesize($path); + $headers = $response->header(); + $this->assertEquals($expected, $headers['Content-Length']); + } + +/** + * test that missing asset processors trigger a 404 with no response body. + * + * @return void + */ + public function testMissingAssetProcessor404() { + $response = $this->getMock('CakeResponse', array('send')); + $Dispatcher = new TestDispatcher(); + Configure::write('Asset.filter', array( + 'js' => '', + 'css' => null + )); + Configure::write('Dispatcher.filters', array('AssetDispatcher')); + + $request = new CakeRequest('ccss/cake.generic.css'); + $Dispatcher->dispatch($request, $response); + $this->assertEquals('404', $response->statusCode()); + } + +/** + * Data provider for cached actions. + * + * - Test simple views + * - Test views with nocache tags + * - Test requests with named + passed params. + * - Test requests with query string params + * - Test themed views. + * + * @return array + */ + public static function cacheActionProvider() { + return array( + array('/'), + array('test_cached_pages/index'), + array('TestCachedPages/index'), + array('test_cached_pages/test_nocache_tags'), + array('TestCachedPages/test_nocache_tags'), + array('test_cached_pages/view/param/param'), + array('test_cached_pages/view/foo:bar/value:goo'), + array('test_cached_pages/view?q=cakephp'), + array('test_cached_pages/themed'), + ); + } + +/** + * testFullPageCachingDispatch method + * + * @dataProvider cacheActionProvider + * @return void + */ + public function testFullPageCachingDispatch($url) { + Configure::write('Cache.disable', false); + Configure::write('Cache.check', true); + Configure::write('debug', 2); + + Router::reload(); + Router::connect('/', array('controller' => 'test_cached_pages', 'action' => 'index')); + Router::connect('/:controller/:action/*'); + + App::build(array( + 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS), + ), App::RESET); + + $dispatcher = new TestDispatcher(); + $request = new CakeRequest($url); + $response = $this->getMock('CakeResponse', array('send')); + + $dispatcher->dispatch($request, $response); + $out = $response->body(); + + Configure::write('Dispatcher.filters', array('CacheDispatcher')); + $request = new CakeRequest($url); + $response = $this->getMock('CakeResponse', array('send')); + $dispatcher = new TestDispatcher(); + $dispatcher->dispatch($request, $response); + $cached = $response->body(); + + $cached = preg_replace('//', '', $cached); + + $this->assertTextEquals($out, $cached); + + $filename = $this->__cachePath($request->here()); + unlink($filename); + } + +/** + * testHttpMethodOverrides method + * + * @return void + */ + public function testHttpMethodOverrides() { + Router::reload(); + Router::mapResources('Posts'); + + $_SERVER['REQUEST_METHOD'] = 'POST'; + $dispatcher = new Dispatcher(); + + $request = new CakeRequest('/posts'); + $event = new CakeEvent('DispatcherTest', $dispatcher, array('request' => $request)); + $dispatcher->parseParams($event); + $expected = array('pass' => array(), 'named' => array(), 'plugin' => null, 'controller' => 'posts', 'action' => 'add', '[method]' => 'POST'); + foreach ($expected as $key => $value) { + $this->assertEquals($value, $request[$key], 'Value mismatch for ' . $key . ' %s'); + } + + $_SERVER['REQUEST_METHOD'] = 'GET'; + $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'] = 'PUT'; + + $request = new CakeRequest('/posts/5'); + $event = new CakeEvent('DispatcherTest', $dispatcher, array('request' => $request)); + $dispatcher->parseParams($event); + $expected = array( + 'pass' => array('5'), + 'named' => array(), + 'id' => '5', + 'plugin' => null, + 'controller' => 'posts', + 'action' => 'edit', + '[method]' => 'PUT' + ); + foreach ($expected as $key => $value) { + $this->assertEquals($value, $request[$key], 'Value mismatch for ' . $key . ' %s'); + } + + unset($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE']); + $_SERVER['REQUEST_METHOD'] = 'GET'; + + $request = new CakeRequest('/posts/5'); + $event = new CakeEvent('DispatcherTest', $dispatcher, array('request' => $request)); + $dispatcher->parseParams($event); + $expected = array('pass' => array('5'), 'named' => array(), 'id' => '5', 'plugin' => null, 'controller' => 'posts', 'action' => 'view', '[method]' => 'GET'); + foreach ($expected as $key => $value) { + $this->assertEquals($value, $request[$key], 'Value mismatch for ' . $key . ' %s'); + } + + $_POST['_method'] = 'PUT'; + + $request = new CakeRequest('/posts/5'); + $event = new CakeEvent('DispatcherTest', $dispatcher, array('request' => $request)); + $dispatcher->parseParams($event); + $expected = array('pass' => array('5'), 'named' => array(), 'id' => '5', 'plugin' => null, 'controller' => 'posts', 'action' => 'edit', '[method]' => 'PUT'); + foreach ($expected as $key => $value) { + $this->assertEquals($value, $request[$key], 'Value mismatch for ' . $key . ' %s'); + } + + $_POST['_method'] = 'POST'; + $_POST['data'] = array('Post' => array('title' => 'New Post')); + $_POST['extra'] = 'data'; + $_SERVER = array(); + + $request = new CakeRequest('/posts'); + $event = new CakeEvent('DispatcherTest', $dispatcher, array('request' => $request)); + $dispatcher->parseParams($event); + $expected = array( + 'pass' => array(), 'named' => array(), 'plugin' => null, 'controller' => 'posts', 'action' => 'add', + '[method]' => 'POST', 'data' => array('extra' => 'data', 'Post' => array('title' => 'New Post')), + ); + foreach ($expected as $key => $value) { + $this->assertEquals($value, $request[$key], 'Value mismatch for ' . $key . ' %s'); + } + + unset($_POST['_method']); + } + +/** + * backupEnvironment method + * + * @return void + */ + protected function __backupEnvironment() { + return array( + 'App' => Configure::read('App'), + 'GET' => $_GET, + 'POST' => $_POST, + 'SERVER' => $_SERVER + ); + } + +/** + * reloadEnvironment method + * + * @return void + */ + protected function __reloadEnvironment() { + foreach ($_GET as $key => $val) { + unset($_GET[$key]); + } + foreach ($_POST as $key => $val) { + unset($_POST[$key]); + } + foreach ($_SERVER as $key => $val) { + unset($_SERVER[$key]); + } + Configure::write('App', array()); + } + +/** + * loadEnvironment method + * + * @param array $env + * @return void + */ + protected function __loadEnvironment($env) { + if ($env['reload']) { + $this->__reloadEnvironment(); + } + + if (isset($env['App'])) { + Configure::write('App', $env['App']); + } + + if (isset($env['GET'])) { + foreach ($env['GET'] as $key => $val) { + $_GET[$key] = $val; + } + } + + if (isset($env['POST'])) { + foreach ($env['POST'] as $key => $val) { + $_POST[$key] = $val; + } + } + + if (isset($env['SERVER'])) { + foreach ($env['SERVER'] as $key => $val) { + $_SERVER[$key] = $val; + } + } + } + +/** + * cachePath method + * + * @param string $here + * @return string + */ + protected function __cachePath($here) { + $path = $here; + if ($here == '/') { + $path = 'home'; + } + $path = strtolower(Inflector::slug($path)); + + $filename = CACHE . 'views' . DS . $path . '.php'; + + if (!file_exists($filename)) { + $filename = CACHE . 'views' . DS . $path . '_index.php'; + } + return $filename; + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Routing/Filter/AssetDispatcherTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Routing/Filter/AssetDispatcherTest.php new file mode 100644 index 0000000..28d44b4 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Routing/Filter/AssetDispatcherTest.php @@ -0,0 +1,124 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The Open Group Test Suite License + * Redistributions of files must retain the above copyright notice. + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/view/1196/Testing CakePHP(tm) Tests + * @package Cake.Test.Case.Routing.Filter + * @since CakePHP(tm) v 2.2 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ + +App::uses('AssetDispatcher', 'Routing/Filter'); +App::uses('CakeEvent', 'Event'); +App::uses('CakeResponse', 'Network'); + +class AssetDispatcherTest extends CakeTestCase { + +/** + * tearDown method + * + * @return void + */ + public function tearDown() { + Configure::write('Dispatcher.filters', array()); + } + +/** + * test that asset filters work for theme and plugin assets + * + * @return void + */ + public function testAssetFilterForThemeAndPlugins() { + $filter = new AssetDispatcher(); + $response = $this->getMock('CakeResponse', array('_sendHeader')); + Configure::write('Asset.filter', array( + 'js' => '', + 'css' => '' + )); + App::build(array( + 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS), + 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS) + ), APP::RESET); + + $request = new CakeRequest('theme/test_theme/ccss/cake.generic.css'); + $event = new CakeEvent('DispatcherTest', $this, compact('request', 'response')); + $this->assertSame($response, $filter->beforeDispatch($event)); + $this->assertTrue($event->isStopped()); + + $request = new CakeRequest('theme/test_theme/cjs/debug_kit.js'); + $event = new CakeEvent('DispatcherTest', $this, compact('request', 'response')); + $this->assertSame($response, $filter->beforeDispatch($event)); + $this->assertTrue($event->isStopped()); + + $request = new CakeRequest('test_plugin/ccss/cake.generic.css'); + $event = new CakeEvent('DispatcherTest', $this, compact('request', 'response')); + $this->assertSame($response, $filter->beforeDispatch($event)); + $this->assertTrue($event->isStopped()); + + $request = new CakeRequest('test_plugin/cjs/debug_kit.js'); + $event = new CakeEvent('DispatcherTest', $this, compact('request', 'response')); + $this->assertSame($response, $filter->beforeDispatch($event)); + $this->assertTrue($event->isStopped()); + + $request = new CakeRequest('css/ccss/debug_kit.css'); + $event = new CakeEvent('DispatcherTest', $this, compact('request', 'response')); + $this->assertNull($filter->beforeDispatch($event)); + $this->assertFalse($event->isStopped()); + + $request = new CakeRequest('js/cjs/debug_kit.js'); + $event = new CakeEvent('DispatcherTest', $this, compact('request', 'response')); + $this->assertNull($filter->beforeDispatch($event)); + $this->assertFalse($event->isStopped()); + } + +/** + * Tests that $response->checkNotModified() is called and bypasses + * file dispatching + * + * @return void + */ + public function testNotModified() { + $filter = new AssetDispatcher(); + Configure::write('Asset.filter', array( + 'js' => '', + 'css' => '' + )); + App::build(array( + 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS), + 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS) + )); + $time = filemtime(App::themePath('TestTheme') . 'webroot' . DS . 'img' . DS . 'cake.power.gif'); + $time = new DateTime('@' . $time); + + $response = $this->getMock('CakeResponse', array('send', 'checkNotModified')); + $request = new CakeRequest('theme/test_theme/img/cake.power.gif'); + + $response->expects($this->once())->method('checkNotModified') + ->with($request) + ->will($this->returnValue(true)); + $event = new CakeEvent('DispatcherTest', $this, compact('request', 'response')); + + ob_start(); + $this->assertSame($response, $filter->beforeDispatch($event)); + ob_end_clean(); + $this->assertEquals(200, $response->statusCode()); + $this->assertEquals($time->format('D, j M Y H:i:s') . ' GMT', $response->modified()); + + $response = $this->getMock('CakeResponse', array('_sendHeader', 'checkNotModified')); + $request = new CakeRequest('theme/test_theme/img/cake.power.gif'); + + $response->expects($this->once())->method('checkNotModified') + ->with($request) + ->will($this->returnValue(true)); + $response->expects($this->never())->method('send'); + $event = new CakeEvent('DispatcherTest', $this, compact('request', 'response')); + + $this->assertSame($response, $filter->beforeDispatch($event)); + $this->assertEquals($time->format('D, j M Y H:i:s') . ' GMT', $response->modified()); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Routing/Route/CakeRouteTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Routing/Route/CakeRouteTest.php new file mode 100644 index 0000000..c393dc2 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Routing/Route/CakeRouteTest.php @@ -0,0 +1,883 @@ + null, 'prefixes' => array())); + } + +/** + * Test the construction of a CakeRoute + * + * @return void + **/ + public function testConstruction() { + $route = new CakeRoute('/:controller/:action/:id', array(), array('id' => '[0-9]+')); + + $this->assertEquals('/:controller/:action/:id', $route->template); + $this->assertEquals(array(), $route->defaults); + $this->assertEquals(array('id' => '[0-9]+'), $route->options); + $this->assertFalse($route->compiled()); + } + +/** + * test Route compiling. + * + * @return void + **/ + public function testBasicRouteCompiling() { + $route = new CakeRoute('/', array('controller' => 'pages', 'action' => 'display', 'home')); + $result = $route->compile(); + $expected = '#^/*$#'; + $this->assertEquals($expected, $result); + $this->assertEquals(array(), $route->keys); + + $route = new CakeRoute('/:controller/:action', array('controller' => 'posts')); + $result = $route->compile(); + + $this->assertRegExp($result, '/posts/edit'); + $this->assertRegExp($result, '/posts/super_delete'); + $this->assertNotRegExp($result, '/posts'); + $this->assertNotRegExp($result, '/posts/super_delete/1'); + + $route = new CakeRoute('/posts/foo:id', array('controller' => 'posts', 'action' => 'view')); + $result = $route->compile(); + + $this->assertRegExp($result, '/posts/foo:1'); + $this->assertRegExp($result, '/posts/foo:param'); + $this->assertNotRegExp($result, '/posts'); + $this->assertNotRegExp($result, '/posts/'); + + $this->assertEquals(array('id'), $route->keys); + + $route = new CakeRoute('/:plugin/:controller/:action/*', array('plugin' => 'test_plugin', 'action' => 'index')); + $result = $route->compile(); + $this->assertRegExp($result, '/test_plugin/posts/index'); + $this->assertRegExp($result, '/test_plugin/posts/edit/5'); + $this->assertRegExp($result, '/test_plugin/posts/edit/5/name:value/nick:name'); + } + +/** + * test that route parameters that overlap don't cause errors. + * + * @return void + */ + public function testRouteParameterOverlap() { + $route = new CakeRoute('/invoices/add/:idd/:id', array('controller' => 'invoices', 'action' => 'add')); + $result = $route->compile(); + $this->assertRegExp($result, '/invoices/add/1/3'); + + $route = new CakeRoute('/invoices/add/:id/:idd', array('controller' => 'invoices', 'action' => 'add')); + $result = $route->compile(); + $this->assertRegExp($result, '/invoices/add/1/3'); + } + +/** + * test compiling routes with keys that have patterns + * + * @return void + **/ + public function testRouteCompilingWithParamPatterns() { + $route = new CakeRoute( + '/:controller/:action/:id', + array(), + array('id' => Router::ID) + ); + $result = $route->compile(); + $this->assertRegExp($result, '/posts/edit/1'); + $this->assertRegExp($result, '/posts/view/518098'); + $this->assertNotRegExp($result, '/posts/edit/name-of-post'); + $this->assertNotRegExp($result, '/posts/edit/4/other:param'); + $this->assertEquals(array('controller', 'action', 'id'), $route->keys); + + $route = new CakeRoute( + '/:lang/:controller/:action/:id', + array('controller' => 'testing4'), + array('id' => Router::ID, 'lang' => '[a-z]{3}') + ); + $result = $route->compile(); + $this->assertRegExp($result, '/eng/posts/edit/1'); + $this->assertRegExp($result, '/cze/articles/view/1'); + $this->assertNotRegExp($result, '/language/articles/view/2'); + $this->assertNotRegExp($result, '/eng/articles/view/name-of-article'); + $this->assertEquals(array('lang', 'controller', 'action', 'id'), $route->keys); + + foreach (array(':', '@', ';', '$', '-') as $delim) { + $route = new CakeRoute('/posts/:id' . $delim . ':title'); + $result = $route->compile(); + + $this->assertRegExp($result, '/posts/1' . $delim . 'name-of-article'); + $this->assertRegExp($result, '/posts/13244' . $delim . 'name-of_Article[]'); + $this->assertNotRegExp($result, '/posts/11!nameofarticle'); + $this->assertNotRegExp($result, '/posts/11'); + + $this->assertEquals(array('id', 'title'), $route->keys); + } + + $route = new CakeRoute( + '/posts/:id::title/:year', + array('controller' => 'posts', 'action' => 'view'), + array('id' => Router::ID, 'year' => Router::YEAR, 'title' => '[a-z-_]+') + ); + $result = $route->compile(); + $this->assertRegExp($result, '/posts/1:name-of-article/2009/'); + $this->assertRegExp($result, '/posts/13244:name-of-article/1999'); + $this->assertNotRegExp($result, '/posts/hey_now:nameofarticle'); + $this->assertNotRegExp($result, '/posts/:nameofarticle/2009'); + $this->assertNotRegExp($result, '/posts/:nameofarticle/01'); + $this->assertEquals(array('id', 'title', 'year'), $route->keys); + + $route = new CakeRoute( + '/posts/:url_title-(uuid::id)', + array('controller' => 'posts', 'action' => 'view'), + array('pass' => array('id', 'url_title'), 'id' => Router::ID) + ); + $result = $route->compile(); + $this->assertRegExp($result, '/posts/some_title_for_article-(uuid:12534)/'); + $this->assertRegExp($result, '/posts/some_title_for_article-(uuid:12534)'); + $this->assertNotRegExp($result, '/posts/'); + $this->assertNotRegExp($result, '/posts/nameofarticle'); + $this->assertNotRegExp($result, '/posts/nameofarticle-12347'); + $this->assertEquals(array('url_title', 'id'), $route->keys); + } + +/** + * test more complex route compiling & parsing with mid route greedy stars + * and optional routing parameters + * + * @return void + */ + public function testComplexRouteCompilingAndParsing() { + $route = new CakeRoute( + '/posts/:month/:day/:year/*', + array('controller' => 'posts', 'action' => 'view'), + array('year' => Router::YEAR, 'month' => Router::MONTH, 'day' => Router::DAY) + ); + $result = $route->compile(); + $this->assertRegExp($result, '/posts/08/01/2007/title-of-post'); + $result = $route->parse('/posts/08/01/2007/title-of-post'); + + $this->assertEquals(7, count($result)); + $this->assertEquals('posts', $result['controller']); + $this->assertEquals('view', $result['action']); + $this->assertEquals('2007', $result['year']); + $this->assertEquals('08', $result['month']); + $this->assertEquals('01', $result['day']); + $this->assertEquals('title-of-post', $result['pass'][0]); + + $route = new CakeRoute( + "/:extra/page/:slug/*", + array('controller' => 'pages', 'action' => 'view', 'extra' => null), + array("extra" => '[a-z1-9_]*', "slug" => '[a-z1-9_]+', "action" => 'view') + ); + $result = $route->compile(); + + $this->assertRegExp($result, '/some_extra/page/this_is_the_slug'); + $this->assertRegExp($result, '/page/this_is_the_slug'); + $this->assertEquals(array('extra', 'slug'), $route->keys); + $this->assertEquals(array('extra' => '[a-z1-9_]*', 'slug' => '[a-z1-9_]+', 'action' => 'view'), $route->options); + $expected = array( + 'controller' => 'pages', + 'action' => 'view' + ); + $this->assertEquals($expected, $route->defaults); + + $route = new CakeRoute( + '/:controller/:action/*', + array('project' => false), + array( + 'controller' => 'source|wiki|commits|tickets|comments|view', + 'action' => 'branches|history|branch|logs|view|start|add|edit|modify' + ) + ); + $this->assertFalse($route->parse('/chaw_test/wiki')); + + $result = $route->compile(); + $this->assertNotRegExp($result, '/some_project/source'); + $this->assertRegExp($result, '/source/view'); + $this->assertRegExp($result, '/source/view/other/params'); + $this->assertNotRegExp($result, '/chaw_test/wiki'); + $this->assertNotRegExp($result, '/source/wierd_action'); + } + +/** + * test that routes match their pattern. + * + * @return void + **/ + public function testMatchBasic() { + $route = new CakeRoute('/:controller/:action/:id', array('plugin' => null)); + $result = $route->match(array('controller' => 'posts', 'action' => 'view', 'plugin' => null)); + $this->assertFalse($result); + + $result = $route->match(array('plugin' => null, 'controller' => 'posts', 'action' => 'view', 0)); + $this->assertFalse($result); + + $result = $route->match(array('plugin' => null, 'controller' => 'posts', 'action' => 'view', 'id' => 1)); + $this->assertEquals('/posts/view/1', $result); + + $route = new CakeRoute('/', array('controller' => 'pages', 'action' => 'display', 'home')); + $result = $route->match(array('controller' => 'pages', 'action' => 'display', 'home')); + $this->assertEquals('/', $result); + + $result = $route->match(array('controller' => 'pages', 'action' => 'display', 'about')); + $this->assertFalse($result); + + $route = new CakeRoute('/pages/*', array('controller' => 'pages', 'action' => 'display')); + $result = $route->match(array('controller' => 'pages', 'action' => 'display', 'home')); + $this->assertEquals('/pages/home', $result); + + $result = $route->match(array('controller' => 'pages', 'action' => 'display', 'about')); + $this->assertEquals('/pages/about', $result); + + $route = new CakeRoute('/blog/:action', array('controller' => 'posts')); + $result = $route->match(array('controller' => 'posts', 'action' => 'view')); + $this->assertEquals('/blog/view', $result); + + $result = $route->match(array('controller' => 'nodes', 'action' => 'view')); + $this->assertFalse($result); + + $result = $route->match(array('controller' => 'posts', 'action' => 'view', 1)); + $this->assertFalse($result); + + $result = $route->match(array('controller' => 'posts', 'action' => 'view', 'id' => 2)); + $this->assertFalse($result); + + $route = new CakeRoute('/foo/:controller/:action', array('action' => 'index')); + $result = $route->match(array('controller' => 'posts', 'action' => 'view')); + $this->assertEquals('/foo/posts/view', $result); + + $route = new CakeRoute('/:plugin/:id/*', array('controller' => 'posts', 'action' => 'view')); + $result = $route->match(array('plugin' => 'test', 'controller' => 'posts', 'action' => 'view', 'id' => '1')); + $this->assertEquals('/test/1/', $result); + + $result = $route->match(array('plugin' => 'fo', 'controller' => 'posts', 'action' => 'view', 'id' => '1', '0')); + $this->assertEquals('/fo/1/0', $result); + + $result = $route->match(array('plugin' => 'fo', 'controller' => 'nodes', 'action' => 'view', 'id' => 1)); + $this->assertFalse($result); + + $result = $route->match(array('plugin' => 'fo', 'controller' => 'posts', 'action' => 'edit', 'id' => 1)); + $this->assertFalse($result); + + $route = new CakeRoute('/admin/subscriptions/:action/*', array( + 'controller' => 'subscribe', 'admin' => true, 'prefix' => 'admin' + )); + + $url = array('controller' => 'subscribe', 'admin' => true, 'action' => 'edit', 1); + $result = $route->match($url); + $expected = '/admin/subscriptions/edit/1'; + $this->assertEquals($expected, $result); + + $url = array( + 'controller' => 'subscribe', + 'admin' => true, + 'action' => 'edit_admin_e', + 1 + ); + $result = $route->match($url); + $expected = '/admin/subscriptions/edit_admin_e/1'; + $this->assertEquals($expected, $result); + } + +/** + * test that non-greedy routes fail with extra passed args + * + * @return void + */ + public function testGreedyRouteFailurePassedArg() { + $route = new CakeRoute('/:controller/:action', array('plugin' => null)); + $result = $route->match(array('controller' => 'posts', 'action' => 'view', '0')); + $this->assertFalse($result); + + $route = new CakeRoute('/:controller/:action', array('plugin' => null)); + $result = $route->match(array('controller' => 'posts', 'action' => 'view', 'test')); + $this->assertFalse($result); + } + +/** + * test that non-greedy routes fail with extra passed args + * + * @return void + */ + public function testGreedyRouteFailureNamedParam() { + $route = new CakeRoute('/:controller/:action', array('plugin' => null)); + $result = $route->match(array('controller' => 'posts', 'action' => 'view', 'page' => 1)); + $this->assertFalse($result); + } + +/** + * test that falsey values do not interrupt a match. + * + * @return void + */ + public function testMatchWithFalseyValues() { + $route = new CakeRoute('/:controller/:action/*', array('plugin' => null)); + $result = $route->match(array( + 'controller' => 'posts', 'action' => 'index', 'plugin' => null, 'admin' => false + )); + $this->assertEquals('/posts/index/', $result); + } + +/** + * test match() with greedy routes, named parameters and passed args. + * + * @return void + */ + public function testMatchWithNamedParametersAndPassedArgs() { + Router::connectNamed(true); + + $route = new CakeRoute('/:controller/:action/*', array('plugin' => null)); + $result = $route->match(array('controller' => 'posts', 'action' => 'index', 'plugin' => null, 'page' => 1)); + $this->assertEquals('/posts/index/page:1', $result); + + $result = $route->match(array('controller' => 'posts', 'action' => 'view', 'plugin' => null, 5)); + $this->assertEquals('/posts/view/5', $result); + + $result = $route->match(array('controller' => 'posts', 'action' => 'view', 'plugin' => null, 0)); + $this->assertEquals('/posts/view/0', $result); + + $result = $route->match(array('controller' => 'posts', 'action' => 'view', 'plugin' => null, '0')); + $this->assertEquals('/posts/view/0', $result); + + $result = $route->match(array('controller' => 'posts', 'action' => 'view', 'plugin' => null, 5, 'page' => 1, 'limit' => 20, 'order' => 'title')); + $this->assertEquals('/posts/view/5/page:1/limit:20/order:title', $result); + + $result = $route->match(array('controller' => 'posts', 'action' => 'view', 'plugin' => null, 'word space', 'order' => 'Θ')); + $this->assertEquals('/posts/view/word%20space/order:%CE%98', $result); + + $route = new CakeRoute('/test2/*', array('controller' => 'pages', 'action' => 'display', 2)); + $result = $route->match(array('controller' => 'pages', 'action' => 'display', 1)); + $this->assertFalse($result); + + $result = $route->match(array('controller' => 'pages', 'action' => 'display', 2, 'something')); + $this->assertEquals('/test2/something', $result); + + $result = $route->match(array('controller' => 'pages', 'action' => 'display', 5, 'something')); + $this->assertFalse($result); + } + +/** + * Ensure that named parameters are urldecoded + * + * @return void + */ + public function testParseNamedParametersUrlDecode() { + Router::connectNamed(true); + $route = new CakeRoute('/:controller/:action/*', array('plugin' => null)); + + $result = $route->parse('/posts/index/page:%CE%98'); + $this->assertEquals('Θ', $result['named']['page']); + + $result = $route->parse('/posts/index/page[]:%CE%98'); + $this->assertEquals('Θ', $result['named']['page'][0]); + + $result = $route->parse('/posts/index/something%20else/page[]:%CE%98'); + $this->assertEquals('Θ', $result['named']['page'][0]); + $this->assertEquals('something else', $result['pass'][0]); + } + +/** + * Ensure that keys at named parameters are urldecoded + * + * @return void + */ + public function testParseNamedKeyUrlDecode() { + Router::connectNamed(true); + $route = new CakeRoute('/:controller/:action/*', array('plugin' => null)); + + // checking /post/index/user[0]:a/user[1]:b + $result = $route->parse('/posts/index/user%5B0%5D:a/user%5B1%5D:b'); + $this->assertArrayHasKey('user', $result['named']); + $this->assertEquals(array('a', 'b'), $result['named']['user']); + + // checking /post/index/user[]:a/user[]:b + $result = $route->parse('/posts/index/user%5B%5D:a/user%5B%5D:b'); + $this->assertArrayHasKey('user', $result['named']); + $this->assertEquals(array('a', 'b'), $result['named']['user']); + } + +/** + * test that named params with null/false are excluded + * + * @return void + */ + public function testNamedParamsWithNullFalse() { + $route = new CakeRoute('/:controller/:action/*'); + $result = $route->match(array('controller' => 'posts', 'action' => 'index', 'page' => null, 'sort' => false)); + $this->assertEquals('/posts/index/', $result); + } + +/** + * test that match with patterns works. + * + * @return void + */ + public function testMatchWithPatterns() { + $route = new CakeRoute('/:controller/:action/:id', array('plugin' => null), array('id' => '[0-9]+')); + $result = $route->match(array('controller' => 'posts', 'action' => 'view', 'id' => 'foo')); + $this->assertFalse($result); + + $result = $route->match(array('plugin' => null, 'controller' => 'posts', 'action' => 'view', 'id' => '9')); + $this->assertEquals('/posts/view/9', $result); + + $result = $route->match(array('plugin' => null, 'controller' => 'posts', 'action' => 'view', 'id' => '922')); + $this->assertEquals('/posts/view/922', $result); + + $result = $route->match(array('plugin' => null, 'controller' => 'posts', 'action' => 'view', 'id' => 'a99')); + $this->assertFalse($result); + } + +/** + * test persistParams ability to persist parameters from $params and remove params. + * + * @return void + */ + public function testPersistParams() { + $route = new CakeRoute( + '/:lang/:color/blog/:action', + array('controller' => 'posts'), + array('persist' => array('lang', 'color')) + ); + $url = array('controller' => 'posts', 'action' => 'index'); + $params = array('lang' => 'en', 'color' => 'blue'); + $result = $route->persistParams($url, $params); + $this->assertEquals('en', $result['lang']); + $this->assertEquals('blue', $result['color']); + + $url = array('controller' => 'posts', 'action' => 'index', 'color' => 'red'); + $params = array('lang' => 'en', 'color' => 'blue'); + $result = $route->persistParams($url, $params); + $this->assertEquals('en', $result['lang']); + $this->assertEquals('red', $result['color']); + } + +/** + * test the parse method of CakeRoute. + * + * @return void + */ + public function testParse() { + $route = new CakeRoute( + '/:controller/:action/:id', + array('controller' => 'testing4', 'id' => null), + array('id' => Router::ID) + ); + $route->compile(); + $result = $route->parse('/posts/view/1'); + $this->assertEquals('posts', $result['controller']); + $this->assertEquals('view', $result['action']); + $this->assertEquals('1', $result['id']); + + $route = new Cakeroute( + '/admin/:controller', + array('prefix' => 'admin', 'admin' => 1, 'action' => 'index') + ); + $route->compile(); + $result = $route->parse('/admin/'); + $this->assertFalse($result); + + $result = $route->parse('/admin/posts'); + $this->assertEquals('posts', $result['controller']); + $this->assertEquals('index', $result['action']); + } + +/** + * Test that :key elements are urldecoded + * + * @return void + */ + public function testParseUrlDecodeElements() { + $route = new Cakeroute( + '/:controller/:slug', + array('action' => 'view') + ); + $route->compile(); + $result = $route->parse('/posts/%E2%88%82%E2%88%82'); + $this->assertEquals('posts', $result['controller']); + $this->assertEquals('view', $result['action']); + $this->assertEquals('∂∂', $result['slug']); + + $result = $route->parse('/posts/∂∂'); + $this->assertEquals('posts', $result['controller']); + $this->assertEquals('view', $result['action']); + $this->assertEquals('∂∂', $result['slug']); + } + +/** + * test numerically indexed defaults, get appended to pass + * + * @return void + */ + public function testParseWithPassDefaults() { + $route = new Cakeroute('/:controller', array('action' => 'display', 'home')); + $result = $route->parse('/posts'); + $expected = array( + 'controller' => 'posts', + 'action' => 'display', + 'pass' => array('home'), + 'named' => array() + ); + $this->assertEquals($expected, $result); + } + +/** + * test that http header conditions can cause route failures. + * + * @return void + */ + public function testParseWithHttpHeaderConditions() { + $_SERVER['REQUEST_METHOD'] = 'GET'; + $route = new CakeRoute('/sample', array('controller' => 'posts', 'action' => 'index', '[method]' => 'POST')); + + $this->assertFalse($route->parse('/sample')); + } + +/** + * test that patterns work for :action + * + * @return void + */ + public function testPatternOnAction() { + $route = new CakeRoute( + '/blog/:action/*', + array('controller' => 'blog_posts'), + array('action' => 'other|actions') + ); + $result = $route->match(array('controller' => 'blog_posts', 'action' => 'foo')); + $this->assertFalse($result); + + $result = $route->match(array('controller' => 'blog_posts', 'action' => 'actions')); + $this->assertNotEmpty($result); + + $result = $route->parse('/blog/other'); + $expected = array('controller' => 'blog_posts', 'action' => 'other', 'pass' => array(), 'named' => array()); + $this->assertEquals($expected, $result); + + $result = $route->parse('/blog/foobar'); + $this->assertFalse($result); + } + +/** + * test the parseArgs method + * + * @return void + */ + public function testParsePassedArgument() { + $route = new CakeRoute('/:controller/:action/*'); + $result = $route->parse('/posts/edit/1/2/0'); + $expected = array( + 'controller' => 'posts', + 'action' => 'edit', + 'pass' => array('1', '2', '0'), + 'named' => array() + ); + $this->assertEquals($expected, $result); + + $result = $route->parse('/posts/edit/a-string/page:1/sort:value'); + $expected = array( + 'controller' => 'posts', + 'action' => 'edit', + 'pass' => array('a-string'), + 'named' => array( + 'page' => 1, + 'sort' => 'value' + ) + ); + $this->assertEquals($expected, $result); + } + +/** + * test that only named parameter rules are followed. + * + * @return void + */ + public function testParseNamedParametersWithRules() { + $route = new CakeRoute('/:controller/:action/*', array(), array( + 'named' => array( + 'wibble', + 'fish' => array('action' => 'index'), + 'fizz' => array('controller' => array('comments', 'other')), + 'pattern' => 'val-[\d]+' + ) + )); + $result = $route->parse('/posts/display/wibble:spin/fish:trout/fizz:buzz/unknown:value'); + $expected = array( + 'controller' => 'posts', + 'action' => 'display', + 'pass' => array('fish:trout', 'fizz:buzz', 'unknown:value'), + 'named' => array( + 'wibble' => 'spin' + ) + ); + $this->assertEquals($expected, $result, 'Fish should not be parsed, as action != index'); + + $result = $route->parse('/posts/index/wibble:spin/fish:trout/fizz:buzz'); + $expected = array( + 'controller' => 'posts', + 'action' => 'index', + 'pass' => array('fizz:buzz'), + 'named' => array( + 'wibble' => 'spin', + 'fish' => 'trout' + ) + ); + $this->assertEquals($expected, $result, 'Fizz should be parsed, as controller == comments|other'); + + $result = $route->parse('/comments/index/wibble:spin/fish:trout/fizz:buzz'); + $expected = array( + 'controller' => 'comments', + 'action' => 'index', + 'pass' => array(), + 'named' => array( + 'wibble' => 'spin', + 'fish' => 'trout', + 'fizz' => 'buzz' + ) + ); + $this->assertEquals($expected, $result, 'All params should be parsed as conditions were met.'); + + $result = $route->parse('/comments/index/pattern:val--'); + $expected = array( + 'controller' => 'comments', + 'action' => 'index', + 'pass' => array('pattern:val--'), + 'named' => array() + ); + $this->assertEquals($expected, $result, 'Named parameter pattern unmet.'); + + $result = $route->parse('/comments/index/pattern:val-2'); + $expected = array( + 'controller' => 'comments', + 'action' => 'index', + 'pass' => array(), + 'named' => array('pattern' => 'val-2') + ); + $this->assertEquals($expected, $result, 'Named parameter pattern met.'); + } + +/** + * test that greedyNamed ignores rules. + * + * @return void + */ + public function testParseGreedyNamed() { + $route = new CakeRoute('/:controller/:action/*', array(), array( + 'named' => array( + 'fizz' => array('controller' => 'comments'), + 'pattern' => 'val-[\d]+', + ), + 'greedyNamed' => true + )); + $result = $route->parse('/posts/display/wibble:spin/fizz:buzz/pattern:ignored'); + $expected = array( + 'controller' => 'posts', + 'action' => 'display', + 'pass' => array('fizz:buzz', 'pattern:ignored'), + 'named' => array( + 'wibble' => 'spin', + ) + ); + $this->assertEquals($expected, $result, 'Greedy named grabs everything, rules are followed'); + } + +/** + * Having greedNamed enabled should not capture routing.prefixes. + * + * @return void + */ + public function testMatchGreedyNamedExcludesPrefixes() { + Configure::write('Routing.prefixes', array('admin')); + Router::reload(); + + $route = new CakeRoute('/sales/*', array('controller' => 'sales', 'action' => 'index')); + $this->assertFalse($route->match(array('controller' => 'sales', 'action' => 'index', 'admin' => 1)), 'Greedy named consume routing prefixes.'); + } + +/** + * test that parsing array format named parameters works + * + * @return void + */ + public function testParseArrayNamedParameters() { + $route = new CakeRoute('/:controller/:action/*'); + $result = $route->parse('/tests/action/var[]:val1/var[]:val2'); + $expected = array( + 'controller' => 'tests', + 'action' => 'action', + 'named' => array( + 'var' => array( + 'val1', + 'val2' + ) + ), + 'pass' => array(), + ); + $this->assertEquals($expected, $result); + + $result = $route->parse('/tests/action/theanswer[is]:42/var[]:val2/var[]:val3'); + $expected = array( + 'controller' => 'tests', + 'action' => 'action', + 'named' => array( + 'theanswer' => array( + 'is' => 42 + ), + 'var' => array( + 'val2', + 'val3' + ) + ), + 'pass' => array(), + ); + $this->assertEquals($expected, $result); + + $result = $route->parse('/tests/action/theanswer[is][not]:42/theanswer[]:5/theanswer[is]:6'); + $expected = array( + 'controller' => 'tests', + 'action' => 'action', + 'named' => array( + 'theanswer' => array( + 5, + 'is' => array( + 6, + 'not' => 42 + ) + ), + ), + 'pass' => array(), + ); + $this->assertEquals($expected, $result); + } + +/** + * Test that match can handle array named parameters + * + * @return void + */ + public function testMatchNamedParametersArray() { + $route = new CakeRoute('/:controller/:action/*'); + + $url = array( + 'controller' => 'posts', + 'action' => 'index', + 'filter' => array( + 'one', + 'model' => 'value' + ) + ); + $result = $route->match($url); + $expected = '/posts/index/filter%5B0%5D:one/filter%5Bmodel%5D:value'; + $this->assertEquals($expected, $result); + + $url = array( + 'controller' => 'posts', + 'action' => 'index', + 'filter' => array( + 'one', + 'model' => array( + 'two', + 'order' => 'field' + ) + ) + ); + $result = $route->match($url); + $expected = '/posts/index/filter%5B0%5D:one/filter%5Bmodel%5D%5B0%5D:two/filter%5Bmodel%5D%5Border%5D:field'; + $this->assertEquals($expected, $result); + } + +/** + * test restructuring args with pass key + * + * @return void + */ + public function testPassArgRestructure() { + $route = new CakeRoute('/:controller/:action/:slug', array(), array( + 'pass' => array('slug') + )); + $result = $route->parse('/posts/view/my-title'); + $expected = array( + 'controller' => 'posts', + 'action' => 'view', + 'slug' => 'my-title', + 'pass' => array('my-title'), + 'named' => array() + ); + $this->assertEquals($expected, $result, 'Slug should have moved'); + } + +/** + * Test the /** special type on parsing. + * + * @return void + */ + public function testParseTrailing() { + $route = new CakeRoute('/:controller/:action/**'); + $result = $route->parse('/posts/index/1/2/3/foo:bar'); + $expected = array( + 'controller' => 'posts', + 'action' => 'index', + 'pass' => array('1/2/3/foo:bar'), + 'named' => array() + ); + $this->assertEquals($expected, $result); + + $result = $route->parse('/posts/index/http://example.com'); + $expected = array( + 'controller' => 'posts', + 'action' => 'index', + 'pass' => array('http://example.com'), + 'named' => array() + ); + $this->assertEquals($expected, $result); + } + +/** + * Test the /** special type on parsing - UTF8. + * + * @return void + */ + public function testParseTrailingUTF8() { + $route = new CakeRoute('/category/**', array('controller' => 'categories','action' => 'index')); + $result = $route->parse('/category/%D9%85%D9%88%D8%A8%D8%A7%DB%8C%D9%84'); + $expected = array( + 'controller' => 'categories', + 'action' => 'index', + 'pass' => array('موبایل'), + 'named' => array() + ); + $this->assertEquals($expected, $result); + } + +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Routing/Route/PluginShortRouteTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Routing/Route/PluginShortRouteTest.php new file mode 100644 index 0000000..4438d47 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Routing/Route/PluginShortRouteTest.php @@ -0,0 +1,72 @@ + null, 'prefixes' => array())); + Router::reload(); + } + +/** + * test the parsing of routes. + * + * @return void + */ + public function testParsing() { + $route = new PluginShortRoute('/:plugin', array('action' => 'index'), array('plugin' => 'foo|bar')); + + $result = $route->parse('/foo'); + $this->assertEquals('foo', $result['plugin']); + $this->assertEquals('foo', $result['controller']); + $this->assertEquals('index', $result['action']); + + $result = $route->parse('/wrong'); + $this->assertFalse($result, 'Wrong plugin name matched %s'); + } + +/** + * test the reverse routing of the plugin shortcut urls. + * + * @return void + */ + public function testMatch() { + $route = new PluginShortRoute('/:plugin', array('action' => 'index'), array('plugin' => 'foo|bar')); + + $result = $route->match(array('plugin' => 'foo', 'controller' => 'posts', 'action' => 'index')); + $this->assertFalse($result, 'plugin controller mismatch was converted. %s'); + + $result = $route->match(array('plugin' => 'foo', 'controller' => 'foo', 'action' => 'index')); + $this->assertEquals('/foo', $result); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Routing/Route/RedirectRouteTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Routing/Route/RedirectRouteTest.php new file mode 100644 index 0000000..33b4276 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Routing/Route/RedirectRouteTest.php @@ -0,0 +1,107 @@ + null, 'prefixes' => array())); + Router::reload(); + } + +/** + * test the parsing of routes. + * + * @return void + */ + public function testParsing() { + $route = new RedirectRoute('/home', array('controller' => 'posts')); + $route->stop = false; + $route->response = $this->getMock('CakeResponse', array('_sendHeader')); + $result = $route->parse('/home'); + $header = $route->response->header(); + $this->assertEquals(Router::url('/posts', true), $header['Location']); + + $route = new RedirectRoute('/home', array('controller' => 'posts', 'action' => 'index')); + $route->stop = false; + $route->response = $this->getMock('CakeResponse', array('_sendHeader')); + $result = $route->parse('/home'); + $header = $route->response->header(); + $this->assertEquals(Router::url('/posts', true), $header['Location']); + $this->assertEquals(301, $route->response->statusCode()); + + $route = new RedirectRoute('/google', 'http://google.com'); + $route->stop = false; + $route->response = $this->getMock('CakeResponse', array('_sendHeader')); + $result = $route->parse('/google'); + $header = $route->response->header(); + $this->assertEquals('http://google.com', $header['Location']); + + $route = new RedirectRoute('/posts/*', array('controller' => 'posts', 'action' => 'view'), array('status' => 302)); + $route->stop = false; + $route->response = $this->getMock('CakeResponse', array('_sendHeader')); + $result = $route->parse('/posts/2'); + $header = $route->response->header(); + $this->assertEquals(Router::url('/posts/view', true), $header['Location']); + $this->assertEquals(302, $route->response->statusCode()); + + $route = new RedirectRoute('/posts/*', array('controller' => 'posts', 'action' => 'view'), array('persist' => true)); + $route->stop = false; + $route->response = $this->getMock('CakeResponse', array('_sendHeader')); + $result = $route->parse('/posts/2'); + $header = $route->response->header(); + $this->assertEquals(Router::url('/posts/view/2', true), $header['Location']); + + $route = new RedirectRoute('/posts/*', '/test', array('persist' => true)); + $route->stop = false; + $route->response = $this->getMock('CakeResponse', array('_sendHeader')); + $result = $route->parse('/posts/2'); + $header = $route->response->header(); + $this->assertEquals(Router::url('/test', true), $header['Location']); + + $route = new RedirectRoute('/my_controllers/:action/*', array('controller' => 'tags', 'action' => 'add'), array('persist' => true)); + $route->stop = false; + $route->response = $this->getMock('CakeResponse', array('_sendHeader')); + $result = $route->parse('/my_controllers/do_something/passme/named:param'); + $header = $route->response->header(); + $this->assertEquals(Router::url('/tags/add/passme/named:param', true), $header['Location']); + + $route = new RedirectRoute('/my_controllers/:action/*', array('controller' => 'tags', 'action' => 'add')); + $route->stop = false; + $route->response = $this->getMock('CakeResponse', array('_sendHeader')); + $result = $route->parse('/my_controllers/do_something/passme/named:param'); + $header = $route->response->header(); + $this->assertEquals(Router::url('/tags/add', true), $header['Location']); + } + +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Routing/RouterTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Routing/RouterTest.php new file mode 100644 index 0000000..44bf6aa --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Routing/RouterTest.php @@ -0,0 +1,2669 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The Open Group Test Suite License + * Redistributions of files must retain the above copyright notice. + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Routing + * @since CakePHP(tm) v 1.2.0.4206 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ + +App::uses('Router', 'Routing'); +App::uses('CakeResponse', 'Network'); + +if (!defined('FULL_BASE_URL')) { + define('FULL_BASE_URL', 'http://cakephp.org'); +} + +/** + * RouterTest class + * + * @package Cake.Test.Case.Routing + */ +class RouterTest extends CakeTestCase { + +/** + * setUp method + * + * @return void + */ + public function setUp() { + parent::setUp(); + Configure::write('Routing', array('admin' => null, 'prefixes' => array())); + } + +/** + * tearDown method + * + * @return void + */ + public function tearDown() { + parent::tearDown(); + CakePlugin::unload(); + } + +/** + * testFullBaseURL method + * + * @return void + */ + public function testFullBaseURL() { + $skip = PHP_SAPI == 'cli'; + if ($skip) { + $this->markTestSkipped('Cannot validate base urls in CLI'); + } + $this->assertRegExp('/^http(s)?:\/\//', Router::url('/', true)); + $this->assertRegExp('/^http(s)?:\/\//', Router::url(null, true)); + $this->assertRegExp('/^http(s)?:\/\//', Router::url(array('full_base' => true))); + $this->assertSame(FULL_BASE_URL . '/', Router::url(array('full_base' => true))); + } + +/** + * testRouteDefaultParams method + * + * @return void + */ + public function testRouteDefaultParams() { + Router::connect('/:controller', array('controller' => 'posts')); + $this->assertEquals(Router::url(array('action' => 'index')), '/'); + } + +/** + * testMapResources method + * + * @return void + */ + public function testMapResources() { + $resources = Router::mapResources('Posts'); + + $_SERVER['REQUEST_METHOD'] = 'GET'; + $result = Router::parse('/posts'); + $this->assertEquals(array('pass' => array(), 'named' => array(), 'plugin' => '', 'controller' => 'posts', 'action' => 'index', '[method]' => 'GET'), $result); + $this->assertEquals(array('posts'), $resources); + + $_SERVER['REQUEST_METHOD'] = 'GET'; + $result = Router::parse('/posts/13'); + $this->assertEquals(array('pass' => array('13'), 'named' => array(), 'plugin' => '', 'controller' => 'posts', 'action' => 'view', 'id' => '13', '[method]' => 'GET'), $result); + + $_SERVER['REQUEST_METHOD'] = 'POST'; + $result = Router::parse('/posts'); + $this->assertEquals(array('pass' => array(), 'named' => array(), 'plugin' => '', 'controller' => 'posts', 'action' => 'add', '[method]' => 'POST'), $result); + + $_SERVER['REQUEST_METHOD'] = 'PUT'; + $result = Router::parse('/posts/13'); + $this->assertEquals(array('pass' => array('13'), 'named' => array(), 'plugin' => '', 'controller' => 'posts', 'action' => 'edit', 'id' => '13', '[method]' => 'PUT'), $result); + + $result = Router::parse('/posts/475acc39-a328-44d3-95fb-015000000000'); + $this->assertEquals(array('pass' => array('475acc39-a328-44d3-95fb-015000000000'), 'named' => array(), 'plugin' => '', 'controller' => 'posts', 'action' => 'edit', 'id' => '475acc39-a328-44d3-95fb-015000000000', '[method]' => 'PUT'), $result); + + $_SERVER['REQUEST_METHOD'] = 'DELETE'; + $result = Router::parse('/posts/13'); + $this->assertEquals(array('pass' => array('13'), 'named' => array(), 'plugin' => '', 'controller' => 'posts', 'action' => 'delete', 'id' => '13', '[method]' => 'DELETE'), $result); + + $_SERVER['REQUEST_METHOD'] = 'GET'; + $result = Router::parse('/posts/add'); + $this->assertEquals(array(), $result); + + Router::reload(); + $resources = Router::mapResources('Posts', array('id' => '[a-z0-9_]+')); + $this->assertEquals(array('posts'), $resources); + + $_SERVER['REQUEST_METHOD'] = 'GET'; + $result = Router::parse('/posts/add'); + $this->assertEquals(array('pass' => array('add'), 'named' => array(), 'plugin' => '', 'controller' => 'posts', 'action' => 'view', 'id' => 'add', '[method]' => 'GET'), $result); + + $_SERVER['REQUEST_METHOD'] = 'PUT'; + $result = Router::parse('/posts/name'); + $this->assertEquals(array('pass' => array('name'), 'named' => array(), 'plugin' => '', 'controller' => 'posts', 'action' => 'edit', 'id' => 'name', '[method]' => 'PUT'), $result); + } + +/** + * testMapResources with plugin controllers. + * + * @return void + */ + public function testPluginMapResources() { + App::build(array( + 'Plugin' => array( + CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS + ) + )); + $resources = Router::mapResources('TestPlugin.TestPlugin'); + + $_SERVER['REQUEST_METHOD'] = 'GET'; + $result = Router::parse('/test_plugin/test_plugin'); + $expected = array( + 'pass' => array(), + 'named' => array(), + 'plugin' => 'test_plugin', + 'controller' => 'test_plugin', + 'action' => 'index', + '[method]' => 'GET' + ); + $this->assertEquals($expected, $result); + $this->assertEquals(array('test_plugin'), $resources); + + $_SERVER['REQUEST_METHOD'] = 'GET'; + $result = Router::parse('/test_plugin/test_plugin/13'); + $expected = array( + 'pass' => array('13'), + 'named' => array(), + 'plugin' => 'test_plugin', + 'controller' => 'test_plugin', + 'action' => 'view', + 'id' => '13', + '[method]' => 'GET' + ); + $this->assertEquals($expected, $result); + } + +/** + * Test mapResources with a plugin and prefix. + * + * @return void + */ + public function testPluginMapResourcesWithPrefix() { + App::build(array( + 'Plugin' => array( + CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS + ) + )); + $resources = Router::mapResources('TestPlugin.TestPlugin', array('prefix' => '/api/')); + + $_SERVER['REQUEST_METHOD'] = 'GET'; + $result = Router::parse('/api/test_plugin'); + $expected = array( + 'pass' => array(), + 'named' => array(), + 'plugin' => 'test_plugin', + 'controller' => 'test_plugin', + 'action' => 'index', + '[method]' => 'GET' + ); + $this->assertEquals($expected, $result); + $this->assertEquals(array('test_plugin'), $resources); + } + +/** + * testMultipleResourceRoute method + * + * @return void + */ + public function testMultipleResourceRoute() { + Router::connect('/:controller', array('action' => 'index', '[method]' => array('GET', 'POST'))); + + $_SERVER['REQUEST_METHOD'] = 'GET'; + $result = Router::parse('/posts'); + $this->assertEquals(array('pass' => array(), 'named' => array(), 'plugin' => '', 'controller' => 'posts', 'action' => 'index', '[method]' => array('GET', 'POST')), $result); + + $_SERVER['REQUEST_METHOD'] = 'POST'; + $result = Router::parse('/posts'); + $this->assertEquals(array('pass' => array(), 'named' => array(), 'plugin' => '', 'controller' => 'posts', 'action' => 'index', '[method]' => array('GET', 'POST')), $result); + } + +/** + * testGenerateUrlResourceRoute method + * + * @return void + */ + public function testGenerateUrlResourceRoute() { + Router::mapResources('Posts'); + + $result = Router::url(array('controller' => 'posts', 'action' => 'index', '[method]' => 'GET')); + $expected = '/posts'; + $this->assertEquals($expected, $result); + + $result = Router::url(array('controller' => 'posts', 'action' => 'view', '[method]' => 'GET', 'id' => 10)); + $expected = '/posts/10'; + $this->assertEquals($expected, $result); + + $result = Router::url(array('controller' => 'posts', 'action' => 'add', '[method]' => 'POST')); + $expected = '/posts'; + $this->assertEquals($expected, $result); + + $result = Router::url(array('controller' => 'posts', 'action' => 'edit', '[method]' => 'PUT', 'id' => 10)); + $expected = '/posts/10'; + $this->assertEquals($expected, $result); + + $result = Router::url(array('controller' => 'posts', 'action' => 'delete', '[method]' => 'DELETE', 'id' => 10)); + $expected = '/posts/10'; + $this->assertEquals($expected, $result); + + $result = Router::url(array('controller' => 'posts', 'action' => 'edit', '[method]' => 'POST', 'id' => 10)); + $expected = '/posts/10'; + $this->assertEquals($expected, $result); + } + +/** + * testUrlNormalization method + * + * @return void + */ + public function testUrlNormalization() { + $expected = '/users/logout'; + + $result = Router::normalize('/users/logout/'); + $this->assertEquals($expected, $result); + + $result = Router::normalize('//users//logout//'); + $this->assertEquals($expected, $result); + + $result = Router::normalize('users/logout'); + $this->assertEquals($expected, $result); + + $result = Router::normalize(array('controller' => 'users', 'action' => 'logout')); + $this->assertEquals($expected, $result); + + $result = Router::normalize('/'); + $this->assertEquals('/', $result); + + $result = Router::normalize('http://google.com/'); + $this->assertEquals('http://google.com/', $result); + + $result = Router::normalize('http://google.com//'); + $this->assertEquals('http://google.com//', $result); + + $result = Router::normalize('/users/login/scope://foo'); + $this->assertEquals('/users/login/scope:/foo', $result); + + $result = Router::normalize('/recipe/recipes/add'); + $this->assertEquals('/recipe/recipes/add', $result); + + $request = new CakeRequest(); + $request->base = '/us'; + Router::setRequestInfo($request); + $result = Router::normalize('/us/users/logout/'); + $this->assertEquals('/users/logout', $result); + + Router::reload(); + + $request = new CakeRequest(); + $request->base = '/cake_12'; + Router::setRequestInfo($request); + $result = Router::normalize('/cake_12/users/logout/'); + $this->assertEquals('/users/logout', $result); + + Router::reload(); + $_back = Configure::read('App.baseUrl'); + Configure::write('App.baseUrl', '/'); + + $request = new CakeRequest(); + $request->base = '/'; + Router::setRequestInfo($request); + $result = Router::normalize('users/login'); + $this->assertEquals('/users/login', $result); + Configure::write('App.baseUrl', $_back); + + Router::reload(); + $request = new CakeRequest(); + $request->base = 'beer'; + Router::setRequestInfo($request); + $result = Router::normalize('beer/admin/beers_tags/add'); + $this->assertEquals('/admin/beers_tags/add', $result); + + $result = Router::normalize('/admin/beers_tags/add'); + $this->assertEquals('/admin/beers_tags/add', $result); + } + +/** + * test generation of basic urls. + * + * @return void + */ + public function testUrlGenerationBasic() { + extract(Router::getNamedExpressions()); + + $request = new CakeRequest(); + $request->addParams(array( + 'action' => 'index', 'plugin' => null, 'controller' => 'subscribe', 'admin' => true + )); + $request->base = '/magazine'; + $request->here = '/magazine'; + $request->webroot = '/magazine/'; + Router::setRequestInfo($request); + + $result = Router::url(); + $this->assertEquals('/magazine', $result); + + Router::reload(); + + Router::connect('/', array('controller' => 'pages', 'action' => 'display', 'home')); + $out = Router::url(array('controller' => 'pages', 'action' => 'display', 'home')); + $this->assertEquals('/', $out); + + Router::connect('/pages/*', array('controller' => 'pages', 'action' => 'display')); + $result = Router::url(array('controller' => 'pages', 'action' => 'display', 'about')); + $expected = '/pages/about'; + $this->assertEquals($expected, $result); + + Router::reload(); + Router::connect('/:plugin/:id/*', array('controller' => 'posts', 'action' => 'view'), array('id' => $ID)); + Router::parse('/'); + + $result = Router::url(array('plugin' => 'cake_plugin', 'controller' => 'posts', 'action' => 'view', 'id' => '1')); + $expected = '/cake_plugin/1'; + $this->assertEquals($expected, $result); + + $result = Router::url(array('plugin' => 'cake_plugin', 'controller' => 'posts', 'action' => 'view', 'id' => '1', '0')); + $expected = '/cake_plugin/1/0'; + $this->assertEquals($expected, $result); + + Router::reload(); + Router::connect('/:controller/:action/:id', array(), array('id' => $ID)); + Router::parse('/'); + + $result = Router::url(array('controller' => 'posts', 'action' => 'view', 'id' => '1')); + $expected = '/posts/view/1'; + $this->assertEquals($expected, $result); + + Router::reload(); + Router::connect('/:controller/:id', array('action' => 'view')); + Router::parse('/'); + + $result = Router::url(array('controller' => 'posts', 'action' => 'view', 'id' => '1')); + $expected = '/posts/1'; + $this->assertEquals($expected, $result); + + $result = Router::url(array('controller' => 'posts', 'action' => 'index', '0')); + $expected = '/posts/index/0'; + $this->assertEquals($expected, $result); + + Router::connect('/view/*', array('controller' => 'posts', 'action' => 'view')); + Router::promote(); + $result = Router::url(array('controller' => 'posts', 'action' => 'view', '1')); + $expected = '/view/1'; + $this->assertEquals($expected, $result); + + Router::reload(); + $request = new CakeRequest(); + $request->addParams(array( + 'action' => 'index', 'plugin' => null, 'controller' => 'real_controller_name' + )); + $request->base = '/'; + $request->here = '/'; + $request->webroot = '/'; + Router::setRequestInfo($request); + + Router::connect('short_controller_name/:action/*', array('controller' => 'real_controller_name')); + Router::parse('/'); + + $result = Router::url(array('controller' => 'real_controller_name', 'page' => '1')); + $expected = '/short_controller_name/index/page:1'; + $this->assertEquals($expected, $result); + + $result = Router::url(array('action' => 'add')); + $expected = '/short_controller_name/add'; + $this->assertEquals($expected, $result); + + Router::reload(); + Router::parse('/'); + $request = new CakeRequest(); + $request->addParams(array( + 'action' => 'index', 'plugin' => null, 'controller' => 'users', 'url' => array('url' => 'users') + )); + $request->base = '/'; + $request->here = '/'; + $request->webroot = '/'; + Router::setRequestInfo($request); + + $result = Router::url(array('action' => 'login')); + $expected = '/users/login'; + $this->assertEquals($expected, $result); + + Router::reload(); + Router::connect('/page/*', array('plugin' => null, 'controller' => 'pages', 'action' => 'view')); + Router::parse('/'); + + $result = Router::url(array('plugin' => 'my_plugin', 'controller' => 'pages', 'action' => 'view', 'my-page')); + $expected = '/my_plugin/pages/view/my-page'; + $this->assertEquals($expected, $result); + + Router::reload(); + Router::connect('/contact/:action', array('plugin' => 'contact', 'controller' => 'contact')); + Router::parse('/'); + + $result = Router::url(array('plugin' => 'contact', 'controller' => 'contact', 'action' => 'me')); + + $expected = '/contact/me'; + $this->assertEquals($expected, $result); + + Router::reload(); + $request = new CakeRequest(); + $request->addParams(array( + 'action' => 'index', 'plugin' => 'myplugin', 'controller' => 'mycontroller', 'admin' => false + )); + $request->base = '/'; + $request->here = '/'; + $request->webroot = '/'; + Router::setRequestInfo($request); + + $result = Router::url(array('plugin' => null, 'controller' => 'myothercontroller')); + $expected = '/myothercontroller'; + $this->assertEquals($expected, $result); + } + +/** + * Tests using arrays in named parameters + * + * @return void + */ + public function testArrayNamedParameters() { + $result = Router::url(array('controller' => 'tests', 'pages' => array( + 1, 2, 3 + ))); + $expected = '/tests/index/pages[0]:1/pages[1]:2/pages[2]:3'; + $this->assertEquals($expected, $result); + + $result = Router::url(array('controller' => 'tests', + 'pages' => array( + 'param1' => array( + 'one', + 'two' + ), + 'three' + ) + )); + $expected = '/tests/index/pages[param1][0]:one/pages[param1][1]:two/pages[0]:three'; + $this->assertEquals($expected, $result); + + $result = Router::url(array('controller' => 'tests', + 'pages' => array( + 'param1' => array( + 'one' => 1, + 'two' => 2 + ), + 'three' + ) + )); + $expected = '/tests/index/pages[param1][one]:1/pages[param1][two]:2/pages[0]:three'; + $this->assertEquals($expected, $result); + + $result = Router::url(array('controller' => 'tests', + 'super' => array( + 'nested' => array( + 'array' => 'awesome', + 'something' => 'else' + ), + 'cool' + ) + )); + $expected = '/tests/index/super[nested][array]:awesome/super[nested][something]:else/super[0]:cool'; + $this->assertEquals($expected, $result); + + $result = Router::url(array('controller' => 'tests', 'namedParam' => array( + 'keyed' => 'is an array', + 'test' + ))); + $expected = '/tests/index/namedParam[keyed]:is%20an%20array/namedParam[0]:test'; + $this->assertEquals($expected, $result); + } + +/** + * Test generation of routes with query string parameters. + * + * @return void + **/ + public function testUrlGenerationWithQueryStrings() { + $result = Router::url(array('controller' => 'posts', 'action' => 'index', '0', '?' => 'var=test&var2=test2')); + $expected = '/posts/index/0?var=test&var2=test2'; + $this->assertEquals($expected, $result); + + $result = Router::url(array('controller' => 'posts', '0', '?' => 'var=test&var2=test2')); + $this->assertEquals($expected, $result); + + $result = Router::url(array('controller' => 'posts', '0', '?' => array('var' => 'test', 'var2' => 'test2'))); + $this->assertEquals($expected, $result); + + $result = Router::url(array('controller' => 'posts', '0', '?' => array('var' => null))); + $this->assertEquals('/posts/index/0', $result); + + $result = Router::url(array('controller' => 'posts', '0', '?' => 'var=test&var2=test2', '#' => 'unencoded string %')); + $expected = '/posts/index/0?var=test&var2=test2#unencoded string %'; + $this->assertEquals($expected, $result); + } + +/** + * test that regex validation of keyed route params is working. + * + * @return void + **/ + public function testUrlGenerationWithRegexQualifiedParams() { + Router::connect( + ':language/galleries', + array('controller' => 'galleries', 'action' => 'index'), + array('language' => '[a-z]{3}') + ); + + Router::connect( + '/:language/:admin/:controller/:action/*', + array('admin' => 'admin'), + array('language' => '[a-z]{3}', 'admin' => 'admin') + ); + + Router::connect('/:language/:controller/:action/*', + array(), + array('language' => '[a-z]{3}') + ); + + $result = Router::url(array('admin' => false, 'language' => 'dan', 'action' => 'index', 'controller' => 'galleries')); + $expected = '/dan/galleries'; + $this->assertEquals($expected, $result); + + $result = Router::url(array('admin' => false, 'language' => 'eng', 'action' => 'index', 'controller' => 'galleries')); + $expected = '/eng/galleries'; + $this->assertEquals($expected, $result); + + Router::reload(); + Router::connect('/:language/pages', + array('controller' => 'pages', 'action' => 'index'), + array('language' => '[a-z]{3}') + ); + Router::connect('/:language/:controller/:action/*', array(), array('language' => '[a-z]{3}')); + + $result = Router::url(array('language' => 'eng', 'action' => 'index', 'controller' => 'pages')); + $expected = '/eng/pages'; + $this->assertEquals($expected, $result); + + $result = Router::url(array('language' => 'eng', 'controller' => 'pages')); + $this->assertEquals($expected, $result); + + $result = Router::url(array('language' => 'eng', 'controller' => 'pages', 'action' => 'add')); + $expected = '/eng/pages/add'; + $this->assertEquals($expected, $result); + + Router::reload(); + Router::connect('/forestillinger/:month/:year/*', + array('plugin' => 'shows', 'controller' => 'shows', 'action' => 'calendar'), + array('month' => '0[1-9]|1[012]', 'year' => '[12][0-9]{3}') + ); + Router::parse('/'); + + $result = Router::url(array('plugin' => 'shows', 'controller' => 'shows', 'action' => 'calendar', 'month' => 10, 'year' => 2007, 'min-forestilling')); + $expected = '/forestillinger/10/2007/min-forestilling'; + $this->assertEquals($expected, $result); + + Router::reload(); + Router::connect('/kalender/:month/:year/*', + array('plugin' => 'shows', 'controller' => 'shows', 'action' => 'calendar'), + array('month' => '0[1-9]|1[012]', 'year' => '[12][0-9]{3}') + ); + Router::connect('/kalender/*', array('plugin' => 'shows', 'controller' => 'shows', 'action' => 'calendar')); + Router::parse('/'); + + $result = Router::url(array('plugin' => 'shows', 'controller' => 'shows', 'action' => 'calendar', 'min-forestilling')); + $expected = '/kalender/min-forestilling'; + $this->assertEquals($expected, $result); + + $result = Router::url(array('plugin' => 'shows', 'controller' => 'shows', 'action' => 'calendar', 'year' => 2007, 'month' => 10, 'min-forestilling')); + $expected = '/kalender/10/2007/min-forestilling'; + $this->assertEquals($expected, $result); + + Router::reload(); + Router::connect('/:controller/:action/*', array(), array( + 'controller' => 'source|wiki|commits|tickets|comments|view', + 'action' => 'branches|history|branch|logs|view|start|add|edit|modify' + )); + } + +/** + * Test url generation with an admin prefix + * + * @return void + */ + public function testUrlGenerationWithAdminPrefix() { + Configure::write('Routing.prefixes', array('admin')); + Router::reload(); + + Router::connectNamed(array('event', 'lang')); + Router::connect('/', array('controller' => 'pages', 'action' => 'display', 'home')); + Router::connect('/pages/contact_us', array('controller' => 'pages', 'action' => 'contact_us')); + Router::connect('/pages/*', array('controller' => 'pages', 'action' => 'display')); + Router::connect('/reset/*', array('admin' => true, 'controller' => 'users', 'action' => 'reset')); + Router::connect('/tests', array('controller' => 'tests', 'action' => 'index')); + Router::parseExtensions('rss'); + + $request = new CakeRequest(); + $request->addParams(array( + 'controller' => 'registrations', 'action' => 'admin_index', + 'plugin' => null, 'prefix' => 'admin', 'admin' => true, + 'ext' => 'html' + )); + $request->base = ''; + $request->here = '/admin/registrations/index'; + $request->webroot = '/'; + Router::setRequestInfo($request); + + $result = Router::url(array('page' => 2)); + $expected = '/admin/registrations/index/page:2'; + $this->assertEquals($expected, $result); + + Router::reload(); + $request = new CakeRequest(); + $request->addParams(array( + 'controller' => 'subscriptions', 'action' => 'admin_index', + 'plugin' => null, 'admin' => true, + 'url' => array('url' => 'admin/subscriptions/index/page:2') + )); + $request->base = '/magazine'; + $request->here = '/magazine/admin/subscriptions/index/page:2'; + $request->webroot = '/magazine/'; + Router::setRequestInfo($request); + + Router::parse('/'); + + $result = Router::url(array('page' => 3)); + $expected = '/magazine/admin/subscriptions/index/page:3'; + $this->assertEquals($expected, $result); + + Router::reload(); + Router::connect('/admin/subscriptions/:action/*', array('controller' => 'subscribe', 'admin' => true, 'prefix' => 'admin')); + Router::parse('/'); + + $request = new CakeRequest(); + $request->addParams(array( + 'action' => 'admin_index', 'plugin' => null, 'controller' => 'subscribe', + 'admin' => true, 'url' => array('url' => 'admin/subscriptions/edit/1') + )); + $request->base = '/magazine'; + $request->here = '/magazine/admin/subscriptions/edit/1'; + $request->webroot = '/magazine/'; + Router::setRequestInfo($request); + + $result = Router::url(array('action' => 'edit', 1)); + $expected = '/magazine/admin/subscriptions/edit/1'; + $this->assertEquals($expected, $result); + + $result = Router::url(array('admin' => true, 'controller' => 'users', 'action' => 'login')); + $expected = '/magazine/admin/users/login'; + $this->assertEquals($expected, $result); + + Router::reload(); + $request = new CakeRequest(); + $request->addParams(array( + 'admin' => true, 'action' => 'index', 'plugin' => null, 'controller' => 'users', + 'url' => array('url' => 'users') + )); + $request->base = '/'; + $request->here = '/'; + $request->webroot = '/'; + Router::setRequestInfo($request); + + Router::connect('/page/*', array('controller' => 'pages', 'action' => 'view', 'admin' => true, 'prefix' => 'admin')); + Router::parse('/'); + + $result = Router::url(array('admin' => true, 'controller' => 'pages', 'action' => 'view', 'my-page')); + $expected = '/page/my-page'; + $this->assertEquals($expected, $result); + + Router::reload(); + + $request = new CakeRequest(); + $request->addParams(array( + 'plugin' => null, 'controller' => 'pages', 'action' => 'admin_add', 'prefix' => 'admin', 'admin' => true, + 'url' => array('url' => 'admin/pages/add') + )); + $request->base = ''; + $request->here = '/admin/pages/add'; + $request->webroot = '/'; + Router::setRequestInfo($request); + Router::parse('/'); + + $result = Router::url(array('plugin' => null, 'controller' => 'pages', 'action' => 'add', 'id' => false)); + $expected = '/admin/pages/add'; + $this->assertEquals($expected, $result); + + Router::reload(); + Router::parse('/'); + $request = new CakeRequest(); + $request->addParams(array( + 'plugin' => null, 'controller' => 'pages', 'action' => 'admin_add', 'prefix' => 'admin', 'admin' => true, + 'url' => array('url' => 'admin/pages/add') + )); + $request->base = ''; + $request->here = '/admin/pages/add'; + $request->webroot = '/'; + Router::setRequestInfo($request); + + $result = Router::url(array('plugin' => null, 'controller' => 'pages', 'action' => 'add', 'id' => false)); + $expected = '/admin/pages/add'; + $this->assertEquals($expected, $result); + + Router::reload(); + Router::connect('/admin/:controller/:action/:id', array('admin' => true), array('id' => '[0-9]+')); + Router::parse('/'); + $request = new CakeRequest(); + Router::setRequestInfo( + $request->addParams(array( + 'plugin' => null, 'controller' => 'pages', 'action' => 'admin_edit', 'pass' => array('284'), + 'prefix' => 'admin', 'admin' => true, + 'url' => array('url' => 'admin/pages/edit/284') + ))->addPaths(array( + 'base' => '', 'here' => '/admin/pages/edit/284', 'webroot' => '/' + )) + ); + + $result = Router::url(array('plugin' => null, 'controller' => 'pages', 'action' => 'edit', 'id' => '284')); + $expected = '/admin/pages/edit/284'; + $this->assertEquals($expected, $result); + + Router::reload(); + Router::parse('/'); + + $request = new CakeRequest(); + Router::setRequestInfo( + $request->addParams(array( + 'plugin' => null, 'controller' => 'pages', 'action' => 'admin_add', 'prefix' => 'admin', + 'admin' => true, 'url' => array('url' => 'admin/pages/add') + ))->addPaths(array( + 'base' => '', 'here' => '/admin/pages/add', 'webroot' => '/' + )) + ); + + $result = Router::url(array('plugin' => null, 'controller' => 'pages', 'action' => 'add', 'id' => false)); + $expected = '/admin/pages/add'; + $this->assertEquals($expected, $result); + + Router::reload(); + Router::parse('/'); + + $request = new CakeRequest(); + Router::setRequestInfo( + $request->addParams(array( + 'plugin' => null, 'controller' => 'pages', 'action' => 'admin_edit', 'prefix' => 'admin', + 'admin' => true, 'pass' => array('284'), 'url' => array('url' => 'admin/pages/edit/284') + ))->addPaths(array( + 'base' => '', 'here' => '/admin/pages/edit/284', 'webroot' => '/' + )) + ); + + $result = Router::url(array('plugin' => null, 'controller' => 'pages', 'action' => 'edit', 284)); + $expected = '/admin/pages/edit/284'; + $this->assertEquals($expected, $result); + + Router::reload(); + Router::connect('/admin/posts/*', array('controller' => 'posts', 'action' => 'index', 'admin' => true)); + Router::parse('/'); + Router::setRequestInfo( + $request->addParams(array( + 'plugin' => null, 'controller' => 'posts', 'action' => 'admin_index', 'prefix' => 'admin', + 'admin' => true, 'pass' => array('284'), 'url' => array('url' => 'admin/posts') + ))->addPaths(array( + 'base' => '', 'here' => '/admin/posts', 'webroot' => '/' + )) + ); + + $result = Router::url(array('all')); + $expected = '/admin/posts/all'; + $this->assertEquals($expected, $result); + } + +/** + * testUrlGenerationWithExtensions method + * + * @return void + */ + public function testUrlGenerationWithExtensions() { + Router::parse('/'); + $result = Router::url(array('plugin' => null, 'controller' => 'articles', 'action' => 'add', 'id' => null, 'ext' => 'json')); + $expected = '/articles/add.json'; + $this->assertEquals($expected, $result); + + $result = Router::url(array('plugin' => null, 'controller' => 'articles', 'action' => 'add', 'ext' => 'json')); + $expected = '/articles/add.json'; + $this->assertEquals($expected, $result); + + $result = Router::url(array('plugin' => null, 'controller' => 'articles', 'action' => 'index', 'id' => null, 'ext' => 'json')); + $expected = '/articles.json'; + $this->assertEquals($expected, $result); + + $result = Router::url(array('plugin' => null, 'controller' => 'articles', 'action' => 'index', 'ext' => 'json')); + $expected = '/articles.json'; + $this->assertEquals($expected, $result); + } + +/** + * testPluginUrlGeneration method + * + * @return void + */ + public function testUrlGenerationPlugins() { + $request = new CakeRequest(); + Router::setRequestInfo( + $request->addParams(array( + 'plugin' => 'test', 'controller' => 'controller', 'action' => 'index' + ))->addPaths(array( + 'base' => '/base', 'here' => '/clients/sage/portal/donations', 'webroot' => '/base/' + )) + ); + + $this->assertEquals(Router::url('read/1'), '/base/test/controller/read/1'); + + Router::reload(); + Router::connect('/:lang/:plugin/:controller/*', array('action' => 'index')); + + $request = new CakeRequest(); + Router::setRequestInfo( + $request->addParams(array( + 'lang' => 'en', + 'plugin' => 'shows', 'controller' => 'shows', 'action' => 'index', + 'url' => array('url' => 'en/shows/'), + ))->addPaths(array( + 'base' => '', 'here' => '/en/shows', 'webroot' => '/' + )) + ); + + Router::parse('/en/shows/'); + + $result = Router::url(array( + 'lang' => 'en', + 'controller' => 'shows', 'action' => 'index', 'page' => '1', + )); + $expected = '/en/shows/shows/page:1'; + $this->assertEquals($expected, $result); + } + +/** + * test that you can leave active plugin routes with plugin = null + * + * @return void + */ + public function testCanLeavePlugin() { + Router::reload(); + Router::connect( + '/admin/other/:controller/:action/*', + array( + 'admin' => 1, + 'plugin' => 'aliased', + 'prefix' => 'admin' + ) + ); + $request = new CakeRequest(); + Router::setRequestInfo( + $request->addParams(array( + 'pass' => array(), + 'admin' => true, + 'prefix' => 'admin', + 'plugin' => 'this', + 'action' => 'admin_index', + 'controller' => 'interesting', + 'url' => array('url' => 'admin/this/interesting/index'), + ))->addPaths(array( + 'base' => '', + 'here' => '/admin/this/interesting/index', + 'webroot' => '/', + )) + ); + $result = Router::url(array('plugin' => null, 'controller' => 'posts', 'action' => 'index')); + $this->assertEquals('/admin/posts', $result); + + $result = Router::url(array('controller' => 'posts', 'action' => 'index')); + $this->assertEquals('/admin/this/posts', $result); + + $result = Router::url(array('plugin' => 'aliased', 'controller' => 'posts', 'action' => 'index')); + $this->assertEquals('/admin/other/posts/index', $result); + } + +/** + * testUrlParsing method + * + * @return void + */ + public function testUrlParsing() { + extract(Router::getNamedExpressions()); + + Router::connect('/posts/:value/:somevalue/:othervalue/*', array('controller' => 'posts', 'action' => 'view'), array('value','somevalue', 'othervalue')); + $result = Router::parse('/posts/2007/08/01/title-of-post-here'); + $expected = array('value' => '2007', 'somevalue' => '08', 'othervalue' => '01', 'controller' => 'posts', 'action' => 'view', 'plugin' => '', 'pass' => array('0' => 'title-of-post-here'), 'named' => array()); + $this->assertEquals($expected, $result); + + Router::reload(); + Router::connect('/posts/:year/:month/:day/*', array('controller' => 'posts', 'action' => 'view'), array('year' => $Year, 'month' => $Month, 'day' => $Day)); + $result = Router::parse('/posts/2007/08/01/title-of-post-here'); + $expected = array('year' => '2007', 'month' => '08', 'day' => '01', 'controller' => 'posts', 'action' => 'view', 'plugin' => '', 'pass' => array('0' => 'title-of-post-here'), 'named' => array()); + $this->assertEquals($expected, $result); + + Router::reload(); + Router::connect('/posts/:day/:year/:month/*', array('controller' => 'posts', 'action' => 'view'), array('year' => $Year, 'month' => $Month, 'day' => $Day)); + $result = Router::parse('/posts/01/2007/08/title-of-post-here'); + $expected = array('day' => '01', 'year' => '2007', 'month' => '08', 'controller' => 'posts', 'action' => 'view', 'plugin' => '', 'pass' => array('0' => 'title-of-post-here'), 'named' => array()); + $this->assertEquals($expected, $result); + + Router::reload(); + Router::connect('/posts/:month/:day/:year/*', array('controller' => 'posts', 'action' => 'view'), array('year' => $Year, 'month' => $Month, 'day' => $Day)); + $result = Router::parse('/posts/08/01/2007/title-of-post-here'); + $expected = array('month' => '08', 'day' => '01', 'year' => '2007', 'controller' => 'posts', 'action' => 'view', 'plugin' => '', 'pass' => array('0' => 'title-of-post-here'), 'named' => array()); + $this->assertEquals($expected, $result); + + Router::reload(); + Router::connect('/posts/:year/:month/:day/*', array('controller' => 'posts', 'action' => 'view')); + $result = Router::parse('/posts/2007/08/01/title-of-post-here'); + $expected = array('year' => '2007', 'month' => '08', 'day' => '01', 'controller' => 'posts', 'action' => 'view', 'plugin' => '', 'pass' => array('0' => 'title-of-post-here'), 'named' => array()); + $this->assertEquals($expected, $result); + + Router::reload(); + require CAKE . 'Config' . DS . 'routes.php'; + $result = Router::parse('/pages/display/home'); + $expected = array('plugin' => null, 'pass' => array('home'), 'controller' => 'pages', 'action' => 'display', 'named' => array()); + $this->assertEquals($expected, $result); + + $result = Router::parse('pages/display/home/'); + $this->assertEquals($expected, $result); + + $result = Router::parse('pages/display/home'); + $this->assertEquals($expected, $result); + + Router::reload(); + Router::connect('/page/*', array('controller' => 'test')); + $result = Router::parse('/page/my-page'); + $expected = array('pass' => array('my-page'), 'plugin' => null, 'controller' => 'test', 'action' => 'index', 'named' => array()); + $this->assertEquals($expected, $result); + + Router::reload(); + Router::connect('/:language/contact', array('language' => 'eng', 'plugin' => 'contact', 'controller' => 'contact', 'action' => 'index'), array('language' => '[a-z]{3}')); + $result = Router::parse('/eng/contact'); + $expected = array('pass' => array(), 'named' => array(), 'language' => 'eng', 'plugin' => 'contact', 'controller' => 'contact', 'action' => 'index'); + $this->assertEquals($expected, $result); + + Router::reload(); + Router::connect('/forestillinger/:month/:year/*', + array('plugin' => 'shows', 'controller' => 'shows', 'action' => 'calendar'), + array('month' => '0[1-9]|1[012]', 'year' => '[12][0-9]{3}') + ); + + $result = Router::parse('/forestillinger/10/2007/min-forestilling'); + $expected = array('pass' => array('min-forestilling'), 'plugin' => 'shows', 'controller' => 'shows', 'action' => 'calendar', 'year' => 2007, 'month' => 10, 'named' => array()); + $this->assertEquals($expected, $result); + + Router::reload(); + Router::connect('/:controller/:action/*'); + Router::connect('/', array('plugin' => 'pages', 'controller' => 'pages', 'action' => 'display')); + $result = Router::parse('/'); + $expected = array('pass' => array(), 'named' => array(), 'controller' => 'pages', 'action' => 'display', 'plugin' => 'pages'); + $this->assertEquals($expected, $result); + + $result = Router::parse('/posts/edit/0'); + $expected = array('pass' => array(0), 'named' => array(), 'controller' => 'posts', 'action' => 'edit', 'plugin' => null); + $this->assertEquals($expected, $result); + + Router::reload(); + Router::connect('/posts/:id::url_title', array('controller' => 'posts', 'action' => 'view'), array('pass' => array('id', 'url_title'), 'id' => '[\d]+')); + $result = Router::parse('/posts/5:sample-post-title'); + $expected = array('pass' => array('5', 'sample-post-title'), 'named' => array(), 'id' => 5, 'url_title' => 'sample-post-title', 'plugin' => null, 'controller' => 'posts', 'action' => 'view'); + $this->assertEquals($expected, $result); + + Router::reload(); + Router::connect('/posts/:id::url_title/*', array('controller' => 'posts', 'action' => 'view'), array('pass' => array('id', 'url_title'), 'id' => '[\d]+')); + $result = Router::parse('/posts/5:sample-post-title/other/params/4'); + $expected = array('pass' => array('5', 'sample-post-title', 'other', 'params', '4'), 'named' => array(), 'id' => 5, 'url_title' => 'sample-post-title', 'plugin' => null, 'controller' => 'posts', 'action' => 'view'); + $this->assertEquals($expected, $result); + + Router::reload(); + Router::connect('/posts/:url_title-(uuid::id)', array('controller' => 'posts', 'action' => 'view'), array('pass' => array('id', 'url_title'), 'id' => $UUID)); + $result = Router::parse('/posts/sample-post-title-(uuid:47fc97a9-019c-41d1-a058-1fa3cbdd56cb)'); + $expected = array('pass' => array('47fc97a9-019c-41d1-a058-1fa3cbdd56cb', 'sample-post-title'), 'named' => array(), 'id' => '47fc97a9-019c-41d1-a058-1fa3cbdd56cb', 'url_title' => 'sample-post-title', 'plugin' => null, 'controller' => 'posts', 'action' => 'view'); + $this->assertEquals($expected, $result); + + Router::reload(); + Router::connect('/posts/view/*', array('controller' => 'posts', 'action' => 'view'), array('named' => false)); + $result = Router::parse('/posts/view/foo:bar/routing:fun'); + $expected = array('pass' => array('foo:bar', 'routing:fun'), 'named' => array(), 'plugin' => null, 'controller' => 'posts', 'action' => 'view'); + $this->assertEquals($expected, $result); + + Router::reload(); + Router::connect('/posts/view/*', array('controller' => 'posts', 'action' => 'view'), array('named' => array('foo', 'answer'))); + $result = Router::parse('/posts/view/foo:bar/routing:fun/answer:42'); + $expected = array('pass' => array('routing:fun'), 'named' => array('foo' => 'bar', 'answer' => '42'), 'plugin' => null, 'controller' => 'posts', 'action' => 'view'); + $this->assertEquals($expected, $result); + + Router::reload(); + Router::connect('/posts/view/*', array('controller' => 'posts', 'action' => 'view'), array('named' => array('foo', 'answer'), 'greedyNamed' => true)); + $result = Router::parse('/posts/view/foo:bar/routing:fun/answer:42'); + $expected = array('pass' => array(), 'named' => array('foo' => 'bar', 'routing' => 'fun', 'answer' => '42'), 'plugin' => null, 'controller' => 'posts', 'action' => 'view'); + $this->assertEquals($expected, $result); + } + +/** + * test that the persist key works. + * + * @return void + */ + public function testPersistentParameters() { + Router::reload(); + Router::connect( + '/:lang/:color/posts/view/*', + array('controller' => 'posts', 'action' => 'view'), + array('persist' => array('lang', 'color') + )); + Router::connect( + '/:lang/:color/posts/index', + array('controller' => 'posts', 'action' => 'index'), + array('persist' => array('lang') + )); + Router::connect('/:lang/:color/posts/edit/*', array('controller' => 'posts', 'action' => 'edit')); + Router::connect('/about', array('controller' => 'pages', 'action' => 'view', 'about')); + Router::parse('/en/red/posts/view/5'); + + $request = new CakeRequest(); + Router::setRequestInfo( + $request->addParams(array( + 'lang' => 'en', + 'color' => 'red', + 'prefix' => 'admin', + 'plugin' => null, + 'action' => 'view', + 'controller' => 'posts', + ))->addPaths(array( + 'base' => '/', + 'here' => '/en/red/posts/view/5', + 'webroot' => '/', + )) + ); + $expected = '/en/red/posts/view/6'; + $result = Router::url(array('controller' => 'posts', 'action' => 'view', 6)); + $this->assertEquals($expected, $result); + + $expected = '/en/blue/posts/index'; + $result = Router::url(array('controller' => 'posts', 'action' => 'index', 'color' => 'blue')); + $this->assertEquals($expected, $result); + + $expected = '/posts/edit/6'; + $result = Router::url(array('controller' => 'posts', 'action' => 'edit', 6, 'color' => null, 'lang' => null)); + $this->assertEquals($expected, $result); + + $expected = '/posts'; + $result = Router::url(array('controller' => 'posts', 'action' => 'index')); + $this->assertEquals($expected, $result); + + $expected = '/posts/edit/7'; + $result = Router::url(array('controller' => 'posts', 'action' => 'edit', 7)); + $this->assertEquals($expected, $result); + + $expected = '/about'; + $result = Router::url(array('controller' => 'pages', 'action' => 'view', 'about')); + $this->assertEquals($expected, $result); + } + +/** + * testUuidRoutes method + * + * @return void + */ + public function testUuidRoutes() { + Router::connect( + '/subjects/add/:category_id', + array('controller' => 'subjects', 'action' => 'add'), + array('category_id' => '\w{8}-\w{4}-\w{4}-\w{4}-\w{12}') + ); + $result = Router::parse('/subjects/add/4795d601-19c8-49a6-930e-06a8b01d17b7'); + $expected = array('pass' => array(), 'named' => array(), 'category_id' => '4795d601-19c8-49a6-930e-06a8b01d17b7', 'plugin' => null, 'controller' => 'subjects', 'action' => 'add'); + $this->assertEquals($expected, $result); + } + +/** + * testRouteSymmetry method + * + * @return void + */ + public function testRouteSymmetry() { + Router::connect( + "/:extra/page/:slug/*", + array('controller' => 'pages', 'action' => 'view', 'extra' => null), + array("extra" => '[a-z1-9_]*', "slug" => '[a-z1-9_]+', "action" => 'view') + ); + + $result = Router::parse('/some_extra/page/this_is_the_slug'); + $expected = array('pass' => array(), 'named' => array(), 'plugin' => null, 'controller' => 'pages', 'action' => 'view', 'slug' => 'this_is_the_slug', 'extra' => 'some_extra'); + $this->assertEquals($expected, $result); + + $result = Router::parse('/page/this_is_the_slug'); + $expected = array('pass' => array(), 'named' => array(), 'plugin' => null, 'controller' => 'pages', 'action' => 'view', 'slug' => 'this_is_the_slug', 'extra' => null); + $this->assertEquals($expected, $result); + + Router::reload(); + Router::connect( + "/:extra/page/:slug/*", + array('controller' => 'pages', 'action' => 'view', 'extra' => null), + array("extra" => '[a-z1-9_]*', "slug" => '[a-z1-9_]+') + ); + Router::parse('/'); + + $result = Router::url(array('admin' => null, 'plugin' => null, 'controller' => 'pages', 'action' => 'view', 'slug' => 'this_is_the_slug', 'extra' => null)); + $expected = '/page/this_is_the_slug'; + $this->assertEquals($expected, $result); + + $result = Router::url(array('admin' => null, 'plugin' => null, 'controller' => 'pages', 'action' => 'view', 'slug' => 'this_is_the_slug', 'extra' => 'some_extra')); + $expected = '/some_extra/page/this_is_the_slug'; + $this->assertEquals($expected, $result); + } + +/** + * Test that Routing.prefixes are used when a Router instance is created + * or reset + * + * @return void + */ + public function testRoutingPrefixesSetting() { + $restore = Configure::read('Routing'); + + Configure::write('Routing.prefixes', array('admin', 'member', 'super_user')); + Router::reload(); + $result = Router::prefixes(); + $expected = array('admin', 'member', 'super_user'); + $this->assertEquals($expected, $result); + + Configure::write('Routing.prefixes', array('admin', 'member')); + Router::reload(); + $result = Router::prefixes(); + $expected = array('admin', 'member'); + $this->assertEquals($expected, $result); + + Configure::write('Routing', $restore); + } + +/** + * Test prefix routing and plugin combinations + * + * @return void + */ + public function testPrefixRoutingAndPlugins() { + Configure::write('Routing.prefixes', array('admin')); + $paths = App::path('plugins'); + App::build(array( + 'plugins' => array( + CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS + ) + ), App::RESET); + CakePlugin::load(array('TestPlugin')); + + Router::reload(); + require CAKE . 'Config' . DS . 'routes.php'; + $request = new CakeRequest(); + Router::setRequestInfo( + $request->addParams(array( + 'admin' => true, 'controller' => 'controller', 'action' => 'action', + 'plugin' => null, 'prefix' => 'admin' + ))->addPaths(array( + 'base' => '/', + 'here' => '/', + 'webroot' => '/base/', + )) + ); + Router::parse('/'); + + $result = Router::url(array('plugin' => 'test_plugin', 'controller' => 'test_plugin', 'action' => 'index')); + $expected = '/admin/test_plugin'; + $this->assertEquals($expected, $result); + + Router::reload(); + require CAKE . 'Config' . DS . 'routes.php'; + $request = new CakeRequest(); + Router::setRequestInfo( + $request->addParams(array( + 'plugin' => 'test_plugin', 'controller' => 'show_tickets', 'action' => 'admin_edit', + 'pass' => array('6'), 'prefix' => 'admin', 'admin' => true, 'form' => array(), + 'url' => array('url' => 'admin/shows/show_tickets/edit/6') + ))->addPaths(array( + 'base' => '/', + 'here' => '/admin/shows/show_tickets/edit/6', + 'webroot' => '/', + )) + ); + + $result = Router::url(array( + 'plugin' => 'test_plugin', 'controller' => 'show_tickets', 'action' => 'edit', 6, + 'admin' => true, 'prefix' => 'admin' + )); + $expected = '/admin/test_plugin/show_tickets/edit/6'; + $this->assertEquals($expected, $result); + + $result = Router::url(array( + 'plugin' => 'test_plugin', 'controller' => 'show_tickets', 'action' => 'index', 'admin' => true + )); + $expected = '/admin/test_plugin/show_tickets'; + $this->assertEquals($expected, $result); + + App::build(array('plugins' => $paths)); + } + +/** + * testParseExtensions method + * + * @return void + */ + public function testParseExtensions() { + $this->assertEquals(array(), Router::extensions()); + + Router::parseExtensions('rss'); + $this->assertEquals(array('rss'), Router::extensions()); + } + +/** + * testSetExtensions method + * + * @return void + */ + public function testSetExtensions() { + Router::setExtensions(array('rss')); + $this->assertEquals(array('rss'), Router::extensions()); + + require CAKE . 'Config' . DS . 'routes.php'; + $result = Router::parse('/posts.rss'); + $this->assertFalse(isset($result['ext'])); + + Router::parseExtensions(); + $result = Router::parse('/posts.rss'); + $this->assertEquals('rss', $result['ext']); + + $result = Router::parse('/posts.xml'); + $this->assertFalse(isset($result['ext'])); + + Router::setExtensions(array('xml')); + $result = Router::extensions(); + $this->assertEquals(array('rss', 'xml'), $result); + + $result = Router::parse('/posts.xml'); + $this->assertEquals('xml', $result['ext']); + + $result = Router::setExtensions(array('pdf'), false); + $this->assertEquals(array('pdf'), $result); + } + +/** + * testExtensionParsing method + * + * @return void + */ + public function testExtensionParsing() { + Router::parseExtensions(); + require CAKE . 'Config' . DS . 'routes.php'; + + $result = Router::parse('/posts.rss'); + $expected = array('plugin' => null, 'controller' => 'posts', 'action' => 'index', 'ext' => 'rss', 'pass' => array(), 'named' => array()); + $this->assertEquals($expected, $result); + + $result = Router::parse('/posts/view/1.rss'); + $expected = array('plugin' => null, 'controller' => 'posts', 'action' => 'view', 'pass' => array('1'), 'named' => array(), 'ext' => 'rss', 'named' => array()); + $this->assertEquals($expected, $result); + + $result = Router::parse('/posts/view/1.rss?query=test'); + $this->assertEquals($expected, $result); + + $result = Router::parse('/posts/view/1.atom'); + $expected['ext'] = 'atom'; + $this->assertEquals($expected, $result); + + Router::reload(); + require CAKE . 'Config' . DS . 'routes.php'; + + Router::parseExtensions('rss', 'xml'); + + $result = Router::parse('/posts.xml'); + $expected = array('plugin' => null, 'controller' => 'posts', 'action' => 'index', 'ext' => 'xml', 'pass' => array(), 'named' => array()); + $this->assertEquals($expected, $result); + + $result = Router::parse('/posts.atom?hello=goodbye'); + $expected = array('plugin' => null, 'controller' => 'posts.atom', 'action' => 'index', 'pass' => array(), 'named' => array()); + $this->assertEquals($expected, $result); + + Router::reload(); + Router::connect('/controller/action', array('controller' => 'controller', 'action' => 'action', 'ext' => 'rss')); + $result = Router::parse('/controller/action'); + $expected = array('controller' => 'controller', 'action' => 'action', 'plugin' => null, 'ext' => 'rss', 'named' => array(), 'pass' => array()); + $this->assertEquals($expected, $result); + + Router::reload(); + Router::parseExtensions('rss'); + Router::connect('/controller/action', array('controller' => 'controller', 'action' => 'action', 'ext' => 'rss')); + $result = Router::parse('/controller/action'); + $expected = array('controller' => 'controller', 'action' => 'action', 'plugin' => null, 'ext' => 'rss', 'named' => array(), 'pass' => array()); + $this->assertEquals($expected, $result); + } + +/** + * testQuerystringGeneration method + * + * @return void + */ + public function testQuerystringGeneration() { + $result = Router::url(array('controller' => 'posts', 'action' => 'index', '0', '?' => 'var=test&var2=test2')); + $expected = '/posts/index/0?var=test&var2=test2'; + $this->assertEquals($expected, $result); + + $result = Router::url(array('controller' => 'posts', 'action' => 'index', '0', '?' => array('var' => 'test', 'var2' => 'test2'))); + $this->assertEquals($expected, $result); + + $expected .= '&more=test+data'; + $result = Router::url(array('controller' => 'posts', 'action' => 'index', '0', '?' => array('var' => 'test', 'var2' => 'test2', 'more' => 'test data'))); + $this->assertEquals($expected, $result); + + // Test bug #4614 + $restore = ini_get('arg_separator.output'); + ini_set('arg_separator.output', '&'); + $result = Router::url(array('controller' => 'posts', 'action' => 'index', '0', '?' => array('var' => 'test', 'var2' => 'test2', 'more' => 'test data'))); + $this->assertEquals($expected, $result); + ini_set('arg_separator.output', $restore); + + $result = Router::url(array('controller' => 'posts', 'action' => 'index', '0', '?' => array('var' => 'test', 'var2' => 'test2')), array('escape' => true)); + $expected = '/posts/index/0?var=test&var2=test2'; + $this->assertEquals($expected, $result); + } + +/** + * testConnectNamed method + * + * @return void + */ + public function testConnectNamed() { + $named = Router::connectNamed(false, array('default' => true)); + $this->assertFalse($named['greedyNamed']); + $this->assertEquals(array_keys($named['rules']), $named['default']); + + Router::reload(); + Router::connect('/foo/*', array('controller' => 'bar', 'action' => 'fubar')); + Router::connectNamed(array(), array('separator' => '=')); + $result = Router::parse('/foo/param1=value1/param2=value2'); + $expected = array('pass' => array(), 'named' => array('param1' => 'value1', 'param2' => 'value2'), 'controller' => 'bar', 'action' => 'fubar', 'plugin' => null); + $this->assertEquals($expected, $result); + + Router::reload(); + Router::connect('/controller/action/*', array('controller' => 'controller', 'action' => 'action'), array('named' => array('param1' => 'value[\d]'))); + Router::connectNamed(array(), array('greedy' => false, 'separator' => '=')); + $result = Router::parse('/controller/action/param1=value1/param2=value2'); + $expected = array('pass' => array('param2=value2'), 'named' => array('param1' => 'value1'), 'controller' => 'controller', 'action' => 'action', 'plugin' => null); + $this->assertEquals($expected, $result); + + Router::reload(); + Router::connect('/:controller/:action/*'); + Router::connectNamed(array('page'), array('default' => false, 'greedy' => false)); + $result = Router::parse('/categories/index/limit=5'); + $this->assertTrue(empty($result['named'])); + } + +/** + * testNamedArgsUrlGeneration method + * + * @return void + */ + public function testNamedArgsUrlGeneration() { + $result = Router::url(array('controller' => 'posts', 'action' => 'index', 'published' => 1, 'deleted' => 1)); + $expected = '/posts/index/published:1/deleted:1'; + $this->assertEquals($expected, $result); + + $result = Router::url(array('controller' => 'posts', 'action' => 'index', 'published' => 0, 'deleted' => 0)); + $expected = '/posts/index/published:0/deleted:0'; + $this->assertEquals($expected, $result); + + Router::reload(); + extract(Router::getNamedExpressions()); + Router::connectNamed(array('file' => '[\w\.\-]+\.(html|png)')); + Router::connect('/', array('controller' => 'graphs', 'action' => 'index')); + Router::connect('/:id/*', array('controller' => 'graphs', 'action' => 'view'), array('id' => $ID)); + + $result = Router::url(array('controller' => 'graphs', 'action' => 'view', 'id' => 12, 'file' => 'asdf.png')); + $expected = '/12/file:asdf.png'; + $this->assertEquals($expected, $result); + + $result = Router::url(array('controller' => 'graphs', 'action' => 'view', 12, 'file' => 'asdf.foo')); + $expected = '/graphs/view/12/file:asdf.foo'; + $this->assertEquals($expected, $result); + + Configure::write('Routing.prefixes', array('admin')); + + Router::reload(); + $request = new CakeRequest(); + Router::setRequestInfo( + $request->addParams(array( + 'admin' => true, 'controller' => 'controller', 'action' => 'index', 'plugin' => null + ))->addPaths(array( + 'base' => '/', + 'here' => '/', + 'webroot' => '/base/', + )) + ); + Router::parse('/'); + + $result = Router::url(array('page' => 1, 0 => null, 'sort' => 'controller', 'direction' => 'asc', 'order' => null)); + $expected = "/admin/controller/index/page:1/sort:controller/direction:asc"; + $this->assertEquals($expected, $result); + + Router::reload(); + $request = new CakeRequest('admin/controller/index'); + $request->addParams(array( + 'admin' => true, 'controller' => 'controller', 'action' => 'index', 'plugin' => null + )); + $request->base = '/'; + Router::setRequestInfo($request); + + $result = Router::parse('/admin/controller/index/type:whatever'); + $result = Router::url(array('type' => 'new')); + $expected = "/admin/controller/index/type:new"; + $this->assertEquals($expected, $result); + } + +/** + * testNamedArgsUrlParsing method + * + * @return void + */ + public function testNamedArgsUrlParsing() { + Router::reload(); + require CAKE . 'Config' . DS . 'routes.php'; + $result = Router::parse('/controller/action/param1:value1:1/param2:value2:3/param:value'); + $expected = array('pass' => array(), 'named' => array('param1' => 'value1:1', 'param2' => 'value2:3', 'param' => 'value'), 'controller' => 'controller', 'action' => 'action', 'plugin' => null); + $this->assertEquals($expected, $result); + + Router::reload(); + require CAKE . 'Config' . DS . 'routes.php'; + $result = Router::connectNamed(false); + $this->assertEquals(array(), array_keys($result['rules'])); + $this->assertFalse($result['greedyNamed']); + $result = Router::parse('/controller/action/param1:value1:1/param2:value2:3/param:value'); + $expected = array('pass' => array('param1:value1:1', 'param2:value2:3', 'param:value'), 'named' => array(), 'controller' => 'controller', 'action' => 'action', 'plugin' => null); + $this->assertEquals($expected, $result); + + Router::reload(); + require CAKE . 'Config' . DS . 'routes.php'; + $result = Router::connectNamed(true); + $named = Router::namedConfig(); + $this->assertEquals($named['default'], array_keys($result['rules'])); + $this->assertTrue($result['greedyNamed']); + + Router::reload(); + require CAKE . 'Config' . DS . 'routes.php'; + Router::connectNamed(array('param1' => 'not-matching')); + $result = Router::parse('/controller/action/param1:value1:1/param2:value2:3/param:value'); + $expected = array('pass' => array('param1:value1:1'), 'named' => array('param2' => 'value2:3', 'param' => 'value'), 'controller' => 'controller', 'action' => 'action', 'plugin' => null); + $this->assertEquals($expected, $result); + + $result = Router::parse('/foo/view/param1:value1:1/param2:value2:3/param:value'); + $expected = array('pass' => array('param1:value1:1'), 'named' => array('param2' => 'value2:3', 'param' => 'value'), 'controller' => 'foo', 'action' => 'view', 'plugin' => null); + $this->assertEquals($expected, $result); + + Router::reload(); + require CAKE . 'Config' . DS . 'routes.php'; + Router::connectNamed(array('param1' => '[\d]', 'param2' => '[a-z]', 'param3' => '[\d]')); + $result = Router::parse('/controller/action/param1:1/param2:2/param3:3'); + $expected = array('pass' => array('param2:2'), 'named' => array('param1' => '1', 'param3' => '3'), 'controller' => 'controller', 'action' => 'action', 'plugin' => null); + $this->assertEquals($expected, $result); + + Router::reload(); + require CAKE . 'Config' . DS . 'routes.php'; + Router::connectNamed(array('param1' => '[\d]', 'param2' => true, 'param3' => '[\d]')); + $result = Router::parse('/controller/action/param1:1/param2:2/param3:3'); + $expected = array('pass' => array(), 'named' => array('param1' => '1', 'param2' => '2', 'param3' => '3'), 'controller' => 'controller', 'action' => 'action', 'plugin' => null); + $this->assertEquals($expected, $result); + + Router::reload(); + require CAKE . 'Config' . DS . 'routes.php'; + Router::connectNamed(array('param1' => 'value[\d]+:[\d]+'), array('greedy' => false)); + $result = Router::parse('/controller/action/param1:value1:1/param2:value2:3/param3:value'); + $expected = array('pass' => array('param2:value2:3', 'param3:value'), 'named' => array('param1' => 'value1:1'), 'controller' => 'controller', 'action' => 'action', 'plugin' => null); + $this->assertEquals($expected, $result); + } + +/** + * test url generation with legacy (1.2) style prefix routes. + * + * @return void + * @todo Remove tests related to legacy style routes. + * @see testUrlGenerationWithAutoPrefixes + */ + public function testUrlGenerationWithLegacyPrefixes() { + Router::reload(); + Router::connect('/protected/:controller/:action/*', array( + 'prefix' => 'protected', + 'protected' => true + )); + Router::parse('/'); + + $request = new CakeRequest(); + Router::setRequestInfo( + $request->addParams(array( + 'plugin' => null, 'controller' => 'images', 'action' => 'index', + 'prefix' => null, 'admin' => false,'url' => array('url' => 'images/index') + ))->addPaths(array( + 'base' => '', + 'here' => '/images/index', + 'webroot' => '/', + )) + ); + + $result = Router::url(array('protected' => true)); + $expected = '/protected/images/index'; + $this->assertEquals($expected, $result); + + $result = Router::url(array('controller' => 'images', 'action' => 'add')); + $expected = '/images/add'; + $this->assertEquals($expected, $result); + + $result = Router::url(array('controller' => 'images', 'action' => 'add', 'protected' => true)); + $expected = '/protected/images/add'; + $this->assertEquals($expected, $result); + + $result = Router::url(array('action' => 'edit', 1)); + $expected = '/images/edit/1'; + $this->assertEquals($expected, $result); + + $result = Router::url(array('action' => 'edit', 1, 'protected' => true)); + $expected = '/protected/images/edit/1'; + $this->assertEquals($expected, $result); + + $result = Router::url(array('action' => 'protected_edit', 1, 'protected' => true)); + $expected = '/protected/images/edit/1'; + $this->assertEquals($expected, $result); + + $result = Router::url(array('action' => 'edit', 1, 'protected' => true)); + $expected = '/protected/images/edit/1'; + $this->assertEquals($expected, $result); + + $result = Router::url(array('controller' => 'others', 'action' => 'edit', 1)); + $expected = '/others/edit/1'; + $this->assertEquals($expected, $result); + + $result = Router::url(array('controller' => 'others', 'action' => 'edit', 1, 'protected' => true)); + $expected = '/protected/others/edit/1'; + $this->assertEquals($expected, $result); + + $result = Router::url(array('controller' => 'others', 'action' => 'edit', 1, 'protected' => true, 'page' => 1)); + $expected = '/protected/others/edit/1/page:1'; + $this->assertEquals($expected, $result); + + Router::connectNamed(array('random')); + $result = Router::url(array('controller' => 'others', 'action' => 'edit', 1, 'protected' => true, 'random' => 'my-value')); + $expected = '/protected/others/edit/1/random:my-value'; + $this->assertEquals($expected, $result); + } + +/** + * test newer style automatically generated prefix routes. + * + * @return void + */ + public function testUrlGenerationWithAutoPrefixes() { + Configure::write('Routing.prefixes', array('protected')); + Router::reload(); + Router::parse('/'); + + $request = new CakeRequest(); + Router::setRequestInfo( + $request->addParams(array( + 'plugin' => null, 'controller' => 'images', 'action' => 'index', + 'prefix' => null, 'protected' => false, 'url' => array('url' => 'images/index') + ))->addPaths(array( + 'base' => '', + 'here' => '/images/index', + 'webroot' => '/', + )) + ); + + $result = Router::url(array('controller' => 'images', 'action' => 'add')); + $expected = '/images/add'; + $this->assertEquals($expected, $result); + + $result = Router::url(array('controller' => 'images', 'action' => 'add', 'protected' => true)); + $expected = '/protected/images/add'; + $this->assertEquals($expected, $result); + + $result = Router::url(array('controller' => 'images', 'action' => 'add_protected_test', 'protected' => true)); + $expected = '/protected/images/add_protected_test'; + $this->assertEquals($expected, $result); + + $result = Router::url(array('action' => 'edit', 1)); + $expected = '/images/edit/1'; + $this->assertEquals($expected, $result); + + $result = Router::url(array('action' => 'edit', 1, 'protected' => true)); + $expected = '/protected/images/edit/1'; + $this->assertEquals($expected, $result); + + $result = Router::url(array('action' => 'protected_edit', 1, 'protected' => true)); + $expected = '/protected/images/edit/1'; + $this->assertEquals($expected, $result); + + $result = Router::url(array('action' => 'protectededit', 1, 'protected' => true)); + $expected = '/protected/images/protectededit/1'; + $this->assertEquals($expected, $result); + + $result = Router::url(array('action' => 'edit', 1, 'protected' => true)); + $expected = '/protected/images/edit/1'; + $this->assertEquals($expected, $result); + + $result = Router::url(array('controller' => 'others', 'action' => 'edit', 1)); + $expected = '/others/edit/1'; + $this->assertEquals($expected, $result); + + $result = Router::url(array('controller' => 'others', 'action' => 'edit', 1, 'protected' => true)); + $expected = '/protected/others/edit/1'; + $this->assertEquals($expected, $result); + + $result = Router::url(array('controller' => 'others', 'action' => 'edit', 1, 'protected' => true, 'page' => 1)); + $expected = '/protected/others/edit/1/page:1'; + $this->assertEquals($expected, $result); + + Router::connectNamed(array('random')); + $result = Router::url(array('controller' => 'others', 'action' => 'edit', 1, 'protected' => true, 'random' => 'my-value')); + $expected = '/protected/others/edit/1/random:my-value'; + $this->assertEquals($expected, $result); + } + +/** + * test that auto-generated prefix routes persist + * + * @return void + */ + public function testAutoPrefixRoutePersistence() { + Configure::write('Routing.prefixes', array('protected')); + Router::reload(); + Router::parse('/'); + + $request = new CakeRequest(); + Router::setRequestInfo( + $request->addParams(array( + 'plugin' => null, 'controller' => 'images', 'action' => 'index', 'prefix' => 'protected', + 'protected' => true, 'url' => array('url' => 'protected/images/index') + ))->addPaths(array( + 'base' => '', + 'here' => '/protected/images/index', + 'webroot' => '/', + )) + ); + + $result = Router::url(array('controller' => 'images', 'action' => 'add')); + $expected = '/protected/images/add'; + $this->assertEquals($expected, $result); + + $result = Router::url(array('controller' => 'images', 'action' => 'add', 'protected' => false)); + $expected = '/images/add'; + $this->assertEquals($expected, $result); + } + +/** + * test that setting a prefix override the current one + * + * @return void + */ + public function testPrefixOverride() { + Configure::write('Routing.prefixes', array('protected', 'admin')); + Router::reload(); + Router::parse('/'); + + $request = new CakeRequest(); + Router::setRequestInfo( + $request->addParams(array( + 'plugin' => null, 'controller' => 'images', 'action' => 'index', 'prefix' => 'protected', + 'protected' => true, 'url' => array('url' => 'protected/images/index') + ))->addPaths(array( + 'base' => '', + 'here' => '/protected/images/index', + 'webroot' => '/', + )) + ); + + $result = Router::url(array('controller' => 'images', 'action' => 'add', 'admin' => true)); + $expected = '/admin/images/add'; + $this->assertEquals($expected, $result); + + $request = new CakeRequest(); + Router::setRequestInfo( + $request->addParams(array( + 'plugin' => null, 'controller' => 'images', 'action' => 'index', 'prefix' => 'admin', + 'admin' => true, 'url' => array('url' => 'admin/images/index') + ))->addPaths(array( + 'base' => '', + 'here' => '/admin/images/index', + 'webroot' => '/', + )) + ); + $result = Router::url(array('controller' => 'images', 'action' => 'add', 'protected' => true)); + $expected = '/protected/images/add'; + $this->assertEquals($expected, $result); + } + +/** + * Test that setting a prefix to false is ignored, as its generally user error. + * + * @return void + */ + public function testPrefixFalseIgnored() { + Configure::write('Routing.prefixes', array('admin')); + Router::reload(); + + Router::connect('/cache_css/*', array('admin' => false, 'controller' => 'asset_compress', 'action' => 'get')); + + $url = Router::url(array('controller' => 'asset_compress', 'action' => 'get', 'test')); + $expected = '/cache_css/test'; + $this->assertEquals($expected, $url); + + $url = Router::url(array('admin' => false, 'controller' => 'asset_compress', 'action' => 'get', 'test')); + $expected = '/cache_css/test'; + $this->assertEquals($expected, $url); + + $url = Router::url(array('admin' => true, 'controller' => 'asset_compress', 'action' => 'get', 'test')); + $this->assertEquals('/admin/asset_compress/get/test', $url); + } + +/** + * testRemoveBase method + * + * @return void + */ + public function testRemoveBase() { + $request = new CakeRequest(); + Router::setRequestInfo( + $request->addParams(array( + 'plugin' => null, 'controller' => 'controller', 'action' => 'index', + 'bare' => 0, 'url' => array('url' => 'protected/images/index') + ))->addPaths(array( + 'base' => '/base', + 'here' => '/', + 'webroot' => '/base/', + )) + ); + + $result = Router::url(array('controller' => 'my_controller', 'action' => 'my_action')); + $expected = '/base/my_controller/my_action'; + $this->assertEquals($expected, $result); + + $result = Router::url(array('controller' => 'my_controller', 'action' => 'my_action', 'base' => false)); + $expected = '/my_controller/my_action'; + $this->assertEquals($expected, $result); + + $result = Router::url(array('controller' => 'my_controller', 'action' => 'my_action', 'base' => true)); + $expected = '/base/my_controller/my_action/base:1'; + $this->assertEquals($expected, $result); + } + +/** + * testPagesUrlParsing method + * + * @return void + */ + public function testPagesUrlParsing() { + Router::connect('/', array('controller' => 'pages', 'action' => 'display', 'home')); + Router::connect('/pages/*', array('controller' => 'pages', 'action' => 'display')); + + $result = Router::parse('/'); + $expected = array('pass' => array('home'), 'named' => array(), 'plugin' => null, 'controller' => 'pages', 'action' => 'display'); + $this->assertEquals($expected, $result); + + $result = Router::parse('/pages/home/'); + $expected = array('pass' => array('home'), 'named' => array(), 'plugin' => null, 'controller' => 'pages', 'action' => 'display'); + $this->assertEquals($expected, $result); + + Router::reload(); + require CAKE . 'Config' . DS . 'routes.php'; + Router::connect('/', array('controller' => 'pages', 'action' => 'display', 'home')); + + $result = Router::parse('/'); + $expected = array('pass' => array('home'), 'named' => array(), 'plugin' => null, 'controller' => 'pages', 'action' => 'display'); + $this->assertEquals($expected, $result); + + $result = Router::parse('/pages/display/home/event:value'); + $expected = array('pass' => array('home'), 'named' => array('event' => 'value'), 'plugin' => null, 'controller' => 'pages', 'action' => 'display'); + $this->assertEquals($expected, $result); + + $result = Router::parse('/pages/display/home/event:Val_u2'); + $expected = array('pass' => array('home'), 'named' => array('event' => 'Val_u2'), 'plugin' => null, 'controller' => 'pages', 'action' => 'display'); + $this->assertEquals($expected, $result); + + $result = Router::parse('/pages/display/home/event:val-ue'); + $expected = array('pass' => array('home'), 'named' => array('event' => 'val-ue'), 'plugin' => null, 'controller' => 'pages', 'action' => 'display'); + $this->assertEquals($expected, $result); + + Router::reload(); + Router::connect('/', array('controller' => 'posts', 'action' => 'index')); + Router::connect('/pages/*', array('controller' => 'pages', 'action' => 'display')); + $result = Router::parse('/pages/contact/'); + + $expected = array('pass' => array('contact'), 'named' => array(), 'plugin' => null, 'controller' => 'pages', 'action' => 'display'); + $this->assertEquals($expected, $result); + } + +/** + * test that requests with a trailing dot don't loose the do. + * + * @return void + */ + public function testParsingWithTrailingPeriod() { + Router::reload(); + Router::connect('/:controller/:action/*'); + $result = Router::parse('/posts/view/something.'); + $this->assertEquals('something.', $result['pass'][0], 'Period was chopped off %s'); + + $result = Router::parse('/posts/view/something. . .'); + $this->assertEquals('something. . .', $result['pass'][0], 'Period was chopped off %s'); + } + +/** + * test that requests with a trailing dot don't loose the do. + * + * @return void + */ + public function testParsingWithTrailingPeriodAndParseExtensions() { + Router::reload(); + Router::connect('/:controller/:action/*'); + Router::parseExtensions('json'); + + $result = Router::parse('/posts/view/something.'); + $this->assertEquals('something.', $result['pass'][0], 'Period was chopped off %s'); + + $result = Router::parse('/posts/view/something. . .'); + $this->assertEquals('something. . .', $result['pass'][0], 'Period was chopped off %s'); + } + +/** + * test that patterns work for :action + * + * @return void + */ + public function testParsingWithPatternOnAction() { + Router::reload(); + Router::connect( + '/blog/:action/*', + array('controller' => 'blog_posts'), + array('action' => 'other|actions') + ); + $result = Router::parse('/blog/other'); + $expected = array( + 'plugin' => null, + 'controller' => 'blog_posts', + 'action' => 'other', + 'pass' => array(), + 'named' => array() + ); + $this->assertEquals($expected, $result); + + $result = Router::parse('/blog/foobar'); + $this->assertEquals(array(), $result); + + $result = Router::url(array('controller' => 'blog_posts', 'action' => 'foo')); + $this->assertEquals('/blog_posts/foo', $result); + + $result = Router::url(array('controller' => 'blog_posts', 'action' => 'actions')); + $this->assertEquals('/blog/actions', $result); + } + +/** + * testParsingWithPrefixes method + * + * @return void + */ + public function testParsingWithPrefixes() { + $adminParams = array('prefix' => 'admin', 'admin' => true); + Router::connect('/admin/:controller', $adminParams); + Router::connect('/admin/:controller/:action', $adminParams); + Router::connect('/admin/:controller/:action/*', $adminParams); + + $request = new CakeRequest(); + Router::setRequestInfo( + $request->addParams(array( + 'plugin' => null, 'controller' => 'controller', 'action' => 'index' + ))->addPaths(array( + 'base' => '/base', + 'here' => '/', + 'webroot' => '/base/', + )) + ); + + $result = Router::parse('/admin/posts/'); + $expected = array('pass' => array(), 'named' => array(), 'prefix' => 'admin', 'plugin' => null, 'controller' => 'posts', 'action' => 'admin_index', 'admin' => true); + $this->assertEquals($expected, $result); + + $result = Router::parse('/admin/posts'); + $this->assertEquals($expected, $result); + + $result = Router::url(array('admin' => true, 'controller' => 'posts')); + $expected = '/base/admin/posts'; + $this->assertEquals($expected, $result); + + $result = Router::prefixes(); + $expected = array('admin'); + $this->assertEquals($expected, $result); + + Router::reload(); + + $prefixParams = array('prefix' => 'members', 'members' => true); + Router::connect('/members/:controller', $prefixParams); + Router::connect('/members/:controller/:action', $prefixParams); + Router::connect('/members/:controller/:action/*', $prefixParams); + + $request = new CakeRequest(); + Router::setRequestInfo( + $request->addParams(array( + 'plugin' => null, 'controller' => 'controller', 'action' => 'index', + 'bare' => 0 + ))->addPaths(array( + 'base' => '/base', + 'here' => '/', + 'webroot' => '/', + )) + ); + + $result = Router::parse('/members/posts/index'); + $expected = array('pass' => array(), 'named' => array(), 'prefix' => 'members', 'plugin' => null, 'controller' => 'posts', 'action' => 'members_index', 'members' => true); + $this->assertEquals($expected, $result); + + $result = Router::url(array('members' => true, 'controller' => 'posts', 'action' => 'index', 'page' => 2)); + $expected = '/base/members/posts/index/page:2'; + $this->assertEquals($expected, $result); + + $result = Router::url(array('members' => true, 'controller' => 'users', 'action' => 'add')); + $expected = '/base/members/users/add'; + $this->assertEquals($expected, $result); + } + +/** + * Tests URL generation with flags and prefixes in and out of context + * + * @return void + */ + public function testUrlWritingWithPrefixes() { + Router::connect('/company/:controller/:action/*', array('prefix' => 'company', 'company' => true)); + Router::connect('/login', array('controller' => 'users', 'action' => 'login')); + + $result = Router::url(array('controller' => 'users', 'action' => 'login', 'company' => true)); + $expected = '/company/users/login'; + $this->assertEquals($expected, $result); + + $result = Router::url(array('controller' => 'users', 'action' => 'company_login', 'company' => true)); + $expected = '/company/users/login'; + $this->assertEquals($expected, $result); + + $request = new CakeRequest(); + Router::setRequestInfo( + $request->addParams(array( + 'plugin' => null, 'controller' => 'users', 'action' => 'login', + 'company' => true + ))->addPaths(array( + 'base' => '/', + 'here' => '/', + 'webroot' => '/base/', + )) + ); + + $result = Router::url(array('controller' => 'users', 'action' => 'login', 'company' => false)); + $expected = '/login'; + $this->assertEquals($expected, $result); + } + +/** + * test url generation with prefixes and custom routes + * + * @return void + */ + public function testUrlWritingWithPrefixesAndCustomRoutes() { + Router::connect( + '/admin/login', + array('controller' => 'users', 'action' => 'login', 'prefix' => 'admin', 'admin' => true) + ); + $request = new CakeRequest(); + Router::setRequestInfo( + $request->addParams(array( + 'plugin' => null, 'controller' => 'posts', 'action' => 'index', + 'admin' => true, 'prefix' => 'admin' + ))->addPaths(array( + 'base' => '/', + 'here' => '/', + 'webroot' => '/', + )) + ); + $result = Router::url(array('controller' => 'users', 'action' => 'login', 'admin' => true)); + $this->assertEquals('/admin/login', $result); + + $result = Router::url(array('controller' => 'users', 'action' => 'login')); + $this->assertEquals('/admin/login', $result); + + $result = Router::url(array('controller' => 'users', 'action' => 'admin_login')); + $this->assertEquals('/admin/login', $result); + } + +/** + * testPassedArgsOrder method + * + * @return void + */ + public function testPassedArgsOrder() { + Router::connect('/test-passed/*', array('controller' => 'pages', 'action' => 'display', 'home')); + Router::connect('/test2/*', array('controller' => 'pages', 'action' => 'display', 2)); + Router::connect('/test/*', array('controller' => 'pages', 'action' => 'display', 1)); + Router::parse('/'); + + $result = Router::url(array('controller' => 'pages', 'action' => 'display', 1, 'whatever')); + $expected = '/test/whatever'; + $this->assertEquals($expected, $result); + + $result = Router::url(array('controller' => 'pages', 'action' => 'display', 2, 'whatever')); + $expected = '/test2/whatever'; + $this->assertEquals($expected, $result); + + $result = Router::url(array('controller' => 'pages', 'action' => 'display', 'home', 'whatever')); + $expected = '/test-passed/whatever'; + $this->assertEquals($expected, $result); + + Configure::write('Routing.prefixes', array('admin')); + Router::reload(); + + $request = new CakeRequest(); + Router::setRequestInfo( + $request->addParams(array( + 'plugin' => null, 'controller' => 'images', 'action' => 'index', + 'url' => array('url' => 'protected/images/index') + ))->addPaths(array( + 'base' => '', + 'here' => '/protected/images/index', + 'webroot' => '/', + )) + ); + + Router::connect('/protected/:controller/:action/*', array( + 'controller' => 'users', + 'action' => 'index', + 'prefix' => 'protected' + )); + + Router::parse('/'); + $result = Router::url(array('controller' => 'images', 'action' => 'add')); + $expected = '/protected/images/add'; + $this->assertEquals($expected, $result); + + $result = Router::prefixes(); + $expected = array('admin', 'protected'); + $this->assertEquals($expected, $result); + } + +/** + * testRegexRouteMatching method + * + * @return void + */ + public function testRegexRouteMatching() { + Router::connect('/:locale/:controller/:action/*', array(), array('locale' => 'dan|eng')); + + $result = Router::parse('/eng/test/test_action'); + $expected = array('pass' => array(), 'named' => array(), 'locale' => 'eng', 'controller' => 'test', 'action' => 'test_action', 'plugin' => null); + $this->assertEquals($expected, $result); + + $result = Router::parse('/badness/test/test_action'); + $this->assertEquals(array(), $result); + + Router::reload(); + Router::connect('/:locale/:controller/:action/*', array(), array('locale' => 'dan|eng')); + + $request = new CakeRequest(); + Router::setRequestInfo( + $request->addParams(array( + 'plugin' => null, 'controller' => 'test', 'action' => 'index', + 'url' => array('url' => 'test/test_action') + ))->addPaths(array( + 'base' => '', + 'here' => '/test/test_action', + 'webroot' => '/', + )) + ); + + $result = Router::url(array('action' => 'test_another_action')); + $expected = '/test/test_another_action'; + $this->assertEquals($expected, $result); + + $result = Router::url(array('action' => 'test_another_action', 'locale' => 'eng')); + $expected = '/eng/test/test_another_action'; + $this->assertEquals($expected, $result); + + $result = Router::url(array('action' => 'test_another_action', 'locale' => 'badness')); + $expected = '/test/test_another_action/locale:badness'; + $this->assertEquals($expected, $result); + } + +/** + * testStripPlugin + * + * @return void + */ + public function testStripPlugin() { + $pluginName = 'forums'; + $url = 'example.com/' . $pluginName . '/'; + $expected = 'example.com'; + + $this->assertEquals($expected, Router::stripPlugin($url, $pluginName)); + $this->assertEquals(Router::stripPlugin($url), $url); + $this->assertEquals(Router::stripPlugin($url, null), $url); + } + +/** + * testCurrentRoute + * + * This test needs some improvement and actual requestAction() usage + * + * @return void + */ + public function testCurrentRoute() { + $url = array('controller' => 'pages', 'action' => 'display', 'government'); + Router::connect('/government', $url); + Router::parse('/government'); + $route = Router::currentRoute(); + $this->assertEquals(array_merge($url, array('plugin' => null)), $route->defaults); + } + +/** + * testRequestRoute + * + * @return void + */ + public function testRequestRoute() { + $url = array('controller' => 'products', 'action' => 'display', 5); + Router::connect('/government', $url); + Router::parse('/government'); + $route = Router::requestRoute(); + $this->assertEquals(array_merge($url, array('plugin' => null)), $route->defaults); + + // test that the first route is matched + $newUrl = array('controller' => 'products', 'action' => 'display', 6); + Router::connect('/government', $url); + Router::parse('/government'); + $route = Router::requestRoute(); + $this->assertEquals(array_merge($url, array('plugin' => null)), $route->defaults); + + // test that an unmatched route does not change the current route + $newUrl = array('controller' => 'products', 'action' => 'display', 6); + Router::connect('/actor', $url); + Router::parse('/government'); + $route = Router::requestRoute(); + $this->assertEquals(array_merge($url, array('plugin' => null)), $route->defaults); + } + +/** + * testGetParams + * + * @return void + */ + public function testGetParams() { + $paths = array('base' => '/', 'here' => '/products/display/5', 'webroot' => '/webroot'); + $params = array('param1' => '1', 'param2' => '2'); + Router::setRequestInfo(array($params, $paths)); + + $expected = array( + 'plugin' => null, 'controller' => false, 'action' => false, + 'named' => array(), 'pass' => array(), + 'param1' => '1', 'param2' => '2', + ); + $this->assertEquals(Router::getParams(), $expected); + $this->assertEquals(Router::getParam('controller'), false); + $this->assertEquals(Router::getParam('param1'), '1'); + $this->assertEquals(Router::getParam('param2'), '2'); + + Router::reload(); + + $params = array('controller' => 'pages', 'action' => 'display'); + Router::setRequestInfo(array($params, $paths)); + $expected = array( + 'plugin' => null, 'controller' => 'pages', 'action' => 'display', + 'named' => array(), 'pass' => array(), + ); + $this->assertEquals(Router::getParams(), $expected); + $this->assertEquals(Router::getParams(true), $expected); + } + +/** + * test that connectDefaults() can disable default route connection + * + * @return void + */ + public function testDefaultsMethod() { + Router::connect('/test/*', array('controller' => 'pages', 'action' => 'display', 2)); + $result = Router::parse('/posts/edit/5'); + $this->assertFalse(isset($result['controller'])); + $this->assertFalse(isset($result['action'])); + } + +/** + * test that the required default routes are connected. + * + * @return void + */ + public function testConnectDefaultRoutes() { + App::build(array( + 'plugins' => array( + CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS + ) + ), App::RESET); + CakePlugin::load(array('TestPlugin', 'PluginJs')); + Router::reload(); + require CAKE . 'Config' . DS . 'routes.php'; + + $result = Router::url(array('plugin' => 'plugin_js', 'controller' => 'js_file', 'action' => 'index')); + $this->assertEquals('/plugin_js/js_file', $result); + + $result = Router::parse('/plugin_js/js_file'); + $expected = array( + 'plugin' => 'plugin_js', 'controller' => 'js_file', 'action' => 'index', + 'named' => array(), 'pass' => array() + ); + $this->assertEquals($expected, $result); + + $result = Router::url(array('plugin' => 'test_plugin', 'controller' => 'test_plugin', 'action' => 'index')); + $this->assertEquals('/test_plugin', $result); + + $result = Router::parse('/test_plugin'); + $expected = array( + 'plugin' => 'test_plugin', 'controller' => 'test_plugin', 'action' => 'index', + 'named' => array(), 'pass' => array() + ); + + $this->assertEquals($expected, $result, 'Plugin shortcut route broken. %s'); + } + +/** + * test using a custom route class for route connection + * + * @return void + */ + public function testUsingCustomRouteClass() { + $mock = $this->getMock('CakeRoute', array(), array(), 'MockConnectedRoute', false); + $routes = Router::connect( + '/:slug', + array('controller' => 'posts', 'action' => 'view'), + array('routeClass' => 'MockConnectedRoute', 'slug' => '[a-z_-]+') + ); + $this->assertTrue(is_a($routes[0], 'MockConnectedRoute'), 'Incorrect class used. %s'); + $expected = array('controller' => 'posts', 'action' => 'view', 'slug' => 'test'); + $routes[0]->expects($this->any()) + ->method('parse') + ->will($this->returnValue($expected)); + $result = Router::parse('/test'); + $this->assertEquals($expected, $result); + } + +/** + * test that route classes must extend CakeRoute + * + * @expectedException RouterException + * @return void + */ + public function testCustomRouteException() { + Router::connect('/:controller', array(), array('routeClass' => 'Object')); + } + +/** + * test reversing parameter arrays back into strings. + * + * @return void + */ + public function testRouterReverse() { + $params = array( + 'controller' => 'posts', + 'action' => 'view', + 'pass' => array(1), + 'named' => array(), + 'url' => array(), + 'autoRender' => 1, + 'bare' => 1, + 'return' => 1, + 'requested' => 1, + '_Token' => array('key' => 'sekret') + ); + $result = Router::reverse($params); + $this->assertEquals('/posts/view/1', $result); + + $params = array( + 'controller' => 'posts', + 'action' => 'index', + 'pass' => array(1), + 'named' => array('page' => 1, 'sort' => 'Article.title', 'direction' => 'desc'), + 'url' => array() + ); + $result = Router::reverse($params); + $this->assertEquals('/posts/index/1/page:1/sort:Article.title/direction:desc', $result); + + Router::connect('/:lang/:controller/:action/*', array(), array('lang' => '[a-z]{3}')); + $params = array( + 'lang' => 'eng', + 'controller' => 'posts', + 'action' => 'view', + 'pass' => array(1), + 'named' => array(), + 'url' => array('url' => 'eng/posts/view/1') + ); + $result = Router::reverse($params); + $this->assertEquals('/eng/posts/view/1', $result); + + $params = array( + 'lang' => 'eng', + 'controller' => 'posts', + 'action' => 'view', + 'pass' => array(1), + 'named' => array(), + 'url' => array('url' => 'eng/posts/view/1', 'foo' => 'bar', 'baz' => 'quu'), + 'paging' => array(), + 'models' => array() + ); + $result = Router::reverse($params); + $this->assertEquals('/eng/posts/view/1?foo=bar&baz=quu', $result); + + $request = new CakeRequest('/eng/posts/view/1'); + $request->addParams(array( + 'lang' => 'eng', + 'controller' => 'posts', + 'action' => 'view', + 'pass' => array(1), + 'named' => array(), + )); + $request->query = array('url' => 'eng/posts/view/1', 'test' => 'value'); + $result = Router::reverse($request); + $expected = '/eng/posts/view/1?test=value'; + $this->assertEquals($expected, $result); + + $params = array( + 'lang' => 'eng', + 'controller' => 'posts', + 'action' => 'view', + 'pass' => array(1), + 'named' => array(), + 'url' => array('url' => 'eng/posts/view/1') + ); + $result = Router::reverse($params, true); + $this->assertRegExp('/^http(s)?:\/\//', $result); + } + +/** + * Test that extensions work with Router::reverse() + * + * @return void + */ + public function testReverseWithExtension() { + Router::parseExtensions('json'); + + $request = new CakeRequest('/posts/view/1.json'); + $request->addParams(array( + 'controller' => 'posts', + 'action' => 'view', + 'pass' => array(1), + 'named' => array(), + 'ext' => 'json', + )); + $request->query = array(); + $result = Router::reverse($request); + $expected = '/posts/view/1.json'; + $this->assertEquals($expected, $result); + } + +/** + * test that setRequestInfo can accept arrays and turn that into a CakeRequest object. + * + * @return void + */ + public function testSetRequestInfoLegacy() { + Router::setRequestInfo(array( + array( + 'plugin' => null, 'controller' => 'images', 'action' => 'index', + 'url' => array('url' => 'protected/images/index') + ), + array( + 'base' => '', + 'here' => '/protected/images/index', + 'webroot' => '/', + ) + )); + $result = Router::getRequest(); + $this->assertEquals('images', $result->controller); + $this->assertEquals('index', $result->action); + $this->assertEquals('', $result->base); + $this->assertEquals('/protected/images/index', $result->here); + $this->assertEquals('/', $result->webroot); + } + +/** + * Test that Router::url() uses the first request + */ + public function testUrlWithRequestAction() { + $firstRequest = new CakeRequest('/posts/index'); + $firstRequest->addParams(array( + 'plugin' => null, + 'controller' => 'posts', + 'action' => 'index' + ))->addPaths(array('base' => '')); + + $secondRequest = new CakeRequest('/posts/index'); + $secondRequest->addParams(array( + 'requested' => 1, + 'plugin' => null, + 'controller' => 'comments', + 'action' => 'listing' + ))->addPaths(array('base' => '')); + + Router::setRequestInfo($firstRequest); + Router::setRequestInfo($secondRequest); + + $result = Router::url(array('base' => false)); + $this->assertEquals('/comments/listing', $result, 'with second requests, the last should win.'); + + Router::popRequest(); + $result = Router::url(array('base' => false)); + $this->assertEquals('/posts', $result, 'with second requests, the last should win.'); + } + +/** + * test that a route object returning a full url is not modified. + * + * @return void + */ + public function testUrlFullUrlReturnFromRoute() { + $url = 'http://example.com/posts/view/1'; + + $this->getMock('CakeRoute', array(), array('/'), 'MockReturnRoute'); + $routes = Router::connect('/:controller/:action', array(), array('routeClass' => 'MockReturnRoute')); + $routes[0]->expects($this->any())->method('match') + ->will($this->returnValue($url)); + + $result = Router::url(array('controller' => 'posts', 'action' => 'view', 1)); + $this->assertEquals($url, $result); + } + +/** + * test protocol in url + * + * @return void + */ + public function testUrlProtocol() { + $url = 'http://example.com'; + $this->assertEquals($url, Router::url($url)); + + $url = 'ed2k://example.com'; + $this->assertEquals($url, Router::url($url)); + + $url = 'svn+ssh://example.com'; + $this->assertEquals($url, Router::url($url)); + + $url = '://example.com'; + $this->assertEquals($url, Router::url($url)); + } + +/** + * Testing that patterns on the :action param work properly. + * + * @return void + */ + public function testPatternOnAction() { + $route = new CakeRoute( + '/blog/:action/*', + array('controller' => 'blog_posts'), + array('action' => 'other|actions') + ); + $result = $route->match(array('controller' => 'blog_posts', 'action' => 'foo')); + $this->assertFalse($result); + + $result = $route->match(array('controller' => 'blog_posts', 'action' => 'actions')); + $this->assertEquals('/blog/actions/', $result); + + $result = $route->parse('/blog/other'); + $expected = array('controller' => 'blog_posts', 'action' => 'other', 'pass' => array(), 'named' => array()); + $this->assertEquals($expected, $result); + + $result = $route->parse('/blog/foobar'); + $this->assertFalse($result); + } + +/** + * Tests resourceMap as getter and setter. + * + * @return void + */ + public function testResourceMap() { + $default = Router::resourceMap(); + $expected = array( + array('action' => 'index', 'method' => 'GET', 'id' => false), + array('action' => 'view', 'method' => 'GET', 'id' => true), + array('action' => 'add', 'method' => 'POST', 'id' => false), + array('action' => 'edit', 'method' => 'PUT', 'id' => true), + array('action' => 'delete', 'method' => 'DELETE', 'id' => true), + array('action' => 'edit', 'method' => 'POST', 'id' => true) + ); + $this->assertEquals($default, $expected); + + $custom = array( + array('action' => 'index', 'method' => 'GET', 'id' => false), + array('action' => 'view', 'method' => 'GET', 'id' => true), + array('action' => 'add', 'method' => 'POST', 'id' => false), + array('action' => 'edit', 'method' => 'PUT', 'id' => true), + array('action' => 'delete', 'method' => 'DELETE', 'id' => true), + array('action' => 'update', 'method' => 'POST', 'id' => true) + ); + Router::resourceMap($custom); + $this->assertEquals(Router::resourceMap(), $custom); + + Router::resourceMap($default); + } + +/** + * test setting redirect routes + * + * @return void + */ + public function testRouteRedirection() { + Router::redirect('/blog', array('controller' => 'posts'), array('status' => 302)); + $this->assertEquals(1, count(Router::$routes)); + Router::$routes[0]->response = $this->getMock('CakeResponse', array('_sendHeader')); + Router::$routes[0]->stop = false; + $this->assertEquals(302, Router::$routes[0]->options['status']); + + Router::parse('/blog'); + $header = Router::$routes[0]->response->header(); + $this->assertEquals(Router::url('/posts', true), $header['Location']); + $this->assertEquals(302, Router::$routes[0]->response->statusCode()); + + Router::$routes[0]->response = $this->getMock('CakeResponse', array('_sendHeader')); + Router::parse('/not-a-match'); + $this->assertEquals(array(), Router::$routes[0]->response->header()); + } + +/** + * Test setting the default route class + * + * @return void + */ + public function testDefaultRouteClass() { + $this->getMock('CakeRoute', array(), array('/test'), 'TestDefaultRouteClass'); + Router::defaultRouteClass('TestDefaultRouteClass'); + + $result = Router::connect('/', array('controller' => 'pages', 'action' => 'display', 'home')); + $this->assertInstanceOf('TestDefaultRouteClass', $result[0]); + } + +/** + * Test getting the default route class + * + * @return void + */ + public function testDefaultRouteClassGetter() { + $routeClass = 'TestDefaultRouteClass'; + Router::defaultRouteClass($routeClass); + + $this->assertEquals($routeClass, Router::defaultRouteClass()); + $this->assertEquals($routeClass, Router::defaultRouteClass(null)); + } + +/** + * Test that route classes must extend CakeRoute + * + * @expectedException RouterException + * @return void + */ + public function testDefaultRouteException() { + Router::defaultRouteClass(''); + Router::connect('/:controller', array()); + } + +/** + * Test that route classes must extend CakeRoute + * + * @expectedException RouterException + * @return void + */ + public function testSettingInvalidDefaultRouteException() { + Router::defaultRouteClass('Object'); + } + +/** + * Test that class must exist + * + * @expectedException RouterException + * @return void + */ + public function testSettingNonExistentDefaultRouteException() { + Router::defaultRouteClass('NonExistentClass'); + } + +/** + * Tests generating well-formed querystrings + * + * @return void + */ + public function testQueryString() { + $result = Router::queryString(array('var' => 'foo bar')); + $expected = '?var=foo+bar'; + $this->assertEquals($expected, $result); + + $result = Router::queryString(false, array('some' => 'param', 'foo' => 'bar')); + $expected = '?some=param&foo=bar'; + $this->assertEquals($expected, $result); + + $existing = array('apple' => 'red', 'pear' => 'green'); + $result = Router::queryString($existing, array('some' => 'param', 'foo' => 'bar')); + $expected = '?apple=red&pear=green&some=param&foo=bar'; + $this->assertEquals($expected, $result); + + $existing = 'apple=red&pear=green'; + $result = Router::queryString($existing, array('some' => 'param', 'foo' => 'bar')); + $expected = '?apple=red&pear=green&some=param&foo=bar'; + $this->assertEquals($expected, $result); + + $existing = '?apple=red&pear=green'; + $result = Router::queryString($existing, array('some' => 'param', 'foo' => 'bar')); + $expected = '?apple=red&pear=green&some=param&foo=bar'; + $this->assertEquals($expected, $result); + + $result = Router::queryString('apple=red&pear=green'); + $expected = '?apple=red&pear=green'; + $this->assertEquals($expected, $result); + + $result = Router::queryString('foo=bar', array('php' => 'nut', 'jose' => 'zap'), true); + $expected = '?foo=bar&php=nut&jose=zap'; + $this->assertEquals($expected, $result); + + $result = Router::queryString('foo=bar&', array('php' => 'nut', 'jose' => 'zap'), true); + $expected = '?foo=bar&php=nut&jose=zap'; + $this->assertEquals($expected, $result); + + $result = Router::queryString('foo=bar&', array('php' => 'nut', 'jose' => 'zap')); + $expected = '?foo=bar&php=nut&jose=zap'; + $this->assertEquals($expected, $result); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/TestSuite/CakeTestCaseTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/TestSuite/CakeTestCaseTest.php new file mode 100644 index 0000000..ccc4356 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/TestSuite/CakeTestCaseTest.php @@ -0,0 +1,342 @@ +Reporter = $this->getMock('CakeHtmlReporter'); + } + +/** + * tearDown + * + * @return void + */ + public function tearDown() { + parent::tearDown(); + unset($this->Result); + unset($this->Reporter); + } + +/** + * testAssertGoodTags + * + * @return void + */ + public function testAssertTagsQuotes() { + $test = new AssertTagsTestCase('testAssertTagsQuotes'); + $result = $test->run(); + $this->assertEquals(0, $result->errorCount()); + $this->assertTrue($result->wasSuccessful()); + $this->assertEquals(0, $result->failureCount()); + + $input = 'My link'; + $pattern = array( + 'a' => array('href' => '/test.html', 'class' => 'active'), + 'My link', + '/a' + ); + $this->assertTrue($test->assertTags($input, $pattern), 'Double quoted attributes %s'); + + $input = "My link"; + $pattern = array( + 'a' => array('href' => '/test.html', 'class' => 'active'), + 'My link', + '/a' + ); + $this->assertTrue($test->assertTags($input, $pattern), 'Single quoted attributes %s'); + + $input = "My link"; + $pattern = array( + 'a' => array('href' => 'preg:/.*\.html/', 'class' => 'active'), + 'My link', + '/a' + ); + $this->assertTrue($test->assertTags($input, $pattern), 'Single quoted attributes %s'); + + $input = "Text"; + $pattern = array( + 'assertTrue($test->assertTags($input, $pattern), 'Tags with no attributes'); + + $input = "Text"; + $pattern = array( + 'span' => array('class'), + 'assertTrue($test->assertTags($input, $pattern), 'Test attribute presence'); + } + +/** + * testNumericValuesInExpectationForAssertTags + * + * @return void + */ + public function testNumericValuesInExpectationForAssertTags() { + $test = new AssertTagsTestCase('testNumericValuesInExpectationForAssertTags'); + $result = $test->run(); + $this->assertEquals(0, $result->errorCount()); + $this->assertTrue($result->wasSuccessful()); + $this->assertEquals(0, $result->failureCount()); + } + +/** + * testBadAssertTags + * + * @return void + */ + public function testBadAssertTags() { + $test = new AssertTagsTestCase('testBadAssertTags'); + $result = $test->run(); + $this->assertEquals(0, $result->errorCount()); + $this->assertFalse($result->wasSuccessful()); + $this->assertEquals(1, $result->failureCount()); + + $test = new AssertTagsTestCase('testBadAssertTags2'); + $result = $test->run(); + $this->assertEquals(0, $result->errorCount()); + $this->assertFalse($result->wasSuccessful()); + $this->assertEquals(1, $result->failureCount()); + } + +/** + * testLoadFixtures + * + * @return void + */ + public function testLoadFixtures() { + $test = new FixturizedTestCase('testFixturePresent'); + $manager = $this->getMock('CakeFixtureManager'); + $manager->fixturize($test); + $test->fixtureManager = $manager; + $manager->expects($this->once())->method('load'); + $manager->expects($this->once())->method('unload'); + $result = $test->run(); + $this->assertEquals(0, $result->errorCount()); + $this->assertTrue($result->wasSuccessful()); + $this->assertEquals(0, $result->failureCount()); + } + +/** + * testLoadFixturesOnDemand + * + * @return void + */ + public function testLoadFixturesOnDemand() { + $test = new FixturizedTestCase('testFixtureLoadOnDemand'); + $test->autoFixtures = false; + $manager = $this->getMock('CakeFixtureManager'); + $manager->fixturize($test); + $test->fixtureManager = $manager; + $manager->expects($this->once())->method('loadSingle'); + $result = $test->run(); + $this->assertEquals(0, $result->errorCount()); + } + +/** + * testLoadFixturesOnDemand + * + * @return void + */ + public function testUnoadFixturesAfterFailure() { + $test = new FixturizedTestCase('testFixtureLoadOnDemand'); + $test->autoFixtures = false; + $manager = $this->getMock('CakeFixtureManager'); + $manager->fixturize($test); + $test->fixtureManager = $manager; + $manager->expects($this->once())->method('loadSingle'); + $result = $test->run(); + $this->assertEquals(0, $result->errorCount()); + } + +/** + * testThrowException + * + * @return void + */ + public function testThrowException() { + $test = new FixturizedTestCase('testThrowException'); + $test->autoFixtures = false; + $manager = $this->getMock('CakeFixtureManager'); + $manager->fixturize($test); + $test->fixtureManager = $manager; + $manager->expects($this->once())->method('unload'); + $result = $test->run(); + $this->assertEquals(1, $result->errorCount()); + } + +/** + * testSkipIf + * + * @return void + */ + public function testSkipIf() { + $test = new FixturizedTestCase('testSkipIfTrue'); + $result = $test->run(); + $this->assertEquals(1, $result->skippedCount()); + + $test = new FixturizedTestCase('testSkipIfFalse'); + $result = $test->run(); + $this->assertEquals(0, $result->skippedCount()); + } + +/** + * Test that CakeTestCase::setUp() backs up values. + * + * @return void + */ + public function testSetupBackUpValues() { + $this->assertArrayHasKey('debug', $this->_configure); + $this->assertArrayHasKey('Plugin', $this->_pathRestore); + } + +/** + * test assertTextNotEquals() + * + * @return void + */ + public function testAssertTextNotEquals() { + $one = "\r\nOne\rTwooo"; + $two = "\nOne\nTwo"; + $this->assertTextNotEquals($one, $two); + } + +/** + * test assertTextEquals() + * + * @return void + */ + public function testAssertTextEquals() { + $one = "\r\nOne\rTwo"; + $two = "\nOne\nTwo"; + $this->assertTextEquals($one, $two); + } + +/** + * test assertTextStartsWith() + * + * @return void + */ + public function testAssertTextStartsWith() { + $stringDirty = "some\nstring\r\nwith\rdifferent\nline endings!"; + $stringClean = "some\nstring\nwith\ndifferent\nline endings!"; + + $this->assertStringStartsWith("some\nstring", $stringDirty); + $this->assertStringStartsNotWith("some\r\nstring\r\nwith", $stringDirty); + $this->assertStringStartsNotWith("some\nstring\nwith", $stringDirty); + + $this->assertTextStartsWith("some\nstring\nwith", $stringDirty); + $this->assertTextStartsWith("some\r\nstring\r\nwith", $stringDirty); + } + +/** + * test assertTextStartsNotWith() + * + * @return void + */ + public function testAssertTextStartsNotWith() { + $stringDirty = "some\nstring\r\nwith\rdifferent\nline endings!"; + $stringClean = "some\nstring\nwith\ndifferent\nline endings!"; + + $this->assertTextStartsNotWith("some\nstring\nwithout", $stringDirty); + } + +/** + * test assertTextEndsWith() + * + * @return void + */ + public function testAssertTextEndsWith() { + $stringDirty = "some\nstring\r\nwith\rdifferent\nline endings!"; + $stringClean = "some\nstring\nwith\ndifferent\nline endings!"; + + $this->assertTextEndsWith("string\nwith\r\ndifferent\rline endings!", $stringDirty); + $this->assertTextEndsWith("string\r\nwith\ndifferent\nline endings!", $stringDirty); + } + +/** + * test assertTextEndsNotWith() + * + * @return void + */ + public function testAssertTextEndsNotWith() { + $stringDirty = "some\nstring\r\nwith\rdifferent\nline endings!"; + $stringClean = "some\nstring\nwith\ndifferent\nline endings!"; + + $this->assertStringEndsNotWith("different\nline endings", $stringDirty); + $this->assertTextEndsNotWith("different\rline endings", $stringDirty); + } + +/** + * test assertTextContains() + * + * @return void + */ + public function testAssertTextContains() { + $stringDirty = "some\nstring\r\nwith\rdifferent\nline endings!"; + $stringClean = "some\nstring\nwith\ndifferent\nline endings!"; + + $this->assertContains("different", $stringDirty); + $this->assertNotContains("different\rline", $stringDirty); + + $this->assertTextContains("different\rline", $stringDirty); + } + +/** + * test assertTextNotContains() + * + * @return void + */ + public function testAssertTextNotContains() { + $stringDirty = "some\nstring\r\nwith\rdifferent\nline endings!"; + $stringClean = "some\nstring\nwith\ndifferent\nline endings!"; + + $this->assertTextNotContains("different\rlines", $stringDirty); + } + +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/TestSuite/CakeTestFixtureTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/TestSuite/CakeTestFixtureTest.php new file mode 100644 index 0000000..5565548 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/TestSuite/CakeTestFixtureTest.php @@ -0,0 +1,499 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.TestSuite + * @since CakePHP(tm) v 1.2.0.4667 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ +App::uses('DboSource', 'Model/Datasource'); +App::uses('Model', 'Model'); +App::uses('CakeTestFixture', 'TestSuite/Fixture'); + +/** + * CakeTestFixtureTestFixture class + * + * @package Cake.Test.Case.TestSuite + */ +class CakeTestFixtureTestFixture extends CakeTestFixture { + +/** + * Name property + * + * @var string + */ + public $name = 'FixtureTest'; + +/** + * Table property + * + * @var string + */ + public $table = 'fixture_tests'; + +/** + * Fields array + * + * @var array + */ + public $fields = array( + 'id' => array('type' => 'integer', 'key' => 'primary'), + 'name' => array('type' => 'string', 'length' => '255'), + 'created' => array('type' => 'datetime') + ); + +/** + * Records property + * + * @var array + */ + public $records = array( + array('name' => 'Gandalf', 'created' => '2009-04-28 19:20:00'), + array('name' => 'Captain Picard', 'created' => '2009-04-28 19:20:00'), + array('name' => 'Chewbacca', 'created' => '2009-04-28 19:20:00') + ); +} + +/** + * StringFieldsTestFixture class + * + * @package Cake.Test.Case.TestSuite + * @subpackage cake.cake.tests.cases.libs + */ +class StringsTestFixture extends CakeTestFixture { + +/** + * Name property + * + * @var string + */ + public $name = 'Strings'; + +/** + * Table property + * + * @var string + */ + public $table = 'strings'; + +/** + * Fields array + * + * @var array + */ + public $fields = array( + 'id' => array('type' => 'integer', 'key' => 'primary'), + 'name' => array('type' => 'string', 'length' => '255'), + 'email' => array('type' => 'string', 'length' => '255'), + 'age' => array('type' => 'integer', 'default' => 10) + ); + +/** + * Records property + * + * @var array + */ + public $records = array( + array('name' => 'Mark Doe', 'email' => 'mark.doe@email.com'), + array('name' => 'John Doe', 'email' => 'john.doe@email.com', 'age' => 20), + array('email' => 'jane.doe@email.com', 'name' => 'Jane Doe', 'age' => 30) + ); +} + + +/** + * CakeTestFixtureImportFixture class + * + * @package Cake.Test.Case.TestSuite + */ +class CakeTestFixtureImportFixture extends CakeTestFixture { + +/** + * Name property + * + * @var string + */ + public $name = 'ImportFixture'; + +/** + * Import property + * + * @var mixed + */ + public $import = array('table' => 'fixture_tests', 'connection' => 'fixture_test_suite'); +} + +/** + * CakeTestFixtureDefaultImportFixture class + * + * @package Cake.Test.Case.TestSuite + */ +class CakeTestFixtureDefaultImportFixture extends CakeTestFixture { + +/** + * Name property + * + * @var string + */ + public $name = 'ImportFixture'; +} + +/** + * FixtureImportTestModel class + * + * @package Cake.Test.Case.TestSuite + * @package Cake.Test.Case.TestSuite + */ +class FixtureImportTestModel extends Model { + + public $name = 'FixtureImport'; + + public $useTable = 'fixture_tests'; + + public $useDbConfig = 'test'; + +} + +class FixturePrefixTest extends Model { + + public $name = 'FixturePrefix'; + + public $useTable = '_tests'; + + public $tablePrefix = 'fixture'; + + public $useDbConfig = 'test'; +} + + +/** + * Test case for CakeTestFixture + * + * @package Cake.Test.Case.TestSuite + */ +class CakeTestFixtureTest extends CakeTestCase { + +/** + * setUp method + * + * @return void + */ + public function setUp() { + $methods = array_diff(get_class_methods('DboSource'), array('enabled')); + $methods[] = 'connect'; + + $this->criticDb = $this->getMock('DboSource', $methods); + $this->criticDb->fullDebug = true; + $this->db = ConnectionManager::getDataSource('test'); + $this->_backupConfig = $this->db->config; + } + +/** + * tearDown + * + * @return void + */ + public function tearDown() { + unset($this->criticDb); + $this->db->config = $this->_backupConfig; + } + +/** + * testInit + * + * @return void + */ + public function testInit() { + $Fixture = new CakeTestFixtureTestFixture(); + unset($Fixture->table); + $Fixture->init(); + $this->assertEquals('fixture_tests', $Fixture->table); + $this->assertEquals('id', $Fixture->primaryKey); + + $Fixture = new CakeTestFixtureTestFixture(); + $Fixture->primaryKey = 'my_random_key'; + $Fixture->init(); + $this->assertEquals('my_random_key', $Fixture->primaryKey); + } + +/** + * test that init() correctly sets the fixture table when the connection + * or model have prefixes defined. + * + * @return void + */ + public function testInitDbPrefix() { + $this->skipIf($this->db instanceof Sqlite, 'Cannot open 2 connections to Sqlite'); + $db = ConnectionManager::getDataSource('test'); + $Source = new CakeTestFixtureTestFixture(); + $Source->drop($db); + $Source->create($db); + $Source->insert($db); + + $Fixture = new CakeTestFixtureTestFixture(); + $expected = array('id', 'name', 'created'); + $this->assertEquals($expected, array_keys($Fixture->fields)); + + $config = $db->config; + $config['prefix'] = 'fixture_test_suite_'; + ConnectionManager::create('fixture_test_suite', $config); + + $Fixture->fields = $Fixture->records = null; + $Fixture->import = array('table' => 'fixture_tests', 'connection' => 'test', 'records' => true); + $Fixture->init(); + $this->assertEquals(count($Fixture->records), count($Source->records)); + $Fixture->create(ConnectionManager::getDataSource('fixture_test_suite')); + + $Fixture = new CakeTestFixtureImportFixture(); + $Fixture->fields = $Fixture->records = $Fixture->table = null; + $Fixture->import = array('model' => 'FixtureImportTestModel', 'connection' => 'test'); + $Fixture->init(); + $this->assertEquals(array('id', 'name', 'created'), array_keys($Fixture->fields)); + $this->assertEquals('fixture_tests', $Fixture->table); + + $keys = array_flip(ClassRegistry::keys()); + $this->assertFalse(array_key_exists('fixtureimporttestmodel', $keys)); + + $Fixture->drop(ConnectionManager::getDataSource('fixture_test_suite')); + $Source->drop($db); + } + +/** + * test that fixtures don't duplicate the test db prefix. + * + * @return void + */ + public function testInitDbPrefixDuplication() { + $this->skipIf($this->db instanceof Sqlite, 'Cannot open 2 connections to Sqlite'); + $db = ConnectionManager::getDataSource('test'); + $backPrefix = $db->config['prefix']; + $db->config['prefix'] = 'cake_fixture_test_'; + ConnectionManager::create('fixture_test_suite', $db->config); + $newDb = ConnectionManager::getDataSource('fixture_test_suite'); + $newDb->config['prefix'] = 'cake_fixture_test_'; + + $Source = new CakeTestFixtureTestFixture(); + $Source->create($db); + $Source->insert($db); + + $Fixture = new CakeTestFixtureImportFixture(); + $Fixture->fields = $Fixture->records = $Fixture->table = null; + $Fixture->import = array('model' => 'FixtureImportTestModel', 'connection' => 'test'); + + $Fixture->init(); + $this->assertEquals(array('id', 'name', 'created'), array_keys($Fixture->fields)); + $this->assertEquals('fixture_tests', $Fixture->table); + + $Source->drop($db); + $db->config['prefix'] = $backPrefix; + } + +/** + * test init with a model that has a tablePrefix declared. + * + * @return void + */ + public function testInitModelTablePrefix() { + $this->skipIf($this->db instanceof Sqlite, 'Cannot open 2 connections to Sqlite'); + $this->skipIf(!empty($this->db->config['prefix']), 'Cannot run this test, you have a database connection prefix.'); + + $Source = new CakeTestFixtureTestFixture(); + $Source->create($this->db); + $Source->insert($this->db); + + $Fixture = new CakeTestFixtureTestFixture(); + unset($Fixture->table); + $Fixture->fields = $Fixture->records = null; + $Fixture->import = array('model' => 'FixturePrefixTest', 'connection' => 'test', 'records' => false); + $Fixture->init(); + $this->assertEquals('fixture_tests', $Fixture->table); + + $keys = array_flip(ClassRegistry::keys()); + $this->assertFalse(array_key_exists('fixtureimporttestmodel', $keys)); + + $Source->drop($this->db); + } + +/** + * testImport + * + * @return void + */ + public function testImport() { + $testSuiteDb = ConnectionManager::getDataSource('test'); + $testSuiteConfig = $testSuiteDb->config; + ConnectionManager::create('new_test_suite', array_merge($testSuiteConfig, array('prefix' => 'new_' . $testSuiteConfig['prefix']))); + $newTestSuiteDb = ConnectionManager::getDataSource('new_test_suite'); + + $Source = new CakeTestFixtureTestFixture(); + $Source->create($newTestSuiteDb); + $Source->insert($newTestSuiteDb); + + $Fixture = new CakeTestFixtureDefaultImportFixture(); + $Fixture->fields = $Fixture->records = null; + $Fixture->import = array('model' => 'FixtureImportTestModel', 'connection' => 'new_test_suite'); + $Fixture->init(); + $this->assertEquals(array('id', 'name', 'created'), array_keys($Fixture->fields)); + + $keys = array_flip(ClassRegistry::keys()); + $this->assertFalse(array_key_exists('fixtureimporttestmodel', $keys)); + + $Source->drop($newTestSuiteDb); + } + +/** + * test that importing with records works. Make sure to try with postgres as its + * handling of aliases is a workaround at best. + * + * @return void + */ + public function testImportWithRecords() { + $testSuiteDb = ConnectionManager::getDataSource('test'); + $testSuiteConfig = $testSuiteDb->config; + ConnectionManager::create('new_test_suite', array_merge($testSuiteConfig, array('prefix' => 'new_' . $testSuiteConfig['prefix']))); + $newTestSuiteDb = ConnectionManager::getDataSource('new_test_suite'); + + $Source = new CakeTestFixtureTestFixture(); + $Source->create($newTestSuiteDb); + $Source->insert($newTestSuiteDb); + + $Fixture = new CakeTestFixtureDefaultImportFixture(); + $Fixture->fields = $Fixture->records = null; + $Fixture->import = array( + 'model' => 'FixtureImportTestModel', 'connection' => 'new_test_suite', 'records' => true + ); + $Fixture->init(); + $this->assertEquals(array('id', 'name', 'created'), array_keys($Fixture->fields)); + $this->assertFalse(empty($Fixture->records[0]), 'No records loaded on importing fixture.'); + $this->assertTrue(isset($Fixture->records[0]['name']), 'No name loaded for first record'); + + $Source->drop($newTestSuiteDb); + } + +/** + * test create method + * + * @return void + */ + public function testCreate() { + $Fixture = new CakeTestFixtureTestFixture(); + $this->criticDb->expects($this->atLeastOnce())->method('execute'); + $this->criticDb->expects($this->atLeastOnce())->method('createSchema'); + $return = $Fixture->create($this->criticDb); + $this->assertTrue($this->criticDb->fullDebug); + $this->assertTrue($return); + + unset($Fixture->fields); + $return = $Fixture->create($this->criticDb); + $this->assertFalse($return); + } + +/** + * test the insert method + * + * @return void + */ + public function testInsert() { + $Fixture = new CakeTestFixtureTestFixture(); + $this->criticDb->expects($this->atLeastOnce()) + ->method('insertMulti') + ->will($this->returnCallback(array($this, 'insertCallback'))); + + $return = $Fixture->insert($this->criticDb); + $this->assertTrue(!empty($this->insertMulti)); + $this->assertTrue($this->criticDb->fullDebug); + $this->assertTrue($return); + $this->assertEquals('fixture_tests', $this->insertMulti['table']); + $this->assertEquals(array('name', 'created'), $this->insertMulti['fields']); + $expected = array( + array('Gandalf', '2009-04-28 19:20:00'), + array('Captain Picard', '2009-04-28 19:20:00'), + array('Chewbacca', '2009-04-28 19:20:00') + ); + $this->assertEquals($expected, $this->insertMulti['values']); + } + +/** + * Helper function to be used as callback and store the parameters of an insertMulti call + * + * @param string $table + * @param string $fields + * @param string $values + * @return boolean true + */ + public function insertCallback($table, $fields, $values) { + $this->insertMulti['table'] = $table; + $this->insertMulti['fields'] = $fields; + $this->insertMulti['values'] = $values; + return true; + } + +/** + * test the insert method + * + * @return void + */ + public function testInsertStrings() { + $Fixture = new StringsTestFixture(); + $this->criticDb->expects($this->atLeastOnce()) + ->method('insertMulti') + ->will($this->returnCallback(array($this, 'insertCallback'))); + + $return = $Fixture->insert($this->criticDb); + $this->assertTrue($this->criticDb->fullDebug); + $this->assertTrue($return); + $this->assertEquals('strings', $this->insertMulti['table']); + $this->assertEquals(array('email', 'name', 'age'), $this->insertMulti['fields']); + $expected = array( + array('Mark Doe', 'mark.doe@email.com', null), + array('John Doe', 'john.doe@email.com', 20), + array('Jane Doe', 'jane.doe@email.com', 30), + ); + $this->assertEquals($expected, $this->insertMulti['values']); + } + +/** + * Test the drop method + * + * @return void + */ + public function testDrop() { + $Fixture = new CakeTestFixtureTestFixture(); + $this->criticDb->expects($this->at(1))->method('execute')->will($this->returnValue(true)); + $this->criticDb->expects($this->at(3))->method('execute')->will($this->returnValue(false)); + $this->criticDb->expects($this->exactly(2))->method('dropSchema'); + + $return = $Fixture->drop($this->criticDb); + $this->assertTrue($this->criticDb->fullDebug); + $this->assertTrue($return); + + $return = $Fixture->drop($this->criticDb); + $this->assertTrue($return); + + unset($Fixture->fields); + $return = $Fixture->drop($this->criticDb); + $this->assertFalse($return); + } + +/** + * Test the truncate method. + * + * @return void + */ + public function testTruncate() { + $Fixture = new CakeTestFixtureTestFixture(); + $this->criticDb->expects($this->atLeastOnce())->method('truncate'); + $Fixture->truncate($this->criticDb); + $this->assertTrue($this->criticDb->fullDebug); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/TestSuite/CakeTestSuiteTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/TestSuite/CakeTestSuiteTest.php new file mode 100644 index 0000000..a30fd5a --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/TestSuite/CakeTestSuiteTest.php @@ -0,0 +1,104 @@ +getMock('CakeTestSuite', array('addTestFile')); + $suite + ->expects($this->exactly($count)) + ->method('addTestFile'); + + $suite->addTestDirectory($testFolder); + } + +/** + * testAddTestDirectoryRecursive + * + * @return void + */ + public function testAddTestDirectoryRecursive() { + $testFolder = CORE_TEST_CASES . DS . 'Cache'; + $count = count(glob($testFolder . DS . '*Test.php')); + $count += count(glob($testFolder . DS . 'Engine' . DS . '*Test.php')); + + $suite = $this->getMock('CakeTestSuite', array('addTestFile')); + $suite + ->expects($this->exactly($count)) + ->method('addTestFile'); + + $suite->addTestDirectoryRecursive($testFolder); + } + +/** + * testAddTestDirectoryRecursiveWithHidden + * + * @return void + */ + public function testAddTestDirectoryRecursiveWithHidden() { + $this->skipIf(!is_writeable(TMP), 'Cant addTestDirectoryRecursiveWithHidden unless the tmp folder is writable.'); + + $Folder = new Folder(TMP . 'MyTestFolder', true, 0777); + mkdir($Folder->path . DS . '.svn', 0777, true); + touch($Folder->path . DS . '.svn' . DS . 'InHiddenFolderTest.php'); + touch($Folder->path . DS . 'NotHiddenTest.php'); + touch($Folder->path . DS . '.HiddenTest.php'); + + $suite = $this->getMock('CakeTestSuite', array('addTestFile')); + $suite + ->expects($this->exactly(1)) + ->method('addTestFile'); + + $suite->addTestDirectoryRecursive($Folder->pwd()); + + $Folder->delete(); + } + +/** + * testAddTestDirectoryRecursiveWithNonPhp + * + * @return void + */ + public function testAddTestDirectoryRecursiveWithNonPhp() { + $this->skipIf(!is_writeable(TMP), 'Cant addTestDirectoryRecursiveWithNonPhp unless the tmp folder is writable.'); + + $Folder = new Folder(TMP . 'MyTestFolder', true, 0777); + touch($Folder->path . DS . 'BackupTest.php~'); + touch($Folder->path . DS . 'SomeNotesTest.txt'); + touch($Folder->path . DS . 'NotHiddenTest.php'); + + $suite = $this->getMock('CakeTestSuite', array('addTestFile')); + $suite + ->expects($this->exactly(1)) + ->method('addTestFile'); + + $suite->addTestDirectoryRecursive($Folder->pwd()); + + $Folder->delete(); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/TestSuite/ControllerTestCaseTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/TestSuite/ControllerTestCaseTest.php new file mode 100644 index 0000000..cf6bbb8 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/TestSuite/ControllerTestCaseTest.php @@ -0,0 +1,564 @@ + array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS), + 'Controller' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Controller' . DS), + 'Model' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Model' . DS), + 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS) + ), App::RESET); + CakePlugin::load(array('TestPlugin', 'TestPluginTwo')); + $this->Case = $this->getMockForAbstractClass('ControllerTestCase'); + Router::reload(); + } + +/** + * tearDown + * + * @return void + */ + public function tearDown() { + parent::tearDown(); + CakePlugin::unload(); + $this->Case->controller = null; + } + +/** + * Test that ControllerTestCase::generate() creates mock objects correctly + */ + public function testGenerate() { + if (defined('APP_CONTROLLER_EXISTS')) { + $this->markTestSkipped('AppController exists, cannot run.'); + } + $Posts = $this->Case->generate('Posts'); + $this->assertEquals('Posts', $Posts->name); + $this->assertEquals('Post', $Posts->modelClass); + $this->assertNull($Posts->response->send()); + + $Posts = $this->Case->generate('Posts', array( + 'methods' => array( + 'render' + ) + )); + $this->assertNull($Posts->render('index')); + + $Posts = $this->Case->generate('Posts', array( + 'models' => array('Post'), + 'components' => array('RequestHandler') + )); + + $this->assertInstanceOf('Post', $Posts->Post); + $this->assertNull($Posts->Post->save(array())); + $this->assertNull($Posts->Post->find('all')); + $this->assertEquals('posts', $Posts->Post->useTable); + $this->assertNull($Posts->RequestHandler->isAjax()); + + $Posts = $this->Case->generate('Posts', array( + 'models' => array( + 'Post' => true + ) + )); + $this->assertNull($Posts->Post->save(array())); + $this->assertNull($Posts->Post->find('all')); + + $Posts = $this->Case->generate('Posts', array( + 'models' => array( + 'Post' => array('save'), + ) + )); + $this->assertNull($Posts->Post->save(array())); + $this->assertInternalType('array', $Posts->Post->find('all')); + + $Posts = $this->Case->generate('Posts', array( + 'models' => array('Post'), + 'components' => array( + 'RequestHandler' => array('isPut'), + 'Email' => array('send'), + 'Session' + ) + )); + $Posts->RequestHandler->expects($this->once()) + ->method('isPut') + ->will($this->returnValue(true)); + $this->assertTrue($Posts->RequestHandler->isPut()); + + $Posts->Auth->Session->expects($this->any()) + ->method('write') + ->will($this->returnValue('written!')); + $this->assertEquals('written!', $Posts->Auth->Session->write('something')); + } + +/** + * Tests ControllerTestCase::generate() using classes from plugins + */ + public function testGenerateWithPlugin() { + $Tests = $this->Case->generate('TestPlugin.Tests', array( + 'models' => array( + 'TestPlugin.TestPluginComment' + ), + 'components' => array( + 'TestPlugin.Plugins' + ) + )); + $this->assertEquals('Tests', $Tests->name); + $this->assertInstanceOf('PluginsComponent', $Tests->Plugins); + + $result = ClassRegistry::init('TestPlugin.TestPluginComment'); + $this->assertInstanceOf('TestPluginComment', $result); + + $Tests = $this->Case->generate('ControllerTestCaseTest', array( + 'models' => array( + 'TestPlugin.TestPluginComment' => array('save') + ) + )); + $this->assertInstanceOf('TestPluginComment', $Tests->TestPluginComment); + $Tests->TestPluginComment->expects($this->at(0)) + ->method('save') + ->will($this->returnValue(true)); + $Tests->TestPluginComment->expects($this->at(1)) + ->method('save') + ->will($this->returnValue(false)); + $this->assertTrue($Tests->TestPluginComment->save(array())); + $this->assertFalse($Tests->TestPluginComment->save(array())); + } + +/** + * Tests testAction + */ + public function testTestAction() { + $Controller = $this->Case->generate('TestsApps'); + $this->Case->testAction('/tests_apps/index'); + $this->assertInternalType('array', $this->Case->controller->viewVars); + + $this->Case->testAction('/tests_apps/set_action'); + $results = $this->Case->controller->viewVars; + $expected = array( + 'var' => 'string' + ); + $this->assertEquals($expected, $results); + + $result = $this->Case->controller->response->body(); + $this->assertRegExp('/This is the TestsAppsController index view/', $result); + + $Controller = $this->Case->generate('TestsApps'); + $this->Case->testAction('/tests_apps/redirect_to'); + $results = $this->Case->headers; + $expected = array( + 'Location' => 'http://cakephp.org' + ); + $this->assertEquals($expected, $results); + } + +/** + * Make sure testAction() can hit plugin controllers. + * + * @return void + */ + public function testTestActionWithPlugin() { + $Controller = $this->Case->generate('TestPlugin.Tests'); + $this->Case->testAction('/test_plugin/tests/index'); + $this->assertEquals('It is a variable', $this->Case->controller->viewVars['test_value']); + } + +/** + * Tests using loaded routes during tests + * + * @return void + */ + public function testUseRoutes() { + Router::connect('/:controller/:action/*'); + include CAKE . 'Test' . DS . 'test_app' . DS . 'Config' . DS . 'routes.php'; + + $controller = $this->Case->generate('TestsApps'); + $controller->Components->load('RequestHandler'); + $result = $this->Case->testAction('/tests_apps/index.json', array('return' => 'contents')); + $result = json_decode($result, true); + $expected = array('cakephp' => 'cool'); + $this->assertEquals($expected, $result); + + include CAKE . 'Test' . DS . 'test_app' . DS . 'Config' . DS . 'routes.php'; + $result = $this->Case->testAction('/some_alias'); + $this->assertEquals(5, $result); + } + +/** + * Tests not using loaded routes during tests + * + * @expectedException MissingActionException + */ + public function testSkipRoutes() { + Router::connect('/:controller/:action/*'); + include CAKE . 'Test' . DS . 'test_app' . DS . 'Config' . DS . 'routes.php'; + + $this->Case->loadRoutes = false; + $result = $this->Case->testAction('/tests_apps/missing_action.json', array('return' => 'view')); + } + +/** + * Tests backwards compatibility with setting the return type + */ + public function testBCSetReturn() { + $this->Case->autoMock = true; + + $result = $this->Case->testAction('/tests_apps/some_method'); + $this->assertEquals(5, $result); + + $data = array('var' => 'set'); + $result = $this->Case->testAction('/tests_apps_posts/post_var', array( + 'data' => $data, + 'return' => 'vars' + )); + $this->assertEquals($data, $result['data']); + + $result = $this->Case->testAction('/tests_apps/set_action', array( + 'return' => 'view' + )); + $this->assertEquals('This is the TestsAppsController index view string', $result); + + $result = $this->Case->testAction('/tests_apps/set_action', array( + 'return' => 'contents' + )); + $this->assertRegExp('/assertRegExp('/This is the TestsAppsController index view/', $result); + $this->assertRegExp('/<\/html>/', $result); + } + +/** + * Tests sending POST data to testAction + */ + public function testTestActionPostData() { + $this->Case->autoMock = true; + + $data = array( + 'Post' => array( + 'name' => 'Some Post' + ) + ); + $this->Case->testAction('/tests_apps_posts/post_var', array( + 'data' => $data + )); + $this->assertEquals($this->Case->controller->viewVars['data'], $data); + $this->assertEquals($this->Case->controller->data, $data); + + $this->Case->testAction('/tests_apps_posts/post_var/named:param', array( + 'data' => $data + )); + $expected = array( + 'named' => 'param' + ); + $this->assertEquals($expected, $this->Case->controller->request->named); + $this->assertEquals($this->Case->controller->data, $data); + + $result = $this->Case->testAction('/tests_apps_posts/post_var', array( + 'return' => 'vars', + 'method' => 'post', + 'data' => array( + 'name' => 'is jonas', + 'pork' => 'and beans', + ) + )); + $this->assertEquals(array('name', 'pork'), array_keys($result['data'])); + + $result = $this->Case->testAction('/tests_apps_posts/add', array('return' => 'vars')); + $this->assertTrue(array_key_exists('posts', $result)); + $this->assertEquals(4, count($result['posts'])); + $this->assertTrue($this->Case->controller->request->is('post')); + } + +/** + * Tests sending GET data to testAction + */ + public function testTestActionGetData() { + $this->Case->autoMock = true; + + $result = $this->Case->testAction('/tests_apps_posts/url_var', array( + 'method' => 'get', + 'data' => array( + 'some' => 'var', + 'lackof' => 'creativity' + ) + )); + $this->assertEquals('var', $this->Case->controller->request->query['some']); + $this->assertEquals('creativity', $this->Case->controller->request->query['lackof']); + + $result = $this->Case->testAction('/tests_apps_posts/url_var/var1:value1/var2:val2', array( + 'return' => 'vars', + 'method' => 'get', + )); + $this->assertEquals(array('var1', 'var2'), array_keys($result['params']['named'])); + + $result = $this->Case->testAction('/tests_apps_posts/url_var/gogo/val2', array( + 'return' => 'vars', + 'method' => 'get', + )); + $this->assertEquals(array('gogo', 'val2'), $result['params']['pass']); + + $result = $this->Case->testAction('/tests_apps_posts/url_var', array( + 'return' => 'vars', + 'method' => 'get', + 'data' => array( + 'red' => 'health', + 'blue' => 'mana' + ) + )); + $query = $this->Case->controller->request->query; + $this->assertTrue(isset($query['red'])); + $this->assertTrue(isset($query['blue'])); + } + +/** + * Test that REST actions with XML/JSON input work. + * + * @return void + */ + public function testTestActionJsonData() { + $result = $this->Case->testAction('/tests_apps_posts/input_data', array( + 'return' => 'vars', + 'method' => 'post', + 'data' => '{"key":"value","json":true}' + )); + $this->assertEquals('value', $result['data']['key']); + $this->assertTrue($result['data']['json']); + } + +/** + * Tests autoMock ability + */ + public function testAutoMock() { + $this->Case->autoMock = true; + $this->Case->testAction('/tests_apps/set_action'); + $results = $this->Case->controller->viewVars; + $expected = array( + 'var' => 'string' + ); + $this->assertEquals($expected, $results); + } + +/** + * Test using testAction and not mocking + */ + public function testNoMocking() { + $result = $this->Case->testAction('/tests_apps/some_method'); + $this->Case->assertEquals(5, $result); + + $data = array('var' => 'set'); + $result = $this->Case->testAction('/tests_apps_posts/post_var', array( + 'data' => $data, + 'return' => 'vars' + )); + $this->assertEquals($data, $result['data']); + + $result = $this->Case->testAction('/tests_apps/set_action', array( + 'return' => 'view' + )); + $this->assertEquals('This is the TestsAppsController index view string', $result); + + $result = $this->Case->testAction('/tests_apps/set_action', array( + 'return' => 'contents' + )); + $this->assertRegExp('/assertRegExp('/This is the TestsAppsController index view/', $result); + $this->assertRegExp('/<\/html>/', $result); + } + +/** + * Test that controllers don't get reused. + * + * @return void + */ + public function testNoControllerReuse() { + $this->Case->autoMock = true; + $result = $this->Case->testAction('/tests_apps/index', array( + 'data' => array('var' => 'first call'), + 'method' => 'get', + 'return' => 'contents', + )); + $this->assertContains('assertContains('This is the TestsAppsController index view', $result); + $this->assertContains('first call', $result); + $this->assertContains('', $result); + + $result = $this->Case->testAction('/tests_apps/index', array( + 'data' => array('var' => 'second call'), + 'method' => 'get', + 'return' => 'contents' + )); + $this->assertContains('second call', $result); + + $result = $this->Case->testAction('/tests_apps/index', array( + 'data' => array('var' => 'third call'), + 'method' => 'get', + 'return' => 'contents' + )); + $this->assertContains('third call', $result); + } + +/** + * Test that multiple calls to redirect in the same test method don't cause issues. + * + * @return void + */ + public function testTestActionWithMultipleRedirect() { + $Controller = $this->Case->generate('TestsApps'); + + $options = array('method' => 'get'); + $this->Case->testAction('/tests_apps/redirect_to', $options); + $this->Case->testAction('/tests_apps/redirect_to', $options); + } + +/** + * Tests that Components storing response or request objects internally during construct + * will always have a fresh reference to those object available + * + * @return void + * @see http://cakephp.lighthouseapp.com/projects/42648-cakephp/tickets/2705-requesthandler-weird-behavior + */ + public function testComponentsSameRequestAndResponse() { + $this->Case->generate('TestsApps'); + $options = array('method' => 'get'); + $this->Case->testAction('/tests_apps/index', $options); + $this->assertSame($this->Case->controller->response, $this->Case->controller->RequestHandler->response); + $this->assertSame($this->Case->controller->request, $this->Case->controller->RequestHandler->request); + } + +/** + * Test that testAction() doesn't destroy data in GET & POST + * + * @return void + */ + public function testRestoreGetPost() { + $restored = array('new' => 'value'); + + $_GET = $restored; + $_POST = $restored; + + $this->Case->generate('TestsApps'); + $options = array('method' => 'get'); + $this->Case->testAction('/tests_apps/index', $options); + + $this->assertEquals($restored, $_GET); + $this->assertEquals($restored, $_POST); + } + +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/TestSuite/HtmlCoverageReportTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/TestSuite/HtmlCoverageReportTest.php new file mode 100644 index 0000000..8a5b7a3 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/TestSuite/HtmlCoverageReportTest.php @@ -0,0 +1,231 @@ + array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS) + ), App::RESET); + CakePlugin::load(array('TestPlugin')); + $reporter = new CakeBaseReporter(); + $reporter->params = array('app' => false, 'plugin' => false, 'group' => false); + $coverage = array(); + $this->Coverage = new HtmlCoverageReport($coverage, $reporter); + } + +/** + * test getting the path filters. + * + * @return void + */ + public function testGetPathFilter() { + $this->Coverage->appTest = false; + $result = $this->Coverage->getPathFilter(); + $this->assertEquals(CAKE, $result); + + $this->Coverage->appTest = true; + $result = $this->Coverage->getPathFilter(); + $this->assertEquals(ROOT . DS . APP_DIR . DS, $result); + + $this->Coverage->appTest = false; + $this->Coverage->pluginTest = 'TestPlugin'; + $result = $this->Coverage->getPathFilter(); + $this->assertEquals(CakePlugin::path('TestPlugin'), $result); + } + +/** + * test filtering coverage data. + * + * @return void + */ + public function testFilterCoverageDataByPathRemovingElements() { + $data = array( + CAKE . 'dispatcher.php' => array( + 10 => -1, + 12 => 1 + ), + APP . 'app_model.php' => array( + 50 => 1, + 52 => -1 + ) + ); + $this->Coverage->setCoverage($data); + $result = $this->Coverage->filterCoverageDataByPath(CAKE); + $this->assertTrue(isset($result[CAKE . 'dispatcher.php'])); + $this->assertFalse(isset($result[APP . 'app_model.php'])); + } + +/** + * test generating HTML reports from file arrays. + * + * @return void + */ + public function testGenerateDiff() { + $file = array( + 'line 1', + 'line 2', + 'line 3', + 'line 4', + 'line 5', + 'line 6', + 'line 7', + 'line 8', + 'line 9', + 'line 10', + ); + $coverage = array( + 1 => array(array('id' => 'HtmlCoverageReportTest::testGenerateDiff')), + 2 => -2, + 3 => array(array('id' => 'HtmlCoverageReportTest::testGenerateDiff')), + 4 => array(array('id' => 'HtmlCoverageReportTest::testGenerateDiff')), + 5 => -1, + 6 => array(array('id' => 'HtmlCoverageReportTest::testGenerateDiff')), + 7 => array(array('id' => 'HtmlCoverageReportTest::testGenerateDiff')), + 8 => array(array('id' => 'HtmlCoverageReportTest::testGenerateDiff')), + 9 => -1, + 10 => array(array('id' => 'HtmlCoverageReportTest::testGenerateDiff')) + ); + $result = $this->Coverage->generateDiff('myfile.php', $file, $coverage); + $this->assertRegExp('/myfile\.php Code coverage\: \d+\.?\d*\%/', $result); + $this->assertRegExp('/
assertRegExp('/
/', $result);
+		foreach ($file as $i => $line) {
+			$this->assertTrue(strpos($line, $result) !== 0, 'Content is missing ' . $i);
+			$class = 'covered';
+			if (in_array($i + 1, array(5, 9, 2))) {
+				$class = 'uncovered';
+			}
+			if ($i + 1 == 2) {
+				$class .= ' dead';
+			}
+			$this->assertTrue(strpos($class, $result) !== 0, 'Class name is wrong ' . $i);
+		}
+	}
+
+/**
+ * Test that coverage works with phpunit 3.6 as the data formats from coverage are totally different.
+ *
+ * @return void
+ */
+	public function testPhpunit36Compatibility() {
+		$file = array(
+			'line 1',
+			'line 2',
+			'line 3',
+			'line 4',
+			'line 5',
+			'line 6',
+			'line 7',
+			'line 8',
+			'line 9',
+			'line 10',
+		);
+		$coverage = array(
+			1 => array('HtmlCoverageReportTest::testGenerateDiff'),
+			2 => null,
+			3 => array('HtmlCoverageReportTest::testGenerateDiff'),
+			4 => array('HtmlCoverageReportTest::testGenerateDiff'),
+			5 => array(),
+			6 => array('HtmlCoverageReportTest::testGenerateDiff'),
+			7 => array('HtmlCoverageReportTest::testGenerateDiff'),
+			8 => array('HtmlCoverageReportTest::testGenerateDiff'),
+			9 => array(),
+			10 => array('HtmlCoverageReportTest::testSomething', 'HtmlCoverageReportTest::testGenerateDiff')
+		);
+
+		$result = $this->Coverage->generateDiff('myfile.php', $file, $coverage);
+		$this->assertRegExp('/myfile\.php Code coverage\: \d+\.?\d*\%/', $result);
+		$this->assertRegExp('/
assertRegExp('/
/', $result);
+		foreach ($file as $i => $line) {
+			$this->assertTrue(strpos($line, $result) !== 0, 'Content is missing ' . $i);
+			$class = 'covered';
+			if (in_array($i + 1, array(5, 9, 2))) {
+				$class = 'uncovered';
+			}
+			if ($i + 1 == 2) {
+				$class .= ' dead';
+			}
+			$this->assertTrue(strpos($class, $result) !== 0, 'Class name is wrong ' . $i);
+		}
+	}
+
+/**
+ * test that covering methods show up as title attributes for lines.
+ *
+ * @return void
+ */
+	public function testCoveredLinesTitleAttributes() {
+		$file = array(
+			'line 1',
+			'line 2',
+			'line 3',
+			'line 4',
+			'line 5',
+		);
+
+		$coverage = array(
+			1 => array(array('id' => 'HtmlCoverageReportTest::testAwesomeness')),
+			2 => -2,
+			3 => array(array('id' => 'HtmlCoverageReportTest::testCakeIsSuperior')),
+			4 => array(array('id' => 'HtmlCoverageReportTest::testOther')),
+			5 => -1
+		);
+
+		$result = $this->Coverage->generateDiff('myfile.php', $file, $coverage);
+
+		$this->assertTrue(
+			strpos($result, "title=\"Covered by:\nHtmlCoverageReportTest::testAwesomeness\n\">1") !== false,
+			'Missing method coverage for line 1'
+		);
+		$this->assertTrue(
+			strpos($result, "title=\"Covered by:\nHtmlCoverageReportTest::testCakeIsSuperior\n\">3") !== false,
+			'Missing method coverage for line 3'
+		);
+		$this->assertTrue(
+			strpos($result, "title=\"Covered by:\nHtmlCoverageReportTest::testOther\n\">4") !== false,
+			'Missing method coverage for line 4'
+		);
+		$this->assertTrue(
+			strpos($result, "title=\"\">5") !== false,
+			'Coverage report is wrong for line 5'
+		);
+	}
+
+/**
+ * tearDown
+ *
+ * @return void
+ */
+	public function tearDown() {
+		CakePlugin::unload();
+		unset($this->Coverage);
+		parent::tearDown();
+	}
+}
diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Utility/CakeNumberTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Utility/CakeNumberTest.php
new file mode 100644
index 0000000..bcae41d
--- /dev/null
+++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Utility/CakeNumberTest.php
@@ -0,0 +1,526 @@
+
+ * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
+ *
+ * Licensed under The MIT License
+ * Redistributions of files must retain the above copyright notice
+ *
+ * @copyright     Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
+ * @link          http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
+ * @package       Cake.Test.Case.View.Helper
+ * @since         CakePHP(tm) v 1.2.0.4206
+ * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
+ */
+
+App::uses('View', 'View');
+App::uses('CakeNumber', 'Utility');
+
+/**
+ * CakeNumberTest class
+ *
+ * @package       Cake.Test.Case.Utility
+ */
+class CakeNumberTest extends CakeTestCase {
+
+/**
+ * setUp method
+ *
+ * @return void
+ */
+	public function setUp() {
+		parent::setUp();
+		$this->Number = new CakeNumber();
+	}
+
+/**
+ * tearDown method
+ *
+ * @return void
+ */
+	public function tearDown() {
+		parent::tearDown();
+		unset($this->Number);
+	}
+
+/**
+ * testFormatAndCurrency method
+ *
+ * @return void
+ */
+	public function testFormat() {
+		$value = '100100100';
+
+		$result = $this->Number->format($value, '#');
+		$expected = '#100,100,100';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->format($value, 3);
+		$expected = '100,100,100.000';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->format($value);
+		$expected = '100,100,100';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->format($value, '-');
+		$expected = '100-100-100';
+		$this->assertEquals($expected, $result);
+	}
+
+/**
+ * testMultibyteFormat
+ *
+ * @return void
+ */
+	public function testMultibyteFormat() {
+		$value = '5199100.0006';
+		$result = $this->Number->format($value, array(
+			'thousands'	=> ' ',
+			'decimals'	=> '&',
+			'places'	=> 3,
+			'escape'	=> false,
+			'before'	=> '',
+		));
+		$expected = '5 199 100&001';
+		$this->assertEquals($expected, $result);
+
+		$value = 1000.45;
+		$result = $this->Number->format($value, array(
+			'thousands'	=> ',,',
+			'decimals'	=> '.a',
+			'escape'	=> false,
+		));
+		$expected = '$1,,000.a45';
+		$this->assertEquals($expected, $result);
+
+		$value = 519919827593784.00;
+		$this->Number->addFormat('RUR', array(
+			'thousands'		=> 'ø€ƒ‡™',
+			'decimals'		=> '(§.§)',
+			'escape'		=> false,
+			'wholeSymbol'	=> '€',
+			'wholePosition'	=> 'after',
+		));
+		$result = $this->Number->currency($value, 'RUR');
+		$expected = '519ø€ƒ‡™919ø€ƒ‡™827ø€ƒ‡™593ø€ƒ‡™784(§.§)00€';
+		$this->assertEquals($expected, $result);
+
+		$value = '13371337.1337';
+		$result = CakeNumber::format($value, array(
+			'thousands'	=> '- |-| /-\ >< () |2 -',
+			'decimals'	=> '- £€€† -',
+			'before'	=> ''
+		));
+		$expected = '13- |-| /-\ >< () |2 -371- |-| /-\ >< () |2 -337- £€€† -13';
+		$this->assertEquals($expected, $result);
+	}
+
+/**
+ * Test currency method.
+ *
+ * @return void
+ */
+	public function testCurrency() {
+		$value = '100100100';
+
+		$result = $this->Number->currency($value);
+		$expected = '$100,100,100.00';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->currency($value, '#');
+		$expected = '#100,100,100.00';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->currency($value, false);
+		$expected = '100,100,100.00';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->currency($value, 'USD');
+		$expected = '$100,100,100.00';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->currency($value, 'EUR');
+		$expected = '€100.100.100,00';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->currency($value, 'GBP');
+		$expected = '£100,100,100.00';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->currency($value, '', array('thousands' => ' ', 'wholeSymbol' => '€', 'wholePosition' => 'after', 'decimals' => ',', 'zero' => 'Gratuit'));
+		$expected = '100 100 100,00€';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->currency(1000.45, null, array('after' => 'øre', 'before' => 'Kr. ', 'decimals' => ',', 'thousands' => '.'));
+		$expected = 'Kr. 1.000,45';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->currency(0.5, 'USD');
+		$expected = '50c';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->currency(0.5, null, array('after' => 'øre'));
+		$expected = '50øre';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->currency(1, null, array('wholeSymbol' => '$ '));
+		$expected = '$ 1.00';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->currency(1, null, array('wholeSymbol' => ' $', 'wholePosition' => 'after'));
+		$expected = '1.00 $';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->currency(0.2, null, array('wholeSymbol' => ' $', 'wholePosition' => 'after', 'fractionSymbol' => 'cents'));
+		$expected = '20cents';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->currency(0.2, null, array('wholeSymbol' => ' $', 'wholePosition' => 'after', 'fractionSymbol' => 'cents', 'fractionPosition' => 'before'));
+		$expected = 'cents20';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->currency(311, 'USD', array('wholePosition' => 'after'));
+		$expected = '311.00$';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->currency(0.2, 'EUR');
+		$expected = '€0,20';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->currency(12, null, array('wholeSymbol' => ' dollars', 'wholePosition' => 'after', 'fractionSymbol' => ' cents', 'fractionPosition' => 'after'));
+		$expected = '12.00 dollars';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->currency(0.12, null, array('wholeSymbol' => ' dollars', 'wholePosition' => 'after', 'fractionSymbol' => ' cents', 'fractionPosition' => 'after'));
+		$expected = '12 cents';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->currency(0.5, null, array('fractionSymbol' => false, 'fractionPosition' => 'before', 'wholeSymbol' => '$'));
+		$expected = '$0.50';
+		$this->assertEquals($expected, $result);
+	}
+
+/**
+ * Test adding currency format options to the number helper
+ *
+ * @return void
+ */
+	public function testCurrencyAddFormat() {
+		$this->Number->addFormat('NOK', array('before' => 'Kr. '));
+		$result = $this->Number->currency(1000, 'NOK');
+		$expected = 'Kr. 1,000.00';
+		$this->assertEquals($expected, $result);
+
+		$this->Number->addFormat('Other', array('before' => '$$ ', 'after' => 'c!'));
+		$result = $this->Number->currency(0.22, 'Other');
+		$expected = '22c!';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->currency(-10, 'Other');
+		$expected = '($$ 10.00)';
+		$this->assertEquals($expected, $result);
+
+		$this->Number->addFormat('Other2', array('before' => '$ ', 'after' => false));
+		$result = $this->Number->currency(0.22, 'Other2');
+		$expected = '$ 0.22';
+		$this->assertEquals($expected, $result);
+	}
+
+/**
+ * testCurrencyPositive method
+ *
+ * @return void
+ */
+	public function testCurrencyPositive() {
+		$value = '100100100';
+
+		$result = $this->Number->currency($value);
+		$expected = '$100,100,100.00';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->currency($value, 'USD', array('before' => '#'));
+		$expected = '#100,100,100.00';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->currency($value, false);
+		$expected = '100,100,100.00';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->currency($value, 'USD');
+		$expected = '$100,100,100.00';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->currency($value, 'EUR');
+		$expected = '€100.100.100,00';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->currency($value, 'GBP');
+		$expected = '£100,100,100.00';
+		$this->assertEquals($expected, $result);
+	}
+
+/**
+ * testCurrencyNegative method
+ *
+ * @return void
+ */
+	public function testCurrencyNegative() {
+		$value = '-100100100';
+
+		$result = $this->Number->currency($value);
+		$expected = '($100,100,100.00)';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->currency($value, 'EUR');
+		$expected = '(€100.100.100,00)';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->currency($value, 'GBP');
+		$expected = '(£100,100,100.00)';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->currency($value, 'USD', array('negative' => '-'));
+		$expected = '-$100,100,100.00';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->currency($value, 'EUR', array('negative' => '-'));
+		$expected = '-€100.100.100,00';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->currency($value, 'GBP', array('negative' => '-'));
+		$expected = '-£100,100,100.00';
+		$this->assertEquals($expected, $result);
+	}
+
+/**
+ * testCurrencyCentsPositive method
+ *
+ * @return void
+ */
+	public function testCurrencyCentsPositive() {
+		$value = '0.99';
+
+		$result = $this->Number->currency($value, 'USD');
+		$expected = '99c';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->currency($value, 'EUR');
+		$expected = '€0,99';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->currency($value, 'GBP');
+		$expected = '99p';
+		$this->assertEquals($expected, $result);
+	}
+
+/**
+ * testCurrencyCentsNegative method
+ *
+ * @return void
+ */
+	public function testCurrencyCentsNegative() {
+		$value = '-0.99';
+
+		$result = $this->Number->currency($value, 'USD');
+		$expected = '(99c)';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->currency($value, 'EUR');
+		$expected = '(€0,99)';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->currency($value, 'GBP');
+		$expected = '(99p)';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->currency($value, 'USD', array('negative' => '-'));
+		$expected = '-99c';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->currency($value, 'EUR', array('negative' => '-'));
+		$expected = '-€0,99';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->currency($value, 'GBP', array('negative' => '-'));
+		$expected = '-99p';
+		$this->assertEquals($expected, $result);
+	}
+
+/**
+ * testCurrencyZero method
+ *
+ * @return void
+ */
+	public function testCurrencyZero() {
+		$value = '0';
+
+		$result = $this->Number->currency($value, 'USD');
+		$expected = '$0.00';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->currency($value, 'EUR');
+		$expected = '€0,00';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->currency($value, 'GBP');
+		$expected = '£0.00';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->currency($value, 'GBP', array('zero' => 'FREE!'));
+		$expected = 'FREE!';
+		$this->assertEquals($expected, $result);
+	}
+
+/**
+ * testCurrencyOptions method
+ *
+ * @return void
+ */
+	public function testCurrencyOptions() {
+		$value = '1234567.89';
+
+		$result = $this->Number->currency($value, null, array('before' => 'GBP'));
+		$expected = 'GBP1,234,567.89';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->currency($value, 'GBP', array('places' => 0));
+		$expected = '£1,234,568';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->currency('1234567.8912345', null, array('before' => 'GBP', 'places' => 3));
+		$expected = 'GBP1,234,567.891';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->currency('650.120001', null, array('before' => 'GBP', 'places' => 4));
+		$expected = 'GBP650.1200';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->currency($value, 'GBP', array('escape' => true));
+		$expected = '&#163;1,234,567.89';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->currency('0.35', 'USD', array('after' => false));
+		$expected = '$0.35';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->currency('0.35', 'GBP', array('after' => false));
+		$expected = '£0.35';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->currency('0.35', 'GBP');
+		$expected = '35p';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->currency('0.35', 'EUR');
+		$expected = '€0,35';
+		$this->assertEquals($expected, $result);
+	}
+
+/**
+ * testToReadableSize method
+ *
+ * @return void
+ */
+	public function testToReadableSize() {
+		$result = $this->Number->toReadableSize(0);
+		$expected = '0 Bytes';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->toReadableSize(1);
+		$expected = '1 Byte';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->toReadableSize(45);
+		$expected = '45 Bytes';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->toReadableSize(1023);
+		$expected = '1023 Bytes';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->toReadableSize(1024);
+		$expected = '1 KB';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->toReadableSize(1024 * 512);
+		$expected = '512 KB';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->toReadableSize(1024 * 1024 - 1);
+		$expected = '1.00 MB';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->toReadableSize(1024 * 1024 * 512);
+		$expected = '512.00 MB';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->toReadableSize(1024 * 1024 * 1024 - 1);
+		$expected = '1.00 GB';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->toReadableSize(1024 * 1024 * 1024 * 512);
+		$expected = '512.00 GB';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->toReadableSize(1024 * 1024 * 1024 * 1024 - 1);
+		$expected = '1.00 TB';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->toReadableSize(1024 * 1024 * 1024 * 1024 * 512);
+		$expected = '512.00 TB';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->toReadableSize(1024 * 1024 * 1024 * 1024 * 1024 - 1);
+		$expected = '1024.00 TB';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->toReadableSize(1024 * 1024 * 1024 * 1024 * 1024 * 1024);
+		$expected = (1024 * 1024) . '.00 TB';
+		$this->assertEquals($expected, $result);
+	}
+
+/**
+ * test toReadableSize() with locales
+ *
+ * @return void
+ */
+	public function testReadableSizeLocalized() {
+		$restore = setlocale(LC_NUMERIC, 0);
+		setlocale(LC_NUMERIC, 'de_DE');
+		$result = $this->Number->toReadableSize(1321205);
+		$this->assertRegExp('/1[,.]26 MB/', $result);
+
+		$result = $this->Number->toReadableSize(1024 * 1024 * 1024 * 512);
+		$this->assertRegExp('/512[,.]00 GB/', $result);
+		setlocale(LC_NUMERIC, $restore);
+	}
+
+/**
+ * testToPercentage method
+ *
+ * @return void
+ */
+	public function testToPercentage() {
+		$result = $this->Number->toPercentage(45, 0);
+		$expected = '45%';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->toPercentage(45, 2);
+		$expected = '45.00%';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->toPercentage(0, 0);
+		$expected = '0%';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Number->toPercentage(0, 4);
+		$expected = '0.0000%';
+		$this->assertEquals($expected, $result);
+	}
+
+}
diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Utility/CakeTimeTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Utility/CakeTimeTest.php
new file mode 100644
index 0000000..13bf89d
--- /dev/null
+++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Utility/CakeTimeTest.php
@@ -0,0 +1,1052 @@
+
+ * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
+ *
+ * Licensed under The MIT License
+ * Redistributions of files must retain the above copyright notice
+ *
+ * @copyright     Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
+ * @link          http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
+ * @package       Cake.Test.Case.View.Helper
+ * @since         CakePHP(tm) v 1.2.0.4206
+ * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
+ */
+App::uses('CakeTime', 'Utility');
+
+/**
+ * CakeTimeTest class
+ *
+ * @package       Cake.Test.Case.View.Helper
+ */
+class CakeTimeTest extends CakeTestCase {
+
+/**
+ * Default system timezone identifier
+ *
+ * @var string
+ */
+	protected $_systemTimezoneIdentifier = null;
+
+/**
+ * setUp method
+ *
+ * @return void
+ */
+	public function setUp() {
+		$this->Time = new CakeTime();
+		$this->_systemTimezoneIdentifier = date_default_timezone_get();
+	}
+
+/**
+ * tearDown method
+ *
+ * @return void
+ */
+	public function tearDown() {
+		unset($this->Time);
+		$this->_restoreSystemTimezone();
+	}
+
+/**
+ * Restored the original system timezone
+ *
+ * @param string $timezoneIdentifier Timezone string
+ * @return void
+ */
+	protected function _restoreSystemTimezone() {
+		date_default_timezone_set($this->_systemTimezoneIdentifier);
+	}
+
+/**
+ * testToQuarter method
+ *
+ * @return void
+ */
+	public function testToQuarter() {
+		$result = $this->Time->toQuarter('2007-12-25');
+		$this->assertEquals(4, $result);
+
+		$result = $this->Time->toQuarter('2007-9-25');
+		$this->assertEquals(3, $result);
+
+		$result = $this->Time->toQuarter('2007-3-25');
+		$this->assertEquals(1, $result);
+
+		$result = $this->Time->toQuarter('2007-3-25', true);
+		$this->assertEquals(array('2007-01-01', '2007-03-31'), $result);
+
+		$result = $this->Time->toQuarter('2007-5-25', true);
+		$this->assertEquals(array('2007-04-01', '2007-06-30'), $result);
+
+		$result = $this->Time->toQuarter('2007-8-25', true);
+		$this->assertEquals(array('2007-07-01', '2007-09-30'), $result);
+
+		$result = $this->Time->toQuarter('2007-12-25', true);
+		$this->assertEquals(array('2007-10-01', '2007-12-31'), $result);
+	}
+
+/**
+ * provider for timeAgoInWords() tests
+ *
+ * @return array
+ */
+	public static function timeAgoProvider() {
+		return array(
+			array('-12 seconds', '12 seconds ago'),
+			array('-12 minutes', '12 minutes ago'),
+			array('-2 hours', '2 hours ago'),
+			array('-1 day', '1 day ago'),
+			array('-2 days', '2 days ago'),
+			array('-2 days -3 hours', '2 days, 3 hours ago'),
+			array('-1 week', '1 week ago'),
+			array('-2 weeks -2 days', '2 weeks, 2 days ago'),
+			array('+1 week', '1 week'),
+			array('+1 week 1 day', '1 week, 1 day'),
+			array('+2 weeks 2 day', '2 weeks, 2 days'),
+			array('2007-9-24', 'on 24/9/07'),
+			array('now', 'just now'),
+		);
+	}
+
+/**
+ * testTimeAgoInWords method
+ *
+ * @dataProvider timeAgoProvider
+ * @return void
+ */
+	public function testTimeAgoInWords($input, $expected) {
+		$result = $this->Time->timeAgoInWords($input);
+		$this->assertEquals($expected, $result);
+	}
+
+/**
+ * provider for timeAgo with an end date.
+ *
+ * @return void
+ */
+	public function timeAgoEndProvider() {
+		return array(
+			array(
+				'+4 months +2 weeks +3 days',
+				'4 months, 2 weeks, 3 days',
+				'8 years'
+			),
+			array(
+				'+4 months +2 weeks +1 day',
+				'4 months, 2 weeks, 1 day',
+				'8 years'
+			),
+			array(
+				'+3 months +2 weeks',
+				'3 months, 2 weeks',
+				'8 years'
+			),
+			array(
+				'+3 months +2 weeks +1 day',
+				'3 months, 2 weeks, 1 day',
+				'8 years'
+			),
+			array(
+				'+1 months +1 week +1 day',
+				'1 month, 1 week, 1 day',
+				'8 years'
+			),
+			array(
+				'+2 months +2 days',
+				'2 months, 2 days',
+				'on ' . date('j/n/y', strtotime('+2 months +2 days'))
+			),
+			array(
+				'+2 months +12 days',
+				'2 months, 1 week, 5 days',
+				'3 months'
+			),
+		);
+	}
+
+/**
+ * test the end option for timeAgoInWords
+ *
+ * @dataProvider timeAgoEndProvider
+ * @return void
+ */
+	public function testTimeAgoInWordsEnd($input, $expected, $end) {
+		$result = $this->Time->timeAgoInWords(
+			$input, array('end' => $end)
+		);
+		$this->assertEquals($expected, $result);
+	}
+
+/**
+ * Test the accuracy option for timeAgoInWords()
+ *
+ * @return void
+ */
+	public function testTimeAgoInWordsAccuracy() {
+		$result = $this->Time->timeAgoInWords(
+			strtotime('+8 years +4 months +2 weeks +3 days'),
+			array('accuracy' => array('year' => 'year'), 'end' => '+10 years')
+		);
+		$expected = '8 years';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Time->timeAgoInWords(
+			strtotime('+8 years +4 months +2 weeks +3 days'),
+			array('accuracy' => array('year' => 'month'), 'end' => '+10 years')
+		);
+		$expected = '8 years, 4 months';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Time->timeAgoInWords(
+			strtotime('+8 years +4 months +2 weeks +3 days'),
+			array('accuracy' => array('year' => 'week'), 'end' => '+10 years')
+		);
+		$expected = '8 years, 4 months, 2 weeks';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Time->timeAgoInWords(
+			strtotime('+8 years +4 months +2 weeks +3 days'),
+			array('accuracy' => array('year' => 'day'), 'end' => '+10 years')
+		);
+		$expected = '8 years, 4 months, 2 weeks, 3 days';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Time->timeAgoInWords(
+			strtotime('+1 years +5 weeks'),
+			array('accuracy' => array('year' => 'year'), 'end' => '+10 years')
+		);
+		$expected = '1 year';
+		$this->assertEquals($expected, $result);
+	}
+
+/**
+ * Test the format option of timeAgoInWords()
+ *
+ * @return void
+ */
+	public function testTimeAgoInWordsWithFormat() {
+		$result = $this->Time->timeAgoInWords('2007-9-25', 'Y-m-d');
+		$this->assertEquals('on 2007-09-25', $result);
+
+		$result = $this->Time->timeAgoInWords('2007-9-25', 'Y-m-d');
+		$this->assertEquals('on 2007-09-25', $result);
+
+		$result = $this->Time->timeAgoInWords(
+			strtotime('+2 weeks +2 days'),
+			'Y-m-d'
+		);
+		$this->assertRegExp('/^2 weeks, [1|2] day(s)?$/', $result);
+
+		$result = $this->Time->timeAgoInWords(
+			strtotime('+2 months +2 days'),
+			array('end' => '1 month', 'format' => 'Y-m-d')
+		);
+		$this->assertEquals('on ' . date('Y-m-d', strtotime('+2 months +2 days')), $result);
+	}
+
+/**
+ * test timeAgoInWords() with negative values.
+ *
+ * @return void
+ */
+	public function testTimeAgoInWordsNegativeValues() {
+		$result = $this->Time->timeAgoInWords(
+			strtotime('-2 months -2 days'),
+			array('end' => '3 month')
+		);
+		$this->assertEquals('2 months, 2 days ago', $result);
+
+		$result = $this->Time->timeAgoInWords(
+			strtotime('-2 months -2 days'),
+			array('end' => '3 month')
+		);
+		$this->assertEquals('2 months, 2 days ago', $result);
+
+		$result = $this->Time->timeAgoInWords(
+			strtotime('-2 months -2 days'),
+			array('end' => '1 month', 'format' => 'Y-m-d')
+		);
+		$this->assertEquals('on ' . date('Y-m-d', strtotime('-2 months -2 days')), $result);
+
+		$result = $this->Time->timeAgoInWords(
+			strtotime('-2 years -5 months -2 days'),
+			array('end' => '3 years')
+		);
+		$this->assertEquals('2 years, 5 months, 2 days ago', $result);
+
+		$result = $this->Time->timeAgoInWords(
+			strtotime('-2 weeks -2 days'),
+			'Y-m-d'
+		);
+		$this->assertEquals('2 weeks, 2 days ago', $result);
+
+		$time = strtotime('-3 years -12 months');
+		$result = $this->Time->timeAgoInWords($time);
+		$expected = 'on ' . date('j/n/y', $time);
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Time->timeAgoInWords(
+			strtotime('-1 month -1 week -6 days'),
+			array('end' => '1 year', 'accuracy' => array('month' => 'month'))
+		);
+		$this->assertEquals('1 month ago', $result);
+
+		$timestamp = strtotime('-1 years -2 weeks -3 days');
+		$result = $this->Time->timeAgoInWords(
+			$timestamp,
+			array('accuracy' => array('year' => 'year'))
+		);
+		$expected = 'on ' . date('j/n/y', $timestamp);
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Time->timeAgoInWords(
+			strtotime('-13 months -5 days'),
+			array('end' => '2 years')
+		);
+		$this->assertEquals('1 year, 1 month, 5 days ago', $result);
+	}
+
+/**
+ * testNice method
+ *
+ * @return void
+ */
+	public function testNice() {
+		$time = time() + 2 * DAY;
+		$this->assertEquals(date('D, M jS Y, H:i', $time), $this->Time->nice($time));
+
+		$time = time() - 2 * DAY;
+		$this->assertEquals(date('D, M jS Y, H:i', $time), $this->Time->nice($time));
+
+		$time = time();
+		$this->assertEquals(date('D, M jS Y, H:i', $time), $this->Time->nice($time));
+
+		$time = 0;
+		$this->assertEquals(date('D, M jS Y, H:i', time()), $this->Time->nice($time));
+
+		$time = null;
+		$this->assertEquals(date('D, M jS Y, H:i', time()), $this->Time->nice($time));
+
+		$time = time();
+		$this->assertEquals(date('D', $time), $this->Time->nice($time, null, '%a'));
+		$this->assertEquals(date('M d, Y', $time), $this->Time->nice($time, null, '%b %d, %Y'));
+
+		$this->Time->niceFormat = '%Y-%d-%m';
+		$this->assertEquals(date('Y-d-m', $time), $this->Time->nice($time));
+		$this->assertEquals('%Y-%d-%m', $this->Time->niceFormat);
+
+		CakeTime::$niceFormat = '%Y-%d-%m %H:%M:%S';
+		$this->assertEquals(date('Y-d-m H:i:s', $time), $this->Time->nice($time));
+		$this->assertEquals('%Y-%d-%m %H:%M:%S', $this->Time->niceFormat);
+
+		date_default_timezone_set('UTC');
+		$result = $this->Time->nice(null, 'America/New_York');
+		$expected = $this->Time->nice(time(), 'America/New_York');
+		$this->assertEquals($expected, $result);
+
+		$this->_restoreSystemTimezone();
+	}
+
+/**
+ * testNiceShort method
+ *
+ * @return void
+ */
+	public function testNiceShort() {
+		$time = time();
+		$this->assertEquals('Today, ' . date('H:i', $time), $this->Time->niceShort($time));
+
+		$time = time() - DAY;
+		$this->assertEquals('Yesterday, ' . date('H:i', $time), $this->Time->niceShort($time));
+
+		$time = time() + DAY;
+		$this->assertEquals('Tomorrow, ' . date('H:i', $time), $this->Time->niceShort($time));
+
+		date_default_timezone_set('Europe/London');
+		$result = $this->Time->niceShort('2005-01-15 10:00:00', new DateTimeZone('Europe/Brussels'));
+		$this->assertEquals('Jan 15th 2005, 11:00', $result);
+
+		date_default_timezone_set('UTC');
+		$result = $this->Time->niceShort(null, 'America/New_York');
+		$expected = $this->Time->niceShort(time(), 'America/New_York');
+		$this->assertEquals($expected, $result);
+
+		$this->_restoreSystemTimezone();
+	}
+
+/**
+ * testDaysAsSql method
+ *
+ * @return void
+ */
+	public function testDaysAsSql() {
+		$begin = time();
+		$end = time() + DAY;
+		$field = 'my_field';
+		$expected = '(my_field >= \'' . date('Y-m-d', $begin) . ' 00:00:00\') AND (my_field <= \'' . date('Y-m-d', $end) . ' 23:59:59\')';
+		$this->assertEquals($expected, $this->Time->daysAsSql($begin, $end, $field));
+	}
+
+/**
+ * testDayAsSql method
+ *
+ * @return void
+ */
+	public function testDayAsSql() {
+		$time = time();
+		$field = 'my_field';
+		$expected = '(my_field >= \'' . date('Y-m-d', $time) . ' 00:00:00\') AND (my_field <= \'' . date('Y-m-d', $time) . ' 23:59:59\')';
+		$this->assertEquals($expected, $this->Time->dayAsSql($time, $field));
+	}
+
+/**
+ * testToUnix method
+ *
+ * @return void
+ */
+	public function testToUnix() {
+		$this->assertEquals(time(), $this->Time->toUnix(time()));
+		$this->assertEquals(strtotime('+1 day'), $this->Time->toUnix('+1 day'));
+		$this->assertEquals(strtotime('+0 days'), $this->Time->toUnix('+0 days'));
+		$this->assertEquals(strtotime('-1 days'), $this->Time->toUnix('-1 days'));
+		$this->assertEquals(false, $this->Time->toUnix(''));
+		$this->assertEquals(false, $this->Time->toUnix(null));
+	}
+
+/**
+ * testToServer method
+ *
+ * @return void
+ */
+	public function testToServer() {
+		date_default_timezone_set('Europe/Paris');
+
+		$time = time();
+		$this->assertEquals(date('Y-m-d H:i:s', $time), $this->Time->toServer($time));
+
+		date_default_timezone_set('America/New_York');
+		$time = time();
+		date_default_timezone_set('Europe/Paris');
+		$result = $this->Time->toServer($time, 'America/New_York');
+		$this->assertEquals(date('Y-m-d H:i:s', $time), $result);
+
+		date_default_timezone_set('Europe/Paris');
+		$time = '2005-10-25 10:00:00';
+		$result = $this->Time->toServer($time);
+		$date = new DateTime($time, new DateTimeZone('UTC'));
+		$date->setTimezone(new DateTimeZone(date_default_timezone_get()));
+		$expected = $date->format('Y-m-d H:i:s');
+		$this->assertEquals($expected, $result);
+
+		$time = '2002-01-01 05:15:30';
+		$result = $this->Time->toServer($time, 'America/New_York');
+		$date = new DateTime($time, new DateTimeZone('America/New_York'));
+		$date->setTimezone(new DateTimeZone(date_default_timezone_get()));
+		$expected = $date->format('Y-m-d H:i:s');
+		$this->assertEquals($expected, $result);
+
+		$time = '2010-01-28T15:00:00+10:00';
+		$result = $this->Time->toServer($time, 'America/New_York');
+		$date = new DateTime($time);
+		$date->setTimezone(new DateTimeZone(date_default_timezone_get()));
+		$expected = $date->format('Y-m-d H:i:s');
+		$this->assertEquals($expected, $result);
+
+		$date = new DateTime(null, new DateTimeZone('America/New_York'));
+		$result = $this->Time->toServer($date, 'Pacific/Tahiti');
+		$date->setTimezone(new DateTimeZone(date_default_timezone_get()));
+		$expected = $date->format('Y-m-d H:i:s');
+		$this->assertEquals($expected, $result);
+
+		$this->_restoreSystemTimezone();
+
+		$time = time();
+		$result = $this->Time->toServer($time, null, 'l jS \of F Y h:i:s A');
+		$expected = date('l jS \of F Y h:i:s A', $time);
+		$this->assertEquals($expected, $result);
+
+		$this->assertFalse($this->Time->toServer(time(), new Object()));
+
+		date_default_timezone_set('UTC');
+
+		$serverTime = new DateTime('now');
+
+		$timezones = array('Europe/London', 'Europe/Brussels', 'UTC', 'America/Denver', 'America/Caracas', 'Asia/Kathmandu');
+		foreach ($timezones as $timezone) {
+			$result = $this->Time->toServer($serverTime->format('Y-m-d H:i:s'), $timezone, 'U');
+			$tz = new DateTimeZone($timezone);
+			$this->assertEquals($serverTime->format('U'), $result + $tz->getOffset($serverTime));
+		}
+
+		date_default_timezone_set('UTC');
+		$date = new DateTime('now', new DateTimeZone('America/New_York'));
+
+		$result = $this->Time->toServer($date, null, 'Y-m-d H:i:s');
+		$date->setTimezone($this->Time->timezone());
+		$expected = $date->format('Y-m-d H:i:s');
+		$this->assertEquals($expected, $result);
+
+		$this->_restoreSystemTimezone();
+	}
+
+/**
+ * testToAtom method
+ *
+ * @return void
+ */
+	public function testToAtom() {
+		$this->assertEquals(date('Y-m-d\TH:i:s\Z'), $this->Time->toAtom(time()));
+	}
+
+/**
+ * testToRss method
+ *
+ * @return void
+ */
+	public function testToRss() {
+		$this->assertEquals(date('r'), $this->Time->toRss(time()));
+
+		if (!$this->skipIf(!class_exists('DateTimeZone'), '%s DateTimeZone class not available.')) {
+			$timezones = array('Europe/London', 'Europe/Brussels', 'UTC', 'America/Denver', 'America/Caracas', 'Asia/Kathmandu');
+			foreach ($timezones as $timezone) {
+				$yourTimezone = new DateTimeZone($timezone);
+				$yourTime = new DateTime('now', $yourTimezone);
+				$userOffset = $yourTimezone->getOffset($yourTime) / HOUR;
+				$this->assertEquals($yourTime->format('r'), $this->Time->toRss(time(), $userOffset));
+				$this->assertEquals($yourTime->format('r'), $this->Time->toRss(time(), $timezone));
+			}
+		}
+	}
+
+/**
+ * testFormat method
+ *
+ * @return void
+ */
+	public function testFormat() {
+		$format = 'D-M-Y';
+		$tz = date_default_timezone_get();
+		$arr = array(time(), strtotime('+1 days'), strtotime('+1 days'), strtotime('+0 days'));
+		foreach ($arr as $val) {
+			$this->assertEquals(date($format, $val), $this->Time->format($format, $val));
+			$this->assertEquals(date($format, $val), $this->Time->format($format, $val, false, $tz));
+		}
+
+		$result = $this->Time->format('Y-m-d', null, 'never');
+		$this->assertEquals('never', $result);
+
+		$result = $this->Time->format('2012-01-13', '%d-%m-%Y', 'invalid');
+		$this->assertEquals('13-01-2012', $result);
+
+		$result = $this->Time->format('nonsense', '%d-%m-%Y', 'invalid', 'UTC');
+		$this->assertEquals('invalid', $result);
+	}
+
+/**
+ * testOfGmt method
+ *
+ * @return void
+ */
+	public function testGmt() {
+		$hour = 3;
+		$min = 4;
+		$sec = 2;
+		$month = 5;
+		$day = 14;
+		$year = 2007;
+		$time = mktime($hour, $min, $sec, $month, $day, $year);
+		$expected = gmmktime($hour, $min, $sec, $month, $day, $year);
+		$this->assertEquals($expected, $this->Time->gmt(date('Y-n-j G:i:s', $time)));
+
+		$hour = date('H');
+		$min = date('i');
+		$sec = date('s');
+		$month = date('m');
+		$day = date('d');
+		$year = date('Y');
+		$expected = gmmktime($hour, $min, $sec, $month, $day, $year);
+		$this->assertEquals($expected, $this->Time->gmt(null));
+	}
+
+/**
+ * testIsToday method
+ *
+ * @return void
+ */
+	public function testIsToday() {
+		$result = $this->Time->isToday('+1 day');
+		$this->assertFalse($result);
+		$result = $this->Time->isToday('+1 days');
+		$this->assertFalse($result);
+		$result = $this->Time->isToday('+0 day');
+		$this->assertTrue($result);
+		$result = $this->Time->isToday('-1 day');
+		$this->assertFalse($result);
+	}
+
+/**
+ * testIsThisWeek method
+ *
+ * @return void
+ */
+	public function testIsThisWeek() {
+		// A map of days which goes from -1 day of week to +1 day of week
+		$map = array(
+			'Mon' => array(-1, 7), 'Tue' => array(-2, 6), 'Wed' => array(-3, 5),
+			'Thu' => array(-4, 4), 'Fri' => array(-5, 3), 'Sat' => array(-6, 2),
+			'Sun' => array(-7, 1)
+		);
+		$days = $map[date('D')];
+
+		for ($day = $days[0] + 1; $day < $days[1]; $day++) {
+			$this->assertTrue($this->Time->isThisWeek(($day > 0 ? '+' : '') . $day . ' days'));
+		}
+		$this->assertFalse($this->Time->isThisWeek($days[0] . ' days'));
+		$this->assertFalse($this->Time->isThisWeek('+' . $days[1] . ' days'));
+	}
+
+/**
+ * testIsThisMonth method
+ *
+ * @return void
+ */
+	public function testIsThisMonth() {
+		$result = $this->Time->isThisMonth('+0 day');
+		$this->assertTrue($result);
+		$result = $this->Time->isThisMonth($time = mktime(0, 0, 0, date('m'), mt_rand(1, 28), date('Y')));
+		$this->assertTrue($result);
+		$result = $this->Time->isThisMonth(mktime(0, 0, 0, date('m'), mt_rand(1, 28), date('Y') - mt_rand(1, 12)));
+		$this->assertFalse($result);
+		$result = $this->Time->isThisMonth(mktime(0, 0, 0, date('m'), mt_rand(1, 28), date('Y') + mt_rand(1, 12)));
+		$this->assertFalse($result);
+	}
+
+/**
+ * testIsThisYear method
+ *
+ * @return void
+ */
+	public function testIsThisYear() {
+		$result = $this->Time->isThisYear('+0 day');
+		$this->assertTrue($result);
+		$result = $this->Time->isThisYear(mktime(0, 0, 0, mt_rand(1, 12), mt_rand(1, 28), date('Y')));
+		$this->assertTrue($result);
+	}
+
+/**
+ * testWasYesterday method
+ *
+ * @return void
+ */
+	public function testWasYesterday() {
+		$result = $this->Time->wasYesterday('+1 day');
+		$this->assertFalse($result);
+		$result = $this->Time->wasYesterday('+1 days');
+		$this->assertFalse($result);
+		$result = $this->Time->wasYesterday('+0 day');
+		$this->assertFalse($result);
+		$result = $this->Time->wasYesterday('-1 day');
+		$this->assertTrue($result);
+		$result = $this->Time->wasYesterday('-1 days');
+		$this->assertTrue($result);
+		$result = $this->Time->wasYesterday('-2 days');
+		$this->assertFalse($result);
+	}
+
+/**
+ * testIsTomorrow method
+ *
+ * @return void
+ */
+	public function testIsTomorrow() {
+		$result = $this->Time->isTomorrow('+1 day');
+		$this->assertTrue($result);
+		$result = $this->Time->isTomorrow('+1 days');
+		$this->assertTrue($result);
+		$result = $this->Time->isTomorrow('+0 day');
+		$this->assertFalse($result);
+		$result = $this->Time->isTomorrow('-1 day');
+		$this->assertFalse($result);
+	}
+
+/**
+ * testWasWithinLast method
+ *
+ * @return void
+ */
+	public function testWasWithinLast() {
+		$this->assertTrue($this->Time->wasWithinLast('1 day', '-1 day'));
+		$this->assertTrue($this->Time->wasWithinLast('1 week', '-1 week'));
+		$this->assertTrue($this->Time->wasWithinLast('1 year', '-1 year'));
+		$this->assertTrue($this->Time->wasWithinLast('1 second', '-1 second'));
+		$this->assertTrue($this->Time->wasWithinLast('1 minute', '-1 minute'));
+		$this->assertTrue($this->Time->wasWithinLast('1 year', '-1 year'));
+		$this->assertTrue($this->Time->wasWithinLast('1 month', '-1 month'));
+		$this->assertTrue($this->Time->wasWithinLast('1 day', '-1 day'));
+
+		$this->assertTrue($this->Time->wasWithinLast('1 week', '-1 day'));
+		$this->assertTrue($this->Time->wasWithinLast('2 week', '-1 week'));
+		$this->assertFalse($this->Time->wasWithinLast('1 second', '-1 year'));
+		$this->assertTrue($this->Time->wasWithinLast('10 minutes', '-1 second'));
+		$this->assertTrue($this->Time->wasWithinLast('23 minutes', '-1 minute'));
+		$this->assertFalse($this->Time->wasWithinLast('0 year', '-1 year'));
+		$this->assertTrue($this->Time->wasWithinLast('13 month', '-1 month'));
+		$this->assertTrue($this->Time->wasWithinLast('2 days', '-1 day'));
+
+		$this->assertFalse($this->Time->wasWithinLast('1 week', '-2 weeks'));
+		$this->assertFalse($this->Time->wasWithinLast('1 second', '-2 seconds'));
+		$this->assertFalse($this->Time->wasWithinLast('1 day', '-2 days'));
+		$this->assertFalse($this->Time->wasWithinLast('1 hour', '-2 hours'));
+		$this->assertFalse($this->Time->wasWithinLast('1 month', '-2 months'));
+		$this->assertFalse($this->Time->wasWithinLast('1 year', '-2 years'));
+
+		$this->assertFalse($this->Time->wasWithinLast('1 day', '-2 weeks'));
+		$this->assertFalse($this->Time->wasWithinLast('1 day', '-2 days'));
+		$this->assertFalse($this->Time->wasWithinLast('0 days', '-2 days'));
+		$this->assertTrue($this->Time->wasWithinLast('1 hour', '-20 seconds'));
+		$this->assertTrue($this->Time->wasWithinLast('1 year', '-60 minutes -30 seconds'));
+		$this->assertTrue($this->Time->wasWithinLast('3 years', '-2 months'));
+		$this->assertTrue($this->Time->wasWithinLast('5 months', '-4 months'));
+
+		$this->assertTrue($this->Time->wasWithinLast('5 ', '-3 days'));
+		$this->assertTrue($this->Time->wasWithinLast('1   ', '-1 hour'));
+		$this->assertTrue($this->Time->wasWithinLast('1   ', '-1 minute'));
+		$this->assertTrue($this->Time->wasWithinLast('1   ', '-23 hours -59 minutes -59 seconds'));
+	}
+
+/**
+ * testWasWithinLast method
+ *
+ * @return void
+ */
+	public function testIsWithinNext() {
+		$this->assertFalse($this->Time->isWithinNext('1 day', '-1 day'));
+		$this->assertFalse($this->Time->isWithinNext('1 week', '-1 week'));
+		$this->assertFalse($this->Time->isWithinNext('1 year', '-1 year'));
+		$this->assertFalse($this->Time->isWithinNext('1 second', '-1 second'));
+		$this->assertFalse($this->Time->isWithinNext('1 minute', '-1 minute'));
+		$this->assertFalse($this->Time->isWithinNext('1 year', '-1 year'));
+		$this->assertFalse($this->Time->isWithinNext('1 month', '-1 month'));
+		$this->assertFalse($this->Time->isWithinNext('1 day', '-1 day'));
+
+		$this->assertFalse($this->Time->isWithinNext('1 week', '-1 day'));
+		$this->assertFalse($this->Time->isWithinNext('2 week', '-1 week'));
+		$this->assertFalse($this->Time->isWithinNext('1 second', '-1 year'));
+		$this->assertFalse($this->Time->isWithinNext('10 minutes', '-1 second'));
+		$this->assertFalse($this->Time->isWithinNext('23 minutes', '-1 minute'));
+		$this->assertFalse($this->Time->isWithinNext('0 year', '-1 year'));
+		$this->assertFalse($this->Time->isWithinNext('13 month', '-1 month'));
+		$this->assertFalse($this->Time->isWithinNext('2 days', '-1 day'));
+
+		$this->assertFalse($this->Time->isWithinNext('1 week', '-2 weeks'));
+		$this->assertFalse($this->Time->isWithinNext('1 second', '-2 seconds'));
+		$this->assertFalse($this->Time->isWithinNext('1 day', '-2 days'));
+		$this->assertFalse($this->Time->isWithinNext('1 hour', '-2 hours'));
+		$this->assertFalse($this->Time->isWithinNext('1 month', '-2 months'));
+		$this->assertFalse($this->Time->isWithinNext('1 year', '-2 years'));
+
+		$this->assertFalse($this->Time->isWithinNext('1 day', '-2 weeks'));
+		$this->assertFalse($this->Time->isWithinNext('1 day', '-2 days'));
+		$this->assertFalse($this->Time->isWithinNext('0 days', '-2 days'));
+		$this->assertFalse($this->Time->isWithinNext('1 hour', '-20 seconds'));
+		$this->assertFalse($this->Time->isWithinNext('1 year', '-60 minutes -30 seconds'));
+		$this->assertFalse($this->Time->isWithinNext('3 years', '-2 months'));
+		$this->assertFalse($this->Time->isWithinNext('5 months', '-4 months'));
+
+		$this->assertFalse($this->Time->isWithinNext('5 ', '-3 days'));
+		$this->assertFalse($this->Time->isWithinNext('1   ', '-1 hour'));
+		$this->assertFalse($this->Time->isWithinNext('1   ', '-1 minute'));
+		$this->assertFalse($this->Time->isWithinNext('1   ', '-23 hours -59 minutes -59 seconds'));
+
+		$this->assertTrue($this->Time->isWithinNext('7 days', '6 days, 23 hours, 59 minutes, 59 seconds'));
+		$this->assertFalse($this->Time->isWithinNext('7 days', '6 days, 23 hours, 59 minutes, 61 seconds'));
+	}
+
+/**
+ * testUserOffset method
+ *
+ * @return void
+ */
+	public function testUserOffset() {
+		$timezoneServer = new DateTimeZone(date_default_timezone_get());
+		$timeServer = new DateTime('now', $timezoneServer);
+		$yourTimezone = $timezoneServer->getOffset($timeServer) / HOUR;
+
+		$expected = time();
+		$result = $this->Time->fromString(time(), $yourTimezone);
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Time->fromString(time(), $timezoneServer->getName());
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Time->fromString(time(), $timezoneServer);
+		$this->assertEquals($expected, $result);
+
+		Configure::write('Config.timezone', $timezoneServer->getName());
+		$result = $this->Time->fromString(time());
+		$this->assertEquals($expected, $result);
+		Configure::delete('Config.timezone');
+	}
+
+/**
+ * test fromString()
+ *
+ * @return void
+ */
+	public function testFromString() {
+		$result = $this->Time->fromString('');
+		$this->assertFalse($result);
+
+		$result = $this->Time->fromString(0, 0);
+		$this->assertFalse($result);
+
+		$result = $this->Time->fromString('+1 hour');
+		$expected = strtotime('+1 hour');
+		$this->assertEquals($expected, $result);
+
+		$timezone = date('Z', time());
+		$result = $this->Time->fromString('+1 hour', $timezone);
+		$expected = $this->Time->convert(strtotime('+1 hour'), $timezone);
+		$this->assertEquals($expected, $result);
+
+		$timezone = date_default_timezone_get();
+		$result = $this->Time->fromString('+1 hour', $timezone);
+		$expected = $this->Time->convert(strtotime('+1 hour'), $timezone);
+		$this->assertEquals($expected, $result);
+
+		date_default_timezone_set('UTC');
+		$date = new DateTime('now', new DateTimeZone('Europe/London'));
+		$this->Time->fromString($date);
+		$this->assertEquals('Europe/London', $date->getTimeZone()->getName());
+
+		$this->_restoreSystemTimezone();
+	}
+
+/**
+ * test fromString() with a DateTime object as the dateString
+ *
+ * @return void
+ */
+	public function testFromStringWithDateTime() {
+		date_default_timezone_set('UTC');
+
+		$date = new DateTime('+1 hour', new DateTimeZone('America/New_York'));
+		$result = $this->Time->fromString($date, 'UTC');
+		$date->setTimezone(new DateTimeZone('UTC'));
+		$expected = $date->format('U') + $date->getOffset();
+
+		$this->assertEquals($expected, $result);
+
+		date_default_timezone_set('Australia/Melbourne');
+
+		$date = new DateTime('+1 hour', new DateTimeZone('America/New_York'));
+		$result = $this->Time->fromString($date, 'Asia/Kuwait');
+		$date->setTimezone(new DateTimeZone('Asia/Kuwait'));
+		$expected = $date->format('U') + $date->getOffset();
+		$this->assertEquals($expected, $result);
+
+		$this->_restoreSystemTimezone();
+	}
+
+/**
+ * test converting time specifiers using a time definition localfe file
+ *
+ * @return void
+ */
+	public function testConvertSpecifiers() {
+		App::build(array(
+			'Locale' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Locale' . DS)
+		), App::RESET);
+		Configure::write('Config.language', 'time_test');
+		$time = strtotime('Thu Jan 14 11:43:39 2010');
+
+		$result = $this->Time->convertSpecifiers('%a', $time);
+		$expected = 'jue';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Time->convertSpecifiers('%A', $time);
+		$expected = 'jueves';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Time->convertSpecifiers('%c', $time);
+		$expected = 'jue %d ene %Y %H:%M:%S %Z';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Time->convertSpecifiers('%C', $time);
+		$expected = '20';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Time->convertSpecifiers('%D', $time);
+		$expected = '%m/%d/%y';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Time->convertSpecifiers('%b', $time);
+		$expected = 'ene';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Time->convertSpecifiers('%h', $time);
+		$expected = 'ene';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Time->convertSpecifiers('%B', $time);
+		$expected = 'enero';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Time->convertSpecifiers('%n', $time);
+		$expected = "\n";
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Time->convertSpecifiers('%n', $time);
+		$expected = "\n";
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Time->convertSpecifiers('%p', $time);
+		$expected = 'AM';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Time->convertSpecifiers('%P', $time);
+		$expected = 'am';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Time->convertSpecifiers('%r', $time);
+		$expected = '%I:%M:%S AM';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Time->convertSpecifiers('%R', $time);
+		$expected = '11:43';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Time->convertSpecifiers('%t', $time);
+		$expected = "\t";
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Time->convertSpecifiers('%T', $time);
+		$expected = '%H:%M:%S';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Time->convertSpecifiers('%u', $time);
+		$expected = 4;
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Time->convertSpecifiers('%x', $time);
+		$expected = '%d/%m/%y';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Time->convertSpecifiers('%X', $time);
+		$expected = '%H:%M:%S';
+		$this->assertEquals($expected, $result);
+	}
+
+/**
+ * test convert %e on windows.
+ *
+ * @return void
+ */
+	public function testConvertPercentE() {
+		$this->skipIf(DIRECTORY_SEPARATOR !== '\\', 'Cannot run windows tests on non-windows OS.');
+
+		$time = strtotime('Thu Jan 14 11:43:39 2010');
+		$result = $this->Time->convertSpecifiers('%e', $time);
+		$expected = '14';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Time->convertSpecifiers('%e', strtotime('2011-01-01'));
+		$expected = ' 1';
+		$this->assertEquals($expected, $result);
+	}
+
+/**
+ * test formatting dates taking in account preferred i18n locale file
+ *
+ * @return void
+ */
+	public function testI18nFormat() {
+		App::build(array(
+			'Locale' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Locale' . DS)
+		), App::RESET);
+		Configure::write('Config.language', 'time_test');
+
+		$time = strtotime('Thu Jan 14 13:59:28 2010');
+
+		$result = $this->Time->i18nFormat($time);
+		$expected = '14/01/10';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Time->i18nFormat($time, '%c');
+		$expected = 'jue 14 ene 2010 13:59:28 ' . utf8_encode(strftime('%Z', $time));
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Time->i18nFormat($time, 'Time is %r, and date is %x');
+		$expected = 'Time is 01:59:28 PM, and date is 14/01/10';
+		$this->assertEquals($expected, $result);
+
+		$time = strtotime('Wed Jan 13 13:59:28 2010');
+
+		$result = $this->Time->i18nFormat($time);
+		$expected = '13/01/10';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Time->i18nFormat($time, '%c');
+		$expected = 'mié 13 ene 2010 13:59:28 ' . utf8_encode(strftime('%Z', $time));
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Time->i18nFormat($time, 'Time is %r, and date is %x');
+		$expected = 'Time is 01:59:28 PM, and date is 13/01/10';
+		$this->assertEquals($expected, $result);
+
+		$result = $this->Time->i18nFormat('invalid date', '%x', 'Date invalid');
+		$expected = 'Date invalid';
+		$this->assertEquals($expected, $result);
+	}
+
+/**
+ * test new format() syntax which inverts first and second parameters
+ *
+ * @return void
+ */
+	public function testFormatNewSyntax() {
+		$time = time();
+		$this->assertEquals($this->Time->format($time), $this->Time->i18nFormat($time));
+		$this->assertEquals($this->Time->format($time, '%c'), $this->Time->i18nFormat($time, '%c'));
+	}
+
+/**
+ * testListTimezones
+ *
+ * @return void
+ */
+	public function testListTimezones() {
+		$return = CakeTime::listTimezones();
+		$this->assertTrue(isset($return['Asia']['Asia/Bangkok']));
+		$this->assertEquals('Bangkok', $return['Asia']['Asia/Bangkok']);
+		$this->assertTrue(isset($return['America']['America/Argentina/Buenos_Aires']));
+		$this->assertEquals('Argentina/Buenos_Aires', $return['America']['America/Argentina/Buenos_Aires']);
+		$this->assertTrue(isset($return['UTC']['UTC']));
+		$this->assertFalse(isset($return['Cuba']));
+		$this->assertFalse(isset($return['US']));
+
+		$return = CakeTime::listTimezones('#^Asia/#');
+		$this->assertTrue(isset($return['Asia']['Asia/Bangkok']));
+		$this->assertFalse(isset($return['Pacific']));
+
+		$return = CakeTime::listTimezones('#^(America|Pacific)/#', null, false);
+		$this->assertTrue(isset($return['America/Argentina/Buenos_Aires']));
+		$this->assertTrue(isset($return['Pacific/Tahiti']));
+
+		if (!$this->skipIf(version_compare(PHP_VERSION, '5.3.0', '<'))) {
+			$return = CakeTime::listTimezones(DateTimeZone::ASIA);
+			$this->assertTrue(isset($return['Asia']['Asia/Bangkok']));
+			$this->assertFalse(isset($return['Pacific']));
+
+			$return = CakeTime::listTimezones(DateTimeZone::PER_COUNTRY, 'US', false);
+			$this->assertTrue(isset($return['Pacific/Honolulu']));
+			$this->assertFalse(isset($return['Asia/Bangkok']));
+		}
+	}
+
+}
diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Utility/ClassRegistryTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Utility/ClassRegistryTest.php
new file mode 100644
index 0000000..eb20fce
--- /dev/null
+++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Utility/ClassRegistryTest.php
@@ -0,0 +1,349 @@
+
+ * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
+ *
+ * Licensed under The MIT License
+ * Redistributions of files must retain the above copyright notice
+ *
+ * @copyright     Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
+ * @link          http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
+ * @package       Cake.Test.Case.Utility
+ * @since         CakePHP(tm) v 1.2.0.5432
+ * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
+ */
+App::uses('ClassRegistry', 'Utility');
+
+/**
+ * ClassRegisterModel class
+ *
+ * @package       Cake.Test.Case.Utility
+ */
+class ClassRegisterModel extends CakeTestModel {
+
+/**
+ * useTable property
+ *
+ * @var bool false
+ */
+	public $useTable = false;
+}
+
+/**
+ * RegisterArticle class
+ *
+ * @package       Cake.Test.Case.Utility
+ */
+class RegisterArticle extends ClassRegisterModel {
+
+/**
+ * name property
+ *
+ * @var string 'RegisterArticle'
+ */
+	public $name = 'RegisterArticle';
+}
+
+/**
+ * RegisterArticleFeatured class
+ *
+ * @package       Cake.Test.Case.Utility
+ */
+class RegisterArticleFeatured extends ClassRegisterModel {
+
+/**
+ * name property
+ *
+ * @var string 'RegisterArticleFeatured'
+ */
+	public $name = 'RegisterArticleFeatured';
+}
+
+/**
+ * RegisterArticleTag class
+ *
+ * @package       Cake.Test.Case.Utility
+ */
+class RegisterArticleTag extends ClassRegisterModel {
+
+/**
+ * name property
+ *
+ * @var string 'RegisterArticleTag'
+ */
+	public $name = 'RegisterArticleTag';
+}
+
+/**
+ * RegistryPluginAppModel class
+ *
+ * @package       Cake.Test.Case.Utility
+ */
+class RegistryPluginAppModel extends ClassRegisterModel {
+
+/**
+ * tablePrefix property
+ *
+ * @var string 'something_'
+ */
+	public $tablePrefix = 'something_';
+}
+
+/**
+ * TestRegistryPluginModel class
+ *
+ * @package       Cake.Test.Case.Utility
+ */
+class TestRegistryPluginModel extends RegistryPluginAppModel {
+
+/**
+ * name property
+ *
+ * @var string 'TestRegistryPluginModel'
+ */
+	public $name = 'TestRegistryPluginModel';
+}
+
+/**
+ * RegisterCategory class
+ *
+ * @package       Cake.Test.Case.Utility
+ */
+class RegisterCategory extends ClassRegisterModel {
+
+/**
+ * name property
+ *
+ * @var string 'RegisterCategory'
+ */
+	public $name = 'RegisterCategory';
+}
+/**
+ * RegisterPrefixedDs class
+ *
+ * @package       Cake.Test.Case.Utility
+ */
+class RegisterPrefixedDs extends ClassRegisterModel {
+
+/**
+ * useDbConfig property
+ *
+ * @var string 'doesnotexist'
+ */
+	public $useDbConfig = 'doesnotexist';
+}
+
+/**
+ * Abstract class for testing ClassRegistry.
+ */
+abstract class ClassRegistryAbstractModel extends ClassRegisterModel {
+
+	public abstract function doSomething();
+
+}
+
+/**
+ * Interface for testing ClassRegistry
+ */
+interface ClassRegistryInterfaceTest {
+
+	public function doSomething();
+
+}
+
+/**
+ * ClassRegistryTest class
+ *
+ * @package       Cake.Test.Case.Utility
+ */
+class ClassRegistryTest extends CakeTestCase {
+
+/**
+ * testAddModel method
+ *
+ * @return void
+ */
+	public function testAddModel() {
+		$Tag = ClassRegistry::init('RegisterArticleTag');
+		$this->assertTrue(is_a($Tag, 'RegisterArticleTag'));
+
+		$TagCopy = ClassRegistry::isKeySet('RegisterArticleTag');
+		$this->assertTrue($TagCopy);
+
+		$Tag->name = 'SomeNewName';
+
+		$TagCopy = ClassRegistry::getObject('RegisterArticleTag');
+
+		$this->assertTrue(is_a($TagCopy, 'RegisterArticleTag'));
+		$this->assertSame($Tag, $TagCopy);
+
+		$NewTag = ClassRegistry::init(array('class' => 'RegisterArticleTag', 'alias' => 'NewTag'));
+		$this->assertTrue(is_a($Tag, 'RegisterArticleTag'));
+
+		$NewTagCopy = ClassRegistry::init(array('class' => 'RegisterArticleTag', 'alias' => 'NewTag'));
+
+		$this->assertNotSame($Tag, $NewTag);
+		$this->assertSame($NewTag, $NewTagCopy);
+
+		$NewTag->name = 'SomeOtherName';
+		$this->assertNotSame($Tag, $NewTag);
+		$this->assertSame($NewTag, $NewTagCopy);
+
+		$Tag->name = 'SomeOtherName';
+		$this->assertNotSame($Tag, $NewTag);
+
+		$this->assertTrue($TagCopy->name === 'SomeOtherName');
+
+		$User = ClassRegistry::init(array('class' => 'RegisterUser', 'alias' => 'User', 'table' => false));
+		$this->assertTrue(is_a($User, 'AppModel'));
+
+		$UserCopy = ClassRegistry::init(array('class' => 'RegisterUser', 'alias' => 'User', 'table' => false));
+		$this->assertTrue(is_a($UserCopy, 'AppModel'));
+		$this->assertEquals($User, $UserCopy);
+
+		$Category = ClassRegistry::init(array('class' => 'RegisterCategory'));
+		$this->assertTrue(is_a($Category, 'RegisterCategory'));
+
+		$ParentCategory = ClassRegistry::init(array('class' => 'RegisterCategory', 'alias' => 'ParentCategory'));
+		$this->assertTrue(is_a($ParentCategory, 'RegisterCategory'));
+		$this->assertNotSame($Category, $ParentCategory);
+
+		$this->assertNotEquals($Category->alias, $ParentCategory->alias);
+		$this->assertEquals('RegisterCategory', $Category->alias);
+		$this->assertEquals('ParentCategory', $ParentCategory->alias);
+	}
+
+/**
+ * testClassRegistryFlush method
+ *
+ * @return void
+ */
+	public function testClassRegistryFlush() {
+		$Tag = ClassRegistry::init('RegisterArticleTag');
+
+		$ArticleTag = ClassRegistry::getObject('RegisterArticleTag');
+		$this->assertTrue(is_a($ArticleTag, 'RegisterArticleTag'));
+		ClassRegistry::flush();
+
+		$NoArticleTag = ClassRegistry::isKeySet('RegisterArticleTag');
+		$this->assertFalse($NoArticleTag);
+		$this->assertTrue(is_a($ArticleTag, 'RegisterArticleTag'));
+	}
+
+/**
+ * testAddMultipleModels method
+ *
+ * @return void
+ */
+	public function testAddMultipleModels() {
+		$Article = ClassRegistry::isKeySet('Article');
+		$this->assertFalse($Article);
+
+		$Featured = ClassRegistry::isKeySet('Featured');
+		$this->assertFalse($Featured);
+
+		$Tag = ClassRegistry::isKeySet('Tag');
+		$this->assertFalse($Tag);
+
+		$models = array(array('class' => 'RegisterArticle', 'alias' => 'Article'),
+				array('class' => 'RegisterArticleFeatured', 'alias' => 'Featured'),
+				array('class' => 'RegisterArticleTag', 'alias' => 'Tag'));
+
+		$added = ClassRegistry::init($models);
+		$this->assertTrue($added);
+
+		$Article = ClassRegistry::isKeySet('Article');
+		$this->assertTrue($Article);
+
+		$Featured = ClassRegistry::isKeySet('Featured');
+		$this->assertTrue($Featured);
+
+		$Tag = ClassRegistry::isKeySet('Tag');
+		$this->assertTrue($Tag);
+
+		$Article = ClassRegistry::getObject('Article');
+		$this->assertTrue(is_a($Article, 'RegisterArticle'));
+
+		$Featured = ClassRegistry::getObject('Featured');
+		$this->assertTrue(is_a($Featured, 'RegisterArticleFeatured'));
+
+		$Tag = ClassRegistry::getObject('Tag');
+		$this->assertTrue(is_a($Tag, 'RegisterArticleTag'));
+	}
+
+/**
+ * testPluginAppModel method
+ *
+ * @return void
+ */
+	public function testPluginAppModel() {
+		$TestRegistryPluginModel = ClassRegistry::isKeySet('TestRegistryPluginModel');
+		$this->assertFalse($TestRegistryPluginModel);
+
+		//Faking a plugin
+		CakePlugin::load('RegistryPlugin', array('path' => '/fake/path'));
+		$TestRegistryPluginModel = ClassRegistry::init('RegistryPlugin.TestRegistryPluginModel');
+		$this->assertTrue(is_a($TestRegistryPluginModel, 'TestRegistryPluginModel'));
+
+		$this->assertEquals('something_', $TestRegistryPluginModel->tablePrefix);
+
+		$PluginUser = ClassRegistry::init(array('class' => 'RegistryPlugin.RegisterUser', 'alias' => 'RegistryPluginUser', 'table' => false));
+		$this->assertTrue(is_a($PluginUser, 'RegistryPluginAppModel'));
+
+		$PluginUserCopy = ClassRegistry::getObject('RegistryPluginUser');
+		$this->assertTrue(is_a($PluginUserCopy, 'RegistryPluginAppModel'));
+		$this->assertSame($PluginUser, $PluginUserCopy);
+		CakePlugin::unload();
+	}
+
+/**
+ * Tests prefixed datasource names for test purposes
+ *
+ */
+	public function testPrefixedTestDatasource() {
+		ClassRegistry::config(array('testing' => true));
+		$Model = ClassRegistry::init('RegisterPrefixedDs');
+		$this->assertEquals('test', $Model->useDbConfig);
+		ClassRegistry::removeObject('RegisterPrefixedDs');
+
+		$testConfig = ConnectionManager::getDataSource('test')->config;
+		ConnectionManager::create('test_doesnotexist', $testConfig);
+
+		$Model = ClassRegistry::init('RegisterArticle');
+		$this->assertEquals('test', $Model->useDbConfig);
+		$Model = ClassRegistry::init('RegisterPrefixedDs');
+		$this->assertEquals('test_doesnotexist', $Model->useDbConfig);
+	}
+
+/**
+ * Tests that passing the string parameter to init() will return false if the model does not exists
+ *
+ */
+	public function testInitStrict() {
+		$this->assertFalse(ClassRegistry::init('NonExistent', true));
+	}
+
+/**
+ * Test that you cannot init() an abstract class. An exception will be raised.
+ *
+ * @expectedException CakeException
+ * @return void
+ */
+	public function testInitAbstractClass() {
+		ClassRegistry::init('ClassRegistryAbstractModel');
+	}
+
+/**
+ * Test that you cannot init() an abstract class. A exception will be raised.
+ *
+ * @expectedException CakeException
+ * @return void
+ */
+	public function testInitInterface() {
+		ClassRegistry::init('ClassRegistryInterfaceTest');
+	}
+}
diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Utility/DebuggerTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Utility/DebuggerTest.php
new file mode 100644
index 0000000..6d7d9ec
--- /dev/null
+++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Utility/DebuggerTest.php
@@ -0,0 +1,499 @@
+_restoreError) {
+			restore_error_handler();
+		}
+	}
+
+/**
+ * testDocRef method
+ *
+ * @return void
+ */
+	public function testDocRef() {
+		ini_set('docref_root', '');
+		$this->assertEquals(ini_get('docref_root'), '');
+		$debugger = new Debugger();
+		$this->assertEquals(ini_get('docref_root'), 'http://php.net/');
+	}
+
+/**
+ * test Excerpt writing
+ *
+ * @return void
+ */
+	public function testExcerpt() {
+		$result = Debugger::excerpt(__FILE__, __LINE__, 2);
+		$this->assertTrue(is_array($result));
+		$this->assertEquals(5, count($result));
+		$this->assertRegExp('/function(.+)testExcerpt/', $result[1]);
+
+		$result = Debugger::excerpt(__FILE__, 2, 2);
+		$this->assertTrue(is_array($result));
+		$this->assertEquals(4, count($result));
+
+		$pattern = '/.*?<\?php/';
+		$this->assertRegExp($pattern, $result[0]);
+
+		$return = Debugger::excerpt('[internal]', 2, 2);
+		$this->assertTrue(empty($return));
+	}
+
+/**
+ * testOutput method
+ *
+ * @return void
+ */
+	public function testOutput() {
+		set_error_handler('Debugger::showError');
+		$this->_restoreError = true;
+
+		$result = Debugger::output(false);
+		$this->assertEquals('', $result);
+		$out .= '';
+		$result = Debugger::output(true);
+
+		$this->assertEquals('Notice', $result[0]['error']);
+		$this->assertRegExp('/Undefined variable\:\s+out/', $result[0]['description']);
+		$this->assertRegExp('/DebuggerTest::testOutput/i', $result[0]['trace']);
+
+		ob_start();
+		Debugger::output('txt');
+		$other .= '';
+		$result = ob_get_clean();
+
+		$this->assertRegExp('/Undefined variable:\s+other/', $result);
+		$this->assertRegExp('/Context:/', $result);
+		$this->assertRegExp('/DebuggerTest::testOutput/i', $result);
+
+		ob_start();
+		Debugger::output('html');
+		$wrong .= '';
+		$result = ob_get_clean();
+		$this->assertRegExp('/
.+<\/pre>/', $result);
+		$this->assertRegExp('/Notice<\/b>/', $result);
+		$this->assertRegExp('/variable:\s+wrong/', $result);
+
+		ob_start();
+		Debugger::output('js');
+		$buzz .= '';
+		$result = explode('', ob_get_clean());
+		$this->assertTags($result[0], array(
+			'pre' => array('class' => 'cake-error'),
+			'a' => array(
+				'href' => "javascript:void(0);",
+				'onclick' => "preg:/document\.getElementById\('cakeErr[a-z0-9]+\-trace'\)\.style\.display = " .
+					 "\(document\.getElementById\('cakeErr[a-z0-9]+\-trace'\)\.style\.display == 'none'" .
+					 " \? '' \: 'none'\);/"
+			),
+			'b' => array(), 'Notice', '/b', ' (8)',
+		));
+
+		$this->assertRegExp('/Undefined variable:\s+buzz/', $result[1]);
+		$this->assertRegExp('/]+>Code/', $result[1]);
+		$this->assertRegExp('/]+>Context/', $result[2]);
+		$this->assertContains('$wrong = ''', $result[3], 'Context should be HTML escaped.');
+	}
+
+/**
+ * Tests that changes in output formats using Debugger::output() change the templates used.
+ *
+ * @return void
+ */
+	public function testChangeOutputFormats() {
+		set_error_handler('Debugger::showError');
+		$this->_restoreError = true;
+
+		Debugger::output('js', array(
+			'traceLine' => '{:reference} - {:path}, line {:line}'
+		));
+		$result = Debugger::trace();
+		$this->assertRegExp('/' . preg_quote('txmt://open?url=file://', '/') . '(\/|[A-Z]:\\\\)' . '/', $result);
+
+		Debugger::output('xml', array(
+			'error' => '{:code}{:file}{:line}' .
+				 '{:description}',
+			'context' => "{:context}",
+			'trace' => "{:trace}",
+		));
+		Debugger::output('xml');
+
+		ob_start();
+		$foo .= '';
+		$result = ob_get_clean();
+
+		$data = array(
+			'error' => array(),
+			'code' => array(), '8', '/code',
+			'file' => array(), 'preg:/[^<]+/', '/file',
+			'line' => array(), '' . (intval(__LINE__) - 7), '/line',
+			'preg:/Undefined variable:\s+foo/',
+			'/error'
+		);
+		$this->assertTags($result, $data, true);
+	}
+
+/**
+ * Test that outputAs works.
+ *
+ * @return void
+ */
+	public function testOutputAs() {
+		Debugger::outputAs('html');
+		$this->assertEquals('html', Debugger::outputAs());
+	}
+
+/**
+ * Test that choosing a non-existent format causes an exception
+ *
+ * @expectedException CakeException
+ * @return void
+ */
+	public function testOutputAsException() {
+		Debugger::outputAs('Invalid junk');
+	}
+
+/**
+ * Tests that changes in output formats using Debugger::output() change the templates used.
+ *
+ * @return void
+ */
+	public function testAddFormat() {
+		set_error_handler('Debugger::showError');
+		$this->_restoreError = true;
+
+		Debugger::addFormat('js', array(
+			'traceLine' => '{:reference} - {:path}, line {:line}'
+		));
+		Debugger::outputAs('js');
+
+		$result = Debugger::trace();
+		$this->assertRegExp('/' . preg_quote('txmt://open?url=file://', '/') . '(\/|[A-Z]:\\\\)' . '/', $result);
+
+		Debugger::addFormat('xml', array(
+			'error' => '{:code}{:file}{:line}' .
+						 '{:description}',
+		));
+		Debugger::outputAs('xml');
+
+		ob_start();
+		$foo .= '';
+		$result = ob_get_clean();
+
+		$data = array(
+			'assertTags($result, $data, true);
+	}
+
+/**
+ * Test adding a format that is handled by a callback.
+ *
+ * @return void
+ */
+	public function testAddFormatCallback() {
+		set_error_handler('Debugger::showError');
+		$this->_restoreError = true;
+
+		Debugger::addFormat('callback', array('callback' => array($this, 'customFormat')));
+		Debugger::outputAs('callback');
+
+		ob_start();
+		$foo .= '';
+		$result = ob_get_clean();
+		$this->assertContains('Notice: I eated an error', $result);
+		$this->assertContains('DebuggerTest.php', $result);
+	}
+
+/**
+ * Test method for testing addFormat with callbacks.
+ */
+	public function customFormat($error, $strings) {
+		return $error['error'] . ': I eated an error ' . $error['path'];
+	}
+
+/**
+ * testTrimPath method
+ *
+ * @return void
+ */
+	public function testTrimPath() {
+		$this->assertEquals(Debugger::trimPath(APP), 'APP' . DS);
+		$this->assertEquals(Debugger::trimPath(CAKE_CORE_INCLUDE_PATH), 'CORE');
+	}
+
+/**
+ * testExportVar method
+ *
+ * @return void
+ */
+	public function testExportVar() {
+		App::uses('Controller', 'Controller');
+		$Controller = new Controller();
+		$Controller->helpers = array('Html', 'Form');
+		$View = new View($Controller);
+		$View->int = 2;
+		$View->float = 1.333;
+
+		$result = Debugger::exportVar($View);
+		$expected = << object(HelperCollection) {}
+	Blocks => object(ViewBlock) {}
+	plugin => null
+	name => ''
+	passedArgs => array()
+	helpers => array(
+		(int) 0 => 'Html',
+		(int) 1 => 'Form'
+	)
+	viewPath => ''
+	viewVars => array()
+	view => null
+	layout => 'default'
+	layoutPath => null
+	autoLayout => true
+	ext => '.ctp'
+	subDir => null
+	theme => null
+	cacheAction => false
+	validationErrors => array()
+	hasRendered => false
+	uuids => array()
+	request => object(CakeRequest) {}
+	response => object(CakeResponse) {}
+	elementCache => 'default'
+	int => (int) 2
+	float => (float) 1.333
+}
+TEXT;
+		$this->assertTextEquals($expected, $result);
+
+		$data = array(
+			1 => 'Index one',
+			5 => 'Index five'
+		);
+		$result = Debugger::exportVar($data);
+		$expected = << 'Index one',
+	(int) 5 => 'Index five'
+)
+TEXT;
+		$this->assertTextEquals($expected, $result);
+
+		$data = array(
+			'key' => array(
+				'value'
+			)
+		);
+		$result = Debugger::exportVar($data, 1);
+		$expected = << array(
+		[maximum depth reached]
+	)
+)
+TEXT;
+		$this->assertTextEquals($expected, $result);
+	}
+
+/**
+ * testLog method
+ *
+ * @return void
+ */
+	public function testLog() {
+		if (file_exists(LOGS . 'debug.log')) {
+			unlink(LOGS . 'debug.log');
+		}
+
+		Debugger::log('cool');
+		$result = file_get_contents(LOGS . 'debug.log');
+		$this->assertRegExp('/DebuggerTest\:\:testLog/i', $result);
+		$this->assertRegExp("/'cool'/", $result);
+
+		unlink(LOGS . 'debug.log');
+
+		Debugger::log(array('whatever', 'here'));
+		$result = file_get_contents(LOGS . 'debug.log');
+		$this->assertRegExp('/DebuggerTest\:\:testLog/i', $result);
+		$this->assertRegExp('/\[main\]/', $result);
+		$this->assertRegExp('/array/', $result);
+		$this->assertRegExp("/'whatever',/", $result);
+		$this->assertRegExp("/'here'/", $result);
+	}
+
+/**
+ * testDump method
+ *
+ * @return void
+ */
+	public function testDump() {
+		$var = array('People' => array(
+			array(
+				'name' => 'joeseph',
+				'coat' => 'technicolor',
+				'hair_color' => 'brown'
+			),
+			array(
+				'name' => 'Shaft',
+				'coat' => 'black',
+				'hair' => 'black'
+			)
+		));
+		ob_start();
+		Debugger::dump($var);
+		$result = ob_get_clean();
+		$expected = <<array(
+	'People' => array(
+		(int) 0 => array(
+			'name' => 'joeseph',
+			'coat' => 'technicolor',
+			'hair_color' => 'brown'
+		),
+		(int) 1 => array(
+			'name' => 'Shaft',
+			'coat' => 'black',
+			'hair' => 'black'
+		)
+	)
+)
+TEXT; + $this->assertTextEquals($expected, $result); + } + +/** + * test getInstance. + * + * @return void + */ + public function testGetInstance() { + $result = Debugger::getInstance(); + $this->assertInstanceOf('Debugger', $result); + + $result = Debugger::getInstance('DebuggerTestCaseDebugger'); + $this->assertInstanceOf('DebuggerTestCaseDebugger', $result); + + $result = Debugger::getInstance(); + $this->assertInstanceOf('DebuggerTestCaseDebugger', $result); + + $result = Debugger::getInstance('Debugger'); + $this->assertInstanceOf('Debugger', $result); + } + +/** + * testNoDbCredentials + * + * If a connection error occurs, the config variable is passed through exportVar + * *** our database login credentials such that they are never visible + * + * @return void + */ + public function testNoDbCredentials() { + $config = array( + 'datasource' => 'mysql', + 'persistent' => false, + 'host' => 'void.cakephp.org', + 'login' => 'cakephp-user', + 'password' => 'cakephp-password', + 'database' => 'cakephp-database', + 'prefix' => '' + ); + + $output = Debugger::exportVar($config); + + $expectedArray = array( + 'datasource' => 'mysql', + 'persistent' => false, + 'host' => '*****', + 'login' => '*****', + 'password' => '*****', + 'database' => '*****', + 'prefix' => '' + ); + $expected = Debugger::exportVar($expectedArray); + + $this->assertEquals($expected, $output); + } + +/** + * test trace exclude + * + * @return void + */ + public function testTraceExclude() { + $result = Debugger::trace(); + $this->assertRegExp('/^DebuggerTest::testTraceExclude/', $result); + + $result = Debugger::trace(array( + 'exclude' => array('DebuggerTest::testTraceExclude') + )); + $this->assertNotRegExp('/^DebuggerTest::testTraceExclude/', $result); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Utility/FileTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Utility/FileTest.php new file mode 100644 index 0000000..e63bcbd --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Utility/FileTest.php @@ -0,0 +1,556 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Utility + * @since CakePHP(tm) v 1.2.0.4206 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ +App::uses('File', 'Utility'); +App::uses('Folder', 'Utility'); + +/** + * FileTest class + * + * @package Cake.Test.Case.Utility + */ +class FileTest extends CakeTestCase { + +/** + * File property + * + * @var mixed null + */ + public $File = null; + +/** + * setup the test case + * + * @return void + */ + public function setUp() { + parent::setUp(); + $file = __FILE__; + $this->File = new File($file); + } + +/** + * tearDown method + * + * @return void + */ + public function tearDown() { + parent::tearDown(); + $this->File->close(); + unset($this->File); + + $Folder = new Folder(); + $Folder->delete(TMP . 'tests' . DS . 'permissions'); + } + +/** + * testBasic method + * + * @return void + */ + public function testBasic() { + $file = __FILE__; + + $result = $this->File->pwd(); + $expecting = $file; + $this->assertEquals($expecting, $result); + + $result = $this->File->name; + $expecting = basename(__FILE__); + $this->assertEquals($expecting, $result); + + $result = $this->File->info(); + $expecting = array( + 'dirname' => dirname(__FILE__), + 'basename' => basename(__FILE__), + 'extension' => 'php', + 'filename' => 'FileTest', + 'filesize' => filesize($file), + 'mime' => 'text/x-php' + ); + if (!function_exists('finfo_open') && (!function_exists('mime_content_type') || + function_exists('mime_content_type') && false === mime_content_type($this->File->pwd()))) { + $expecting['mime'] = false; + } + + $this->assertEquals($expecting, $result); + + $result = $this->File->ext(); + $expecting = 'php'; + $this->assertEquals($expecting, $result); + + $result = $this->File->name(); + $expecting = 'FileTest'; + $this->assertEquals($expecting, $result); + + $result = $this->File->md5(); + $expecting = md5_file($file); + $this->assertEquals($expecting, $result); + + $result = $this->File->md5(true); + $expecting = md5_file($file); + $this->assertEquals($expecting, $result); + + $result = $this->File->size(); + $expecting = filesize($file); + $this->assertEquals($expecting, $result); + + $result = $this->File->owner(); + $expecting = fileowner($file); + $this->assertEquals($expecting, $result); + + $result = $this->File->group(); + $expecting = filegroup($file); + $this->assertEquals($expecting, $result); + + $result = $this->File->Folder(); + $this->assertInstanceOf('Folder', $result); + } + +/** + * testPermission method + */ + public function testPermission() { + $this->skipIf(DIRECTORY_SEPARATOR === '\\', 'File permissions tests not supported on Windows.'); + + $dir = TMP . 'tests' . DS . 'permissions' . DS; + $Folder = new Folder($dir); + + $old = umask(); + + umask(0002); + $file = $dir . 'permission_' . uniqid(); + $expecting = decoct(0664 & ~umask()); + $File = new File($file, true); + $result = $File->perms(); + $this->assertEquals($expecting, $result); + $File->delete(); + + umask(0022); + $file = $dir . 'permission_' . uniqid(); + $expecting = decoct(0644 & ~umask()); + $File = new File($file, true); + $result = $File->perms(); + $this->assertEquals($expecting, $result); + $File->delete(); + + umask(0422); + $file = $dir . 'permission_' . uniqid(); + $expecting = decoct(0244 & ~umask()); + $File = new File($file, true); + $result = $File->perms(); + $this->assertEquals($expecting, $result); + $File->delete(); + + umask(0444); + $file = $dir . 'permission_' . uniqid(); + $expecting = decoct(0222 & ~umask()); + $File = new File($file, true); + $result = $File->perms(); + $this->assertEquals($expecting, $result); + $File->delete(); + + umask($old); + } + +/** + * testRead method + * + * @return void + */ + public function testRead() { + $file = __FILE__; + $this->File = new File($file); + + $result = $this->File->read(); + $expecting = file_get_contents(__FILE__); + $this->assertEquals($expecting, $result); + $this->assertTrue(!is_resource($this->File->handle)); + + $this->File->lock = true; + $result = $this->File->read(); + $expecting = file_get_contents(__FILE__); + $this->assertEquals(trim($expecting), $result); + $this->File->lock = null; + + $data = $expecting; + $expecting = substr($data, 0, 3); + $result = $this->File->read(3); + $this->assertEquals($expecting, $result); + $this->assertTrue(is_resource($this->File->handle)); + + $expecting = substr($data, 3, 3); + $result = $this->File->read(3); + $this->assertEquals($expecting, $result); + } + +/** + * testOffset method + * + * @return void + */ + public function testOffset() { + $this->File->close(); + + $result = $this->File->offset(); + $this->assertFalse($result); + + $this->assertFalse(is_resource($this->File->handle)); + $success = $this->File->offset(0); + $this->assertTrue($success); + $this->assertTrue(is_resource($this->File->handle)); + + $result = $this->File->offset(); + $expecting = 0; + $this->assertSame($result, $expecting); + + $data = file_get_contents(__FILE__); + $success = $this->File->offset(5); + $expecting = substr($data, 5, 3); + $result = $this->File->read(3); + $this->assertTrue($success); + $this->assertEquals($expecting, $result); + + $result = $this->File->offset(); + $expecting = 5 + 3; + $this->assertSame($result, $expecting); + } + +/** + * testOpen method + * + * @return void + */ + public function testOpen() { + $this->File->handle = null; + + $r = $this->File->open(); + $this->assertTrue(is_resource($this->File->handle)); + $this->assertTrue($r); + + $handle = $this->File->handle; + $r = $this->File->open(); + $this->assertTrue($r); + $this->assertTrue($handle === $this->File->handle); + $this->assertTrue(is_resource($this->File->handle)); + + $r = $this->File->open('r', true); + $this->assertTrue($r); + $this->assertFalse($handle === $this->File->handle); + $this->assertTrue(is_resource($this->File->handle)); + } + +/** + * testClose method + * + * @return void + */ + public function testClose() { + $this->File->handle = null; + $this->assertFalse(is_resource($this->File->handle)); + $this->assertTrue($this->File->close()); + $this->assertFalse(is_resource($this->File->handle)); + + $this->File->handle = fopen(__FILE__, 'r'); + $this->assertTrue(is_resource($this->File->handle)); + $this->assertTrue($this->File->close()); + $this->assertFalse(is_resource($this->File->handle)); + } + +/** + * testCreate method + * + * @return void + */ + public function testCreate() { + $tmpFile = TMP . 'tests' . DS . 'cakephp.file.test.tmp'; + $File = new File($tmpFile, true, 0777); + $this->assertTrue($File->exists()); + } + +/** + * testOpeningNonExistentFileCreatesIt method + * + * @return void + */ + public function testOpeningNonExistentFileCreatesIt() { + $someFile = new File(TMP . 'some_file.txt', false); + $this->assertTrue($someFile->open()); + $this->assertEquals('', $someFile->read()); + $someFile->close(); + $someFile->delete(); + } + +/** + * testPrepare method + * + * @return void + */ + public function testPrepare() { + $string = "some\nvery\ncool\r\nteststring here\n\n\nfor\r\r\n\n\r\n\nhere"; + if (DS == '\\') { + $expected = "some\r\nvery\r\ncool\r\nteststring here\r\n\r\n\r\n"; + $expected .= "for\r\n\r\n\r\n\r\n\r\nhere"; + } else { + $expected = "some\nvery\ncool\nteststring here\n\n\nfor\n\n\n\n\nhere"; + } + $this->assertSame(File::prepare($string), $expected); + + $expected = "some\r\nvery\r\ncool\r\nteststring here\r\n\r\n\r\n"; + $expected .= "for\r\n\r\n\r\n\r\n\r\nhere"; + $this->assertSame(File::prepare($string, true), $expected); + } + +/** + * testReadable method + * + * @return void + */ + public function testReadable() { + $someFile = new File(TMP . 'some_file.txt', false); + $this->assertTrue($someFile->open()); + $this->assertTrue($someFile->readable()); + $someFile->close(); + $someFile->delete(); + } + +/** + * testWritable method + * + * @return void + */ + public function testWritable() { + $someFile = new File(TMP . 'some_file.txt', false); + $this->assertTrue($someFile->open()); + $this->assertTrue($someFile->writable()); + $someFile->close(); + $someFile->delete(); + } + +/** + * testExecutable method + * + * @return void + */ + public function testExecutable() { + $someFile = new File(TMP . 'some_file.txt', false); + $this->assertTrue($someFile->open()); + $this->assertFalse($someFile->executable()); + $someFile->close(); + $someFile->delete(); + } + +/** + * testLastAccess method + * + * @return void + */ + public function testLastAccess() { + $ts = time(); + $someFile = new File(TMP . 'some_file.txt', false); + $this->assertFalse($someFile->lastAccess()); + $this->assertTrue($someFile->open()); + $this->assertTrue($someFile->lastAccess() >= $ts); + $someFile->close(); + $someFile->delete(); + } + +/** + * testLastChange method + * + * @return void + */ + public function testLastChange() { + $ts = time(); + $someFile = new File(TMP . 'some_file.txt', false); + $this->assertFalse($someFile->lastChange()); + $this->assertTrue($someFile->open('r+')); + $this->assertTrue($someFile->lastChange() >= $ts); + $someFile->write('something'); + $this->assertTrue($someFile->lastChange() >= $ts); + $someFile->close(); + $someFile->delete(); + } + +/** + * testWrite method + * + * @return void + */ + public function testWrite() { + if (!$tmpFile = $this->_getTmpFile()) { + return false; + }; + if (file_exists($tmpFile)) { + unlink($tmpFile); + } + + $TmpFile = new File($tmpFile); + $this->assertFalse(file_exists($tmpFile)); + $this->assertFalse(is_resource($TmpFile->handle)); + + $testData = array('CakePHP\'s', ' test suite', ' was here ...', ''); + foreach ($testData as $data) { + $r = $TmpFile->write($data); + $this->assertTrue($r); + $this->assertTrue(file_exists($tmpFile)); + $this->assertEquals($data, file_get_contents($tmpFile)); + $this->assertTrue(is_resource($TmpFile->handle)); + $TmpFile->close(); + + } + unlink($tmpFile); + } + +/** + * testAppend method + * + * @return void + */ + public function testAppend() { + if (!$tmpFile = $this->_getTmpFile()) { + return false; + }; + if (file_exists($tmpFile)) { + unlink($tmpFile); + } + + $TmpFile = new File($tmpFile); + $this->assertFalse(file_exists($tmpFile)); + + $fragments = array('CakePHP\'s', ' test suite', ' was here ...', ''); + $data = null; + foreach ($fragments as $fragment) { + $r = $TmpFile->append($fragment); + $this->assertTrue($r); + $this->assertTrue(file_exists($tmpFile)); + $data = $data . $fragment; + $this->assertEquals($data, file_get_contents($tmpFile)); + $TmpFile->close(); + } + } + +/** + * testDelete method + * + * @return void + */ + public function testDelete() { + if (!$tmpFile = $this->_getTmpFile()) { + return false; + } + + if (!file_exists($tmpFile)) { + touch($tmpFile); + } + $TmpFile = new File($tmpFile); + $this->assertTrue(file_exists($tmpFile)); + $result = $TmpFile->delete(); + $this->assertTrue($result); + $this->assertFalse(file_exists($tmpFile)); + + $TmpFile = new File('/this/does/not/exist'); + $result = $TmpFile->delete(); + $this->assertFalse($result); + } + +/** + * Windows has issues unlinking files if there are + * active filehandles open. + * + * @return void + */ + public function testDeleteAfterRead() { + if (!$tmpFile = $this->_getTmpFile()) { + return false; + } + if (!file_exists($tmpFile)) { + touch($tmpFile); + } + $File = new File($tmpFile); + $File->read(); + $this->assertTrue($File->delete()); + } + +/** + * testCopy method + * + * @return void + */ + public function testCopy() { + $dest = TMP . 'tests' . DS . 'cakephp.file.test.tmp'; + $file = __FILE__; + $this->File = new File($file); + $result = $this->File->copy($dest); + $this->assertTrue($result); + + $result = $this->File->copy($dest, true); + $this->assertTrue($result); + + $result = $this->File->copy($dest, false); + $this->assertFalse($result); + + $this->File->close(); + unlink($dest); + + $TmpFile = new File('/this/does/not/exist'); + $result = $TmpFile->copy($dest); + $this->assertFalse($result); + + $TmpFile->close(); + } + +/** + * Test mime() + * + * @return void + */ + public function testMime() { + $this->skipIf(!function_exists('finfo_open') && !function_exists('mime_content_type'), 'Not able to read mime type'); + $path = CAKE . 'Test' . DS . 'test_app' . DS . 'webroot' . DS . 'img' . DS . 'cake.power.gif'; + $file = new File($path); + $expected = 'image/gif'; + if (function_exists('mime_content_type') && false === mime_content_type($file->pwd())) { + $expected = false; + } + $this->assertEquals($expected, $file->mime()); + } + +/** + * getTmpFile method + * + * @param bool $paintSkip + * @return void + */ + protected function _getTmpFile($paintSkip = true) { + $tmpFile = TMP . 'tests' . DS . 'cakephp.file.test.tmp'; + if (is_writable(dirname($tmpFile)) && (!file_exists($tmpFile) || is_writable($tmpFile))) { + return $tmpFile; + }; + + if ($paintSkip) { + $trace = debug_backtrace(); + $caller = $trace[0]['function']; + $shortPath = dirname($tmpFile); + + $message = __d('cake_dev', '[FileTest] Skipping %s because "%s" not writeable!', $caller, $shortPath); + $this->markTestSkipped($message); + } + return false; + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Utility/FolderTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Utility/FolderTest.php new file mode 100644 index 0000000..76ee08a --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Utility/FolderTest.php @@ -0,0 +1,937 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Utility + * @since CakePHP(tm) v 1.2.0.4206 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ +App::uses('Folder', 'Utility'); +App::uses('File', 'Utility'); + +/** + * FolderTest class + * + * @package Cake.Test.Case.Utility + */ +class FolderTest extends CakeTestCase { + + protected static $_tmp = array(); + +/** + * Save the directory names in TMP + * + * @return void + */ + public static function setUpBeforeClass() { + foreach (scandir(TMP) as $file) { + if (is_dir(TMP . $file) && !in_array($file, array('.', '..'))) { + self::$_tmp[] = $file; + } + } + } + +/** + * setUp clearstatcache() to flush file descriptors. + * + * @return void + */ + public function setUp() { + parent::setUp(); + clearstatcache(); + } + +/** + * Restore the TMP directory to its original state. + * + * @return void + */ + public function tearDown() { + $exclude = array_merge(self::$_tmp, array('.', '..')); + foreach (scandir(TMP) as $dir) { + if (is_dir(TMP . $dir) && !in_array($dir, $exclude)) { + $iterator = new RecursiveDirectoryIterator(TMP . $dir); + foreach (new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::CHILD_FIRST) as $file) { + if ($file->isFile() || $file->isLink()) { + unlink($file->getPathname()); + } elseif ($file->isDir() && !in_array($file->getFilename(), array('.', '..'))) { + rmdir($file->getPathname()); + } + } + rmdir(TMP . $dir); + } + } + } + +/** + * testBasic method + * + * @return void + */ + public function testBasic() { + $path = dirname(__FILE__); + $Folder = new Folder($path); + + $result = $Folder->pwd(); + $this->assertEquals($path, $result); + + $result = Folder::addPathElement($path, 'test'); + $expected = $path . DS . 'test'; + $this->assertEquals($expected, $result); + + $result = $Folder->cd(ROOT); + $expected = ROOT; + $this->assertEquals($expected, $result); + + $result = $Folder->cd(ROOT . DS . 'non-existent'); + $this->assertFalse($result); + } + +/** + * testInPath method + * + * @return void + */ + public function testInPath() { + $path = dirname(dirname(__FILE__)); + $inside = dirname($path) . DS; + + $Folder = new Folder($path); + + $result = $Folder->pwd(); + $this->assertEquals($path, $result); + + $result = Folder::isSlashTerm($inside); + $this->assertTrue($result); + + $result = $Folder->realpath('Test/'); + $this->assertEquals($path . DS . 'Test' . DS, $result); + + $result = $Folder->inPath('Test' . DS); + $this->assertTrue($result); + + $result = $Folder->inPath(DS . 'non-existing' . $inside); + $this->assertFalse($result); + + $result = $Folder->inPath($path . DS . 'Model', true); + $this->assertTrue($result); + } + +/** + * test creation of single and multiple paths. + * + * @return void + */ + public function testCreation() { + $Folder = new Folder(TMP . 'tests'); + $result = $Folder->create(TMP . 'tests' . DS . 'first' . DS . 'second' . DS . 'third'); + $this->assertTrue($result); + + rmdir(TMP . 'tests' . DS . 'first' . DS . 'second' . DS . 'third'); + rmdir(TMP . 'tests' . DS . 'first' . DS . 'second'); + rmdir(TMP . 'tests' . DS . 'first'); + + $Folder = new Folder(TMP . 'tests'); + $result = $Folder->create(TMP . 'tests' . DS . 'first'); + $this->assertTrue($result); + rmdir(TMP . 'tests' . DS . 'first'); + } + +/** + * test that creation of folders with trailing ds works + * + * @return void + */ + public function testCreateWithTrailingDs() { + $Folder = new Folder(TMP); + $path = TMP . 'tests' . DS . 'trailing' . DS . 'dir' . DS; + $result = $Folder->create($path); + $this->assertTrue($result); + + $this->assertTrue(is_dir($path), 'Folder was not made'); + + $Folder = new Folder(TMP . 'tests' . DS . 'trailing'); + $this->assertTrue($Folder->delete()); + } + +/** + * test recursive directory create failure. + * + * @return void + */ + public function testRecursiveCreateFailure() { + $this->skipIf(DIRECTORY_SEPARATOR === '\\', 'Cant perform operations using permissions on windows.'); + + $path = TMP . 'tests' . DS . 'one'; + mkdir($path); + chmod($path, '0444'); + + try { + $Folder = new Folder($path); + $result = $Folder->create($path . DS . 'two' . DS . 'three'); + $this->assertFalse($result); + } catch (PHPUnit_Framework_Error $e) { + $this->assertTrue(true); + } + + chmod($path, '0777'); + rmdir($path); + } + +/** + * testOperations method + * + * @return void + */ + public function testOperations() { + $path = CAKE . 'Console' . DS . 'Templates' . DS . 'skel'; + $Folder = new Folder($path); + + $result = is_dir($Folder->pwd()); + $this->assertTrue($result); + + $new = TMP . 'test_folder_new'; + $result = $Folder->create($new); + $this->assertTrue($result); + + $copy = TMP . 'test_folder_copy'; + $result = $Folder->copy($copy); + $this->assertTrue($result); + + $copy = TMP . 'test_folder_copy'; + $result = $Folder->copy($copy); + $this->assertTrue($result); + + $copy = TMP . 'test_folder_copy'; + $result = $Folder->chmod($copy, 0755, false); + $this->assertTrue($result); + + $result = $Folder->cd($copy); + $this->assertTrue((bool)$result); + + $mv = TMP . 'test_folder_mv'; + $result = $Folder->move($mv); + $this->assertTrue($result); + + $mv = TMP . 'test_folder_mv_2'; + $result = $Folder->move($mv); + $this->assertTrue($result); + + $result = $Folder->delete($new); + $this->assertTrue($result); + + $result = $Folder->delete($mv); + $this->assertTrue($result); + + $result = $Folder->delete($mv); + $this->assertTrue($result); + + $new = APP . 'index.php'; + $result = $Folder->create($new); + $this->assertFalse($result); + + $expected = $new . ' is a file'; + $result = $Folder->errors(); + $this->assertEquals($expected, $result[0]); + + $new = TMP . 'test_folder_new'; + $result = $Folder->create($new); + $this->assertTrue($result); + + $result = $Folder->cd($new); + $this->assertTrue((bool)$result); + + $result = $Folder->delete(); + $this->assertTrue($result); + + $Folder = new Folder('non-existent'); + $result = $Folder->pwd(); + $this->assertNull($result); + } + +/** + * testChmod method + * + * @return void + */ + public function testChmod() { + $this->skipIf(DIRECTORY_SEPARATOR === '\\', 'Folder permissions tests not supported on Windows.'); + + $path = TMP; + $Folder = new Folder($path); + + $subdir = 'test_folder_new'; + $new = TMP . $subdir; + + $this->assertTrue($Folder->create($new)); + $this->assertTrue($Folder->create($new . DS . 'test1')); + $this->assertTrue($Folder->create($new . DS . 'test2')); + + $filePath = $new . DS . 'test1.php'; + $File = new File($filePath); + $this->assertTrue($File->create()); + + $filePath = $new . DS . 'skip_me.php'; + $File = new File($filePath); + $this->assertTrue($File->create()); + + $this->assertTrue($Folder->chmod($new, 0755, true)); + $perms = substr(sprintf('%o', fileperms($new . DS . 'test2')), -4); + $this->assertEquals('0755', $perms); + + $this->assertTrue($Folder->chmod($new, 0744, true, array('skip_me.php', 'test2'))); + + $perms = substr(sprintf('%o', fileperms($new . DS . 'test2')), -4); + $this->assertEquals('0755', $perms); + + $perms = substr(sprintf('%o', fileperms($new . DS . 'test1')), -4); + $this->assertEquals('0744', $perms); + + $Folder->delete($new); + } + +/** + * testRealPathForWebroot method + * + * @return void + */ + public function testRealPathForWebroot() { + $Folder = new Folder('files/'); + $this->assertEquals(realpath('files/'), $Folder->path); + } + +/** + * testZeroAsDirectory method + * + * @return void + */ + public function testZeroAsDirectory() { + $Folder = new Folder(TMP); + $new = TMP . '0'; + $this->assertTrue($Folder->create($new)); + + $result = $Folder->read(true, true); + $expected = array('0', 'cache', 'logs', 'sessions', 'tests'); + $this->assertEquals($expected, $result[0]); + + $result = $Folder->read(true, array('logs')); + $expected = array('0', 'cache', 'sessions', 'tests'); + $this->assertEquals($expected, $result[0]); + + $result = $Folder->delete($new); + $this->assertTrue($result); + } + +/** + * test Adding path elements to a path + * + * @return void + */ + public function testAddPathElement() { + $result = Folder::addPathElement(DS . 'some' . DS . 'dir', 'another_path'); + $this->assertEquals(DS . 'some' . DS . 'dir' . DS . 'another_path', $result); + + $result = Folder::addPathElement(DS . 'some' . DS . 'dir' . DS, 'another_path'); + $this->assertEquals(DS . 'some' . DS . 'dir' . DS . 'another_path', $result); + } + +/** + * testFolderRead method + * + * @return void + */ + public function testFolderRead() { + $Folder = new Folder(TMP); + + $expected = array('cache', 'logs', 'sessions', 'tests'); + $result = $Folder->read(true, true); + $this->assertEquals($expected, $result[0]); + + $Folder->path = TMP . 'non-existent'; + $expected = array(array(), array()); + $result = $Folder->read(true, true); + $this->assertEquals($expected, $result); + } + +/** + * testFolderReadWithHiddenFiles method + * + * @return void + */ + public function testFolderReadWithHiddenFiles() { + $this->skipIf(!is_writeable(TMP), 'Cant test Folder::read with hidden files unless the tmp folder is writable.'); + + $Folder = new Folder(TMP . 'folder_tree_hidden', true, 0777); + mkdir($Folder->path . DS . '.svn'); + mkdir($Folder->path . DS . 'some_folder'); + touch($Folder->path . DS . 'not_hidden.txt'); + touch($Folder->path . DS . '.hidden.txt'); + + $expected = array( + array('some_folder'), + array('not_hidden.txt'), + ); + $result = $Folder->read(true, true); + $this->assertEquals($expected, $result); + + $expected = array( + array( + '.svn', + 'some_folder' + ), + array( + '.hidden.txt', + 'not_hidden.txt' + ), + ); + $result = $Folder->read(true); + $this->assertEquals($expected, $result); + } + +/** + * testFolderTree method + * + * @return void + */ + public function testFolderTree() { + $Folder = new Folder(); + $expected = array( + array( + CAKE . 'Config', + CAKE . 'Config' . DS . 'unicode', + CAKE . 'Config' . DS . 'unicode' . DS . 'casefolding' + ), + array( + CAKE . 'Config' . DS . 'config.php', + CAKE . 'Config' . DS . 'unicode' . DS . 'casefolding' . DS . '0080_00ff.php', + CAKE . 'Config' . DS . 'unicode' . DS . 'casefolding' . DS . '0100_017f.php', + CAKE . 'Config' . DS . 'unicode' . DS . 'casefolding' . DS . '0180_024F.php', + CAKE . 'Config' . DS . 'unicode' . DS . 'casefolding' . DS . '0250_02af.php', + CAKE . 'Config' . DS . 'unicode' . DS . 'casefolding' . DS . '0370_03ff.php', + CAKE . 'Config' . DS . 'unicode' . DS . 'casefolding' . DS . '0400_04ff.php', + CAKE . 'Config' . DS . 'unicode' . DS . 'casefolding' . DS . '0500_052f.php', + CAKE . 'Config' . DS . 'unicode' . DS . 'casefolding' . DS . '0530_058f.php', + CAKE . 'Config' . DS . 'unicode' . DS . 'casefolding' . DS . '1e00_1eff.php', + CAKE . 'Config' . DS . 'unicode' . DS . 'casefolding' . DS . '1f00_1fff.php', + CAKE . 'Config' . DS . 'unicode' . DS . 'casefolding' . DS . '2100_214f.php', + CAKE . 'Config' . DS . 'unicode' . DS . 'casefolding' . DS . '2150_218f.php', + CAKE . 'Config' . DS . 'unicode' . DS . 'casefolding' . DS . '2460_24ff.php', + CAKE . 'Config' . DS . 'unicode' . DS . 'casefolding' . DS . '2c00_2c5f.php', + CAKE . 'Config' . DS . 'unicode' . DS . 'casefolding' . DS . '2c60_2c7f.php', + CAKE . 'Config' . DS . 'unicode' . DS . 'casefolding' . DS . '2c80_2cff.php', + CAKE . 'Config' . DS . 'unicode' . DS . 'casefolding' . DS . 'ff00_ffef.php' + ) + ); + + $result = $Folder->tree(CAKE . 'Config', false); + $this->assertSame(array(), array_diff($expected[0], $result[0])); + $this->assertSame(array(), array_diff($result[0], $expected[0])); + + $result = $Folder->tree(CAKE . 'Config', false, 'dir'); + $this->assertSame(array(), array_diff($expected[0], $result)); + $this->assertSame(array(), array_diff($expected[0], $result)); + + $result = $Folder->tree(CAKE . 'Config', false, 'files'); + $this->assertSame(array(), array_diff($expected[1], $result)); + $this->assertSame(array(), array_diff($expected[1], $result)); + } + +/** + * testFolderTreeWithHiddenFiles method + * + * @return void + */ + public function testFolderTreeWithHiddenFiles() { + $this->skipIf(!is_writeable(TMP), 'Can\'t test Folder::tree with hidden files unless the tmp folder is writable.'); + + $Folder = new Folder(TMP . 'folder_tree_hidden', true, 0777); + mkdir($Folder->path . DS . '.svn', 0777, true); + touch($Folder->path . DS . '.svn' . DS . 'InHiddenFolder.php'); + mkdir($Folder->path . DS . '.svn' . DS . 'inhiddenfolder'); + touch($Folder->path . DS . '.svn' . DS . 'inhiddenfolder' . DS . 'NestedInHiddenFolder.php'); + touch($Folder->path . DS . 'not_hidden.txt'); + touch($Folder->path . DS . '.hidden.txt'); + mkdir($Folder->path . DS . 'visible_folder' . DS . '.git', 0777, true); + + $expected = array( + array( + $Folder->path, + $Folder->path . DS . 'visible_folder', + ), + array( + $Folder->path . DS . 'not_hidden.txt', + ), + ); + + $result = $Folder->tree(null, true); + $this->assertEquals($expected, $result); + + $result = $Folder->tree(null, array('.')); + $this->assertEquals($expected, $result); + + $expected = array( + array( + $Folder->path, + $Folder->path . DS . 'visible_folder', + $Folder->path . DS . 'visible_folder' . DS . '.git', + $Folder->path . DS . '.svn', + $Folder->path . DS . '.svn' . DS . 'inhiddenfolder', + ), + array( + $Folder->path . DS . 'not_hidden.txt', + $Folder->path . DS . '.hidden.txt', + $Folder->path . DS . '.svn' . DS . 'inhiddenfolder' . DS . 'NestedInHiddenFolder.php', + $Folder->path . DS . '.svn' . DS . 'InHiddenFolder.php', + ), + ); + + $result = $Folder->tree(null, false); + sort($result[0]); + sort($expected[0]); + sort($result[1]); + sort($expected[1]); + $this->assertEquals($expected, $result); + + $Folder->delete(); + } + +/** + * testWindowsPath method + * + * @return void + */ + public function testWindowsPath() { + $this->assertFalse(Folder::isWindowsPath('0:\\cake\\is\\awesome')); + $this->assertTrue(Folder::isWindowsPath('C:\\cake\\is\\awesome')); + $this->assertTrue(Folder::isWindowsPath('d:\\cake\\is\\awesome')); + $this->assertTrue(Folder::isWindowsPath('\\\\vmware-host\\Shared Folders\\file')); + } + +/** + * testIsAbsolute method + * + * @return void + */ + public function testIsAbsolute() { + $this->assertFalse(Folder::isAbsolute('path/to/file')); + $this->assertFalse(Folder::isAbsolute('cake/')); + $this->assertFalse(Folder::isAbsolute('path\\to\\file')); + $this->assertFalse(Folder::isAbsolute('0:\\path\\to\\file')); + $this->assertFalse(Folder::isAbsolute('\\path/to/file')); + $this->assertFalse(Folder::isAbsolute('\\path\\to\\file')); + + $this->assertTrue(Folder::isAbsolute('/usr/local')); + $this->assertTrue(Folder::isAbsolute('//path/to/file')); + $this->assertTrue(Folder::isAbsolute('C:\\cake')); + $this->assertTrue(Folder::isAbsolute('C:\\path\\to\\file')); + $this->assertTrue(Folder::isAbsolute('d:\\path\\to\\file')); + $this->assertTrue(Folder::isAbsolute('\\\\vmware-host\\Shared Folders\\file')); + } + +/** + * testIsSlashTerm method + * + * @return void + */ + public function testIsSlashTerm() { + $this->assertFalse(Folder::isSlashTerm('cake')); + + $this->assertTrue(Folder::isSlashTerm('C:\\cake\\')); + $this->assertTrue(Folder::isSlashTerm('/usr/local/')); + } + +/** + * testStatic method + * + * @return void + */ + public function testSlashTerm() { + $result = Folder::slashTerm('/path/to/file'); + $this->assertEquals('/path/to/file/', $result); + } + +/** + * testNormalizePath method + * + * @return void + */ + public function testNormalizePath() { + $path = '/path/to/file'; + $result = Folder::normalizePath($path); + $this->assertEquals('/', $result); + + $path = '\\path\\\to\\\file'; + $result = Folder::normalizePath($path); + $this->assertEquals('/', $result); + + $path = 'C:\\path\\to\\file'; + $result = Folder::normalizePath($path); + $this->assertEquals('\\', $result); + } + +/** + * correctSlashFor method + * + * @return void + */ + public function testCorrectSlashFor() { + $path = '/path/to/file'; + $result = Folder::correctSlashFor($path); + $this->assertEquals('/', $result); + + $path = '\\path\\to\\file'; + $result = Folder::correctSlashFor($path); + $this->assertEquals('/', $result); + + $path = 'C:\\path\to\\file'; + $result = Folder::correctSlashFor($path); + $this->assertEquals('\\', $result); + } + +/** + * testInCakePath method + * + * @return void + */ + public function testInCakePath() { + $Folder = new Folder(); + $Folder->cd(ROOT); + $path = 'C:\\path\\to\\file'; + $result = $Folder->inCakePath($path); + $this->assertFalse($result); + + $path = ROOT; + $Folder->cd(ROOT); + $result = $Folder->inCakePath($path); + $this->assertFalse($result); + + $path = DS . 'lib' . DS . 'Cake' . DS . 'Config'; + $Folder->cd(ROOT . DS . 'lib' . DS . 'Cake' . DS . 'Config'); + $result = $Folder->inCakePath($path); + $this->assertTrue($result); + } + +/** + * testFind method + * + * @return void + */ + public function testFind() { + $Folder = new Folder(); + $Folder->cd(CAKE . 'Config'); + $result = $Folder->find(); + $expected = array('config.php'); + $this->assertSame(array_diff($expected, $result), array()); + $this->assertSame(array_diff($expected, $result), array()); + + $result = $Folder->find('.*', true); + $expected = array('config.php', 'routes.php'); + $this->assertSame($expected, $result); + + $result = $Folder->find('.*\.php'); + $expected = array('config.php'); + $this->assertSame(array_diff($expected, $result), array()); + $this->assertSame(array_diff($expected, $result), array()); + + $result = $Folder->find('.*\.php', true); + $expected = array('config.php', 'routes.php'); + $this->assertSame($expected, $result); + + $result = $Folder->find('.*ig\.php'); + $expected = array('config.php'); + $this->assertSame($expected, $result); + + $result = $Folder->find('config\.php'); + $expected = array('config.php'); + $this->assertSame($expected, $result); + + $Folder->cd(TMP); + $File = new File($Folder->pwd() . DS . 'paths.php', true); + $Folder->create($Folder->pwd() . DS . 'testme'); + $Folder->cd('testme'); + $result = $Folder->find('paths\.php'); + $expected = array(); + $this->assertSame($expected, $result); + + $Folder->cd($Folder->pwd() . '/..'); + $result = $Folder->find('paths\.php'); + $expected = array('paths.php'); + $this->assertSame($expected, $result); + + $Folder->cd(TMP); + $Folder->delete($Folder->pwd() . DS . 'testme'); + $File->delete(); + } + +/** + * testFindRecursive method + * + * @return void + */ + public function testFindRecursive() { + $Folder = new Folder(); + $Folder->cd(CAKE); + $result = $Folder->findRecursive('(config|paths)\.php'); + $expected = array( + CAKE . 'Config' . DS . 'config.php' + ); + $this->assertSame(array_diff($expected, $result), array()); + $this->assertSame(array_diff($expected, $result), array()); + + $result = $Folder->findRecursive('(config|paths)\.php', true); + $expected = array( + CAKE . 'Config' . DS . 'config.php' + ); + $this->assertSame($expected, $result); + + $Folder->cd(TMP); + $Folder->create($Folder->pwd() . DS . 'testme'); + $Folder->cd('testme'); + $File = new File($Folder->pwd() . DS . 'paths.php'); + $File->create(); + $Folder->cd(TMP . 'sessions'); + $result = $Folder->findRecursive('paths\.php'); + $expected = array(); + $this->assertSame($expected, $result); + + $Folder->cd(TMP . 'testme'); + $File = new File($Folder->pwd() . DS . 'my.php'); + $File->create(); + $Folder->cd($Folder->pwd() . '/../..'); + + $result = $Folder->findRecursive('(paths|my)\.php'); + $expected = array( + TMP . 'testme' . DS . 'my.php', + TMP . 'testme' . DS . 'paths.php' + ); + $this->assertSame(array_diff($expected, $result), array()); + $this->assertSame(array_diff($expected, $result), array()); + + $result = $Folder->findRecursive('(paths|my)\.php', true); + $expected = array( + TMP . 'testme' . DS . 'my.php', + TMP . 'testme' . DS . 'paths.php' + ); + $this->assertSame($expected, $result); + + $Folder->cd(CAKE . 'Config'); + $Folder->cd(TMP); + $Folder->delete($Folder->pwd() . DS . 'testme'); + $File->delete(); + } + +/** + * testConstructWithNonExistentPath method + * + * @return void + */ + public function testConstructWithNonExistentPath() { + $Folder = new Folder(TMP . 'config_non_existent', true); + $this->assertTrue(is_dir(TMP . 'config_non_existent')); + $Folder->cd(TMP); + $Folder->delete($Folder->pwd() . 'config_non_existent'); + } + +/** + * testDirSize method + * + * @return void + */ + public function testDirSize() { + $Folder = new Folder(TMP . 'config_non_existent', true); + $this->assertEquals(0, $Folder->dirSize()); + + $File = new File($Folder->pwd() . DS . 'my.php', true, 0777); + $File->create(); + $File->write('something here'); + $File->close(); + $this->assertEquals(14, $Folder->dirSize()); + + $Folder->cd(TMP); + $Folder->delete($Folder->pwd() . 'config_non_existent'); + } + +/** + * testDelete method + * + * @return void + */ + public function testDelete() { + $path = TMP . 'folder_delete_test'; + mkdir($path); + touch($path . DS . 'file_1'); + mkdir($path . DS . 'level_1_1'); + touch($path . DS . 'level_1_1' . DS . 'file_1_1'); + mkdir($path . DS . 'level_1_1' . DS . 'level_2_1'); + touch($path . DS . 'level_1_1' . DS . 'level_2_1' . DS . 'file_2_1'); + touch($path . DS . 'level_1_1' . DS . 'level_2_1' . DS . 'file_2_2'); + mkdir($path . DS . 'level_1_1' . DS . 'level_2_2'); + + $Folder = new Folder($path, true); + $return = $Folder->delete(); + $this->assertTrue($return); + + $messages = $Folder->messages(); + $errors = $Folder->errors(); + $this->assertEquals(array(), $errors); + + $expected = array( + $path . DS . 'file_1 removed', + $path . DS . 'level_1_1' . DS . 'file_1_1 removed', + $path . DS . 'level_1_1' . DS . 'level_2_1' . DS . 'file_2_1 removed', + $path . DS . 'level_1_1' . DS . 'level_2_1' . DS . 'file_2_2 removed', + $path . DS . 'level_1_1' . DS . 'level_2_1 removed', + $path . DS . 'level_1_1' . DS . 'level_2_2 removed', + $path . DS . 'level_1_1 removed', + $path . ' removed' + ); + sort($expected); + sort($messages); + $this->assertEquals($expected, $messages); + } + +/** + * testCopy method + * + * Verify that directories and files are copied recursively + * even if the destination directory already exists. + * Subdirectories existing in both destination and source directory + * are skipped and not merged or overwritten. + * + * @return void + */ + public function testCopy() { + $path = TMP . 'folder_test'; + $folderOne = $path . DS . 'folder1'; + $folderTwo = $folderOne . DS . 'folder2'; + $folderThree = $path . DS . 'folder3'; + $fileOne = $folderOne . DS . 'file1.php'; + $fileTwo = $folderTwo . DS . 'file2.php'; + + new Folder($path, true); + new Folder($folderOne, true); + new Folder($folderTwo, true); + new Folder($folderThree, true); + touch($fileOne); + touch($fileTwo); + + $Folder = new Folder($folderOne); + $result = $Folder->copy($folderThree); + $this->assertTrue($result); + $this->assertTrue(file_exists($folderThree . DS . 'file1.php')); + $this->assertTrue(file_exists($folderThree . DS . 'folder2' . DS . 'file2.php')); + + $Folder = new Folder($folderThree); + $Folder->delete(); + + $Folder = new Folder($folderOne); + $result = $Folder->copy($folderThree); + $this->assertTrue($result); + $this->assertTrue(file_exists($folderThree . DS . 'file1.php')); + $this->assertTrue(file_exists($folderThree . DS . 'folder2' . DS . 'file2.php')); + + $Folder = new Folder($folderThree); + $Folder->delete(); + + new Folder($folderThree, true); + new Folder($folderThree . DS . 'folder2', true); + file_put_contents($folderThree . DS . 'folder2' . DS . 'file2.php', 'untouched'); + + $Folder = new Folder($folderOne); + $result = $Folder->copy($folderThree); + $this->assertTrue($result); + $this->assertTrue(file_exists($folderThree . DS . 'file1.php')); + $this->assertEquals('untouched', file_get_contents($folderThree . DS . 'folder2' . DS . 'file2.php')); + + $Folder = new Folder($path); + $Folder->delete(); + } + +/** + * testMove method + * + * Verify that directories and files are moved recursively + * even if the destination directory already exists. + * Subdirectories existing in both destination and source directory + * are skipped and not merged or overwritten. + * + * @return void + */ + public function testMove() { + $path = TMP . 'folder_test'; + $folderOne = $path . DS . 'folder1'; + $folderTwo = $folderOne . DS . 'folder2'; + $folderThree = $path . DS . 'folder3'; + $fileOne = $folderOne . DS . 'file1.php'; + $fileTwo = $folderTwo . DS . 'file2.php'; + + new Folder($path, true); + new Folder($folderOne, true); + new Folder($folderTwo, true); + new Folder($folderThree, true); + touch($fileOne); + touch($fileTwo); + + $Folder = new Folder($folderOne); + $result = $Folder->move($folderThree); + $this->assertTrue($result); + $this->assertTrue(file_exists($folderThree . DS . 'file1.php')); + $this->assertTrue(is_dir($folderThree . DS . 'folder2')); + $this->assertTrue(file_exists($folderThree . DS . 'folder2' . DS . 'file2.php')); + $this->assertFalse(file_exists($fileOne)); + $this->assertFalse(file_exists($folderTwo)); + $this->assertFalse(file_exists($fileTwo)); + + $Folder = new Folder($folderThree); + $Folder->delete(); + + new Folder($folderOne, true); + new Folder($folderTwo, true); + touch($fileOne); + touch($fileTwo); + + $Folder = new Folder($folderOne); + $result = $Folder->move($folderThree); + $this->assertTrue($result); + $this->assertTrue(file_exists($folderThree . DS . 'file1.php')); + $this->assertTrue(is_dir($folderThree . DS . 'folder2')); + $this->assertTrue(file_exists($folderThree . DS . 'folder2' . DS . 'file2.php')); + $this->assertFalse(file_exists($fileOne)); + $this->assertFalse(file_exists($folderTwo)); + $this->assertFalse(file_exists($fileTwo)); + + $Folder = new Folder($folderThree); + $Folder->delete(); + + new Folder($folderOne, true); + new Folder($folderTwo, true); + new Folder($folderThree, true); + new Folder($folderThree . DS . 'folder2', true); + touch($fileOne); + touch($fileTwo); + file_put_contents($folderThree . DS . 'folder2' . DS . 'file2.php', 'untouched'); + + $Folder = new Folder($folderOne); + $result = $Folder->move($folderThree); + $this->assertTrue($result); + $this->assertTrue(file_exists($folderThree . DS . 'file1.php')); + $this->assertEquals('untouched', file_get_contents($folderThree . DS . 'folder2' . DS . 'file2.php')); + $this->assertFalse(file_exists($fileOne)); + $this->assertFalse(file_exists($folderTwo)); + $this->assertFalse(file_exists($fileTwo)); + + $Folder = new Folder($path); + $Folder->delete(); + } + +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Utility/HashTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Utility/HashTest.php new file mode 100644 index 0000000..40fcd7b --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Utility/HashTest.php @@ -0,0 +1,2151 @@ + array( + 'id' => '1', + 'user_id' => '1', + 'title' => 'First Article', + 'body' => 'First Article Body' + ), + 'User' => array( + 'id' => '1', + 'user' => 'mariano', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + ), + 'Comment' => array( + array( + 'id' => '1', + 'article_id' => '1', + 'user_id' => '2', + 'comment' => 'First Comment for First Article', + ), + array( + 'id' => '2', + 'article_id' => '1', + 'user_id' => '4', + 'comment' => 'Second Comment for First Article', + ), + ), + 'Tag' => array( + array( + 'id' => '1', + 'tag' => 'tag1', + ), + array( + 'id' => '2', + 'tag' => 'tag2', + ) + ), + 'Deep' => array( + 'Nesting' => array( + 'test' => array( + 1 => 'foo', + 2 => array( + 'and' => array('more' => 'stuff') + ) + ) + ) + ) + ), + array( + 'Article' => array( + 'id' => '2', + 'user_id' => '1', + 'title' => 'Second Article', + 'body' => 'Second Article Body', + 'published' => 'Y', + ), + 'User' => array( + 'id' => '2', + 'user' => 'mariano', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + ), + 'Comment' => array(), + 'Tag' => array() + ), + array( + 'Article' => array( + 'id' => '3', + 'user_id' => '1', + 'title' => 'Third Article', + 'body' => 'Third Article Body', + ), + 'User' => array( + 'id' => '3', + 'user' => 'mariano', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + ), + 'Comment' => array(), + 'Tag' => array() + ), + array( + 'Article' => array( + 'id' => '4', + 'user_id' => '1', + 'title' => 'Fourth Article', + 'body' => 'Fourth Article Body', + ), + 'User' => array( + 'id' => '4', + 'user' => 'mariano', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + ), + 'Comment' => array(), + 'Tag' => array() + ), + array( + 'Article' => array( + 'id' => '5', + 'user_id' => '1', + 'title' => 'Fifth Article', + 'body' => 'Fifth Article Body', + ), + 'User' => array( + 'id' => '5', + 'user' => 'mariano', + 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', + ), + 'Comment' => array(), + 'Tag' => array() + ) + ); + } + + public static function userData() { + return array( + array( + 'User' => array( + 'id' => 2, + 'group_id' => 1, + 'Data' => array( + 'user' => 'mariano.iglesias', + 'name' => 'Mariano Iglesias' + ) + ) + ), + array( + 'User' => array( + 'id' => 14, + 'group_id' => 2, + 'Data' => array( + 'user' => 'phpnut', + 'name' => 'Larry E. Masters' + ) + ) + ), + array( + 'User' => array( + 'id' => 25, + 'group_id' => 1, + 'Data' => array( + 'user' => 'gwoo', + 'name' => 'The Gwoo' + ) + ) + ) + ); + } + +/** + * Test get() + * + * return void + */ + public function testGet() { + $data = self::articleData(); + + $result = Hash::get(array(), '1.Article.title'); + $this->assertNull($result); + + $result = Hash::get($data, ''); + $this->assertNull($result); + + $result = Hash::get($data, '0.Article.title'); + $this->assertEquals('First Article', $result); + + $result = Hash::get($data, '1.Article.title'); + $this->assertEquals('Second Article', $result); + + $result = Hash::get($data, '5.Article.title'); + $this->assertNull($result); + + $result = Hash::get($data, '1.Article.title.not_there'); + $this->assertNull($result); + + $result = Hash::get($data, '1.Article'); + $this->assertEquals($data[1]['Article'], $result); + + $result = Hash::get($data, array('1', 'Article')); + $this->assertEquals($data[1]['Article'], $result); + } + +/** + * Test dimensions. + * + * @return void + */ + public function testDimensions() { + $result = Hash::dimensions(array()); + $this->assertEquals($result, 0); + + $data = array('one', '2', 'three'); + $result = Hash::dimensions($data); + $this->assertEquals($result, 1); + + $data = array('1' => '1.1', '2', '3'); + $result = Hash::dimensions($data); + $this->assertEquals($result, 1); + + $data = array('1' => array('1.1' => '1.1.1'), '2', '3' => array('3.1' => '3.1.1')); + $result = Hash::dimensions($data); + $this->assertEquals($result, 2); + + $data = array('1' => '1.1', '2', '3' => array('3.1' => '3.1.1')); + $result = Hash::dimensions($data); + $this->assertEquals($result, 1); + + $data = array('1' => array('1.1' => '1.1.1'), '2', '3' => array('3.1' => array('3.1.1' => '3.1.1.1'))); + $result = Hash::dimensions($data); + $this->assertEquals($result, 2); + } + +/** + * Test maxDimensions + * + * @return void + */ + public function testMaxDimensions() { + $data = array('1' => '1.1', '2', '3' => array('3.1' => '3.1.1')); + $result = Hash::maxDimensions($data); + $this->assertEquals($result, 2); + + $data = array('1' => array('1.1' => '1.1.1'), '2', '3' => array('3.1' => array('3.1.1' => '3.1.1.1'))); + $result = Hash::maxDimensions($data); + $this->assertEquals($result, 3); + + $data = array( + '1' => array('1.1' => '1.1.1'), + array('2' => array('2.1' => array('2.1.1' => '2.1.1.1'))), + '3' => array('3.1' => array('3.1.1' => '3.1.1.1')) + ); + $result = Hash::maxDimensions($data); + $this->assertEquals($result, 4); + + $data = array( + '1' => array('1.1' => '1.1.1'), + array('2' => array('2.1' => array('2.1.1' => array('2.1.1.1')))), + '3' => array('3.1' => array('3.1.1' => '3.1.1.1')) + ); + $result = Hash::maxDimensions($data); + $this->assertEquals($result, 5); + + $data = array( + '1' => array('1.1' => '1.1.1'), + array('2' => array('2.1' => array('2.1.1' => array('2.1.1.1' => '2.1.1.1.1')))), + '3' => array('3.1' => array('3.1.1' => '3.1.1.1')) + ); + $result = Hash::maxDimensions($data); + $this->assertEquals($result, 5); + + $data = array( + '1' => array('1.1' => '1.1.1'), + array('2' => array('2.1' => array('2.1.1' => array('2.1.1.1' => '2.1.1.1.1')))), + '3' => array('3.1' => array('3.1.1' => '3.1.1.1')) + ); + $result = Hash::maxDimensions($data); + $this->assertEquals($result, 5); + } + +/** + * Tests Hash::flatten + * + * @return void + */ + public function testFlatten() { + $data = array('Larry', 'Curly', 'Moe'); + $result = Hash::flatten($data); + $this->assertEquals($result, $data); + + $data[9] = 'Shemp'; + $result = Hash::flatten($data); + $this->assertEquals($result, $data); + + $data = array( + array( + 'Post' => array('id' => '1', 'author_id' => '1', 'title' => 'First Post'), + 'Author' => array('id' => '1', 'user' => 'nate', 'password' => 'foo'), + ), + array( + 'Post' => array('id' => '2', 'author_id' => '3', 'title' => 'Second Post', 'body' => 'Second Post Body'), + 'Author' => array('id' => '3', 'user' => 'larry', 'password' => null), + ) + ); + + $result = Hash::flatten($data); + $expected = array( + '0.Post.id' => '1', + '0.Post.author_id' => '1', + '0.Post.title' => 'First Post', + '0.Author.id' => '1', + '0.Author.user' => 'nate', + '0.Author.password' => 'foo', + '1.Post.id' => '2', + '1.Post.author_id' => '3', + '1.Post.title' => 'Second Post', + '1.Post.body' => 'Second Post Body', + '1.Author.id' => '3', + '1.Author.user' => 'larry', + '1.Author.password' => null + ); + $this->assertEquals($expected, $result); + + $data = array( + array('Post' => array('id' => 1)), + array('Post' => array('id' => 2)), + ); + $result = Hash::flatten($data, '/'); + $expected = array( + '0/Post/id' => '1', + '1/Post/id' => '2', + ); + $this->assertEquals($expected, $result); + } + +/** + * Test diff(); + * + * @return void + */ + public function testDiff() { + $a = array( + 0 => array('name' => 'main'), + 1 => array('name' => 'about') + ); + $b = array( + 0 => array('name' => 'main'), + 1 => array('name' => 'about'), + 2 => array('name' => 'contact') + ); + + $result = Hash::diff($a, array()); + $expected = $a; + $this->assertEquals($expected, $result); + + $result = Hash::diff(array(), $b); + $expected = $b; + $this->assertEquals($expected, $result); + + $result = Hash::diff($a, $b); + $expected = array( + 2 => array('name' => 'contact') + ); + $this->assertEquals($expected, $result); + + $b = array( + 0 => array('name' => 'me'), + 1 => array('name' => 'about') + ); + + $result = Hash::diff($a, $b); + $expected = array( + 0 => array('name' => 'main') + ); + $this->assertEquals($expected, $result); + + $a = array(); + $b = array('name' => 'bob', 'address' => 'home'); + $result = Hash::diff($a, $b); + $this->assertEquals($result, $b); + + $a = array('name' => 'bob', 'address' => 'home'); + $b = array(); + $result = Hash::diff($a, $b); + $this->assertEquals($result, $a); + + $a = array('key' => true, 'another' => false, 'name' => 'me'); + $b = array('key' => 1, 'another' => 0); + $expected = array('name' => 'me'); + $result = Hash::diff($a, $b); + $this->assertEquals($expected, $result); + + $a = array('key' => 'value', 'another' => null, 'name' => 'me'); + $b = array('key' => 'differentValue', 'another' => null); + $expected = array('key' => 'value', 'name' => 'me'); + $result = Hash::diff($a, $b); + $this->assertEquals($expected, $result); + + $a = array('key' => 'value', 'another' => null, 'name' => 'me'); + $b = array('key' => 'differentValue', 'another' => 'value'); + $expected = array('key' => 'value', 'another' => null, 'name' => 'me'); + $result = Hash::diff($a, $b); + $this->assertEquals($expected, $result); + + $a = array('key' => 'value', 'another' => null, 'name' => 'me'); + $b = array('key' => 'differentValue', 'another' => 'value'); + $expected = array('key' => 'differentValue', 'another' => 'value', 'name' => 'me'); + $result = Hash::diff($b, $a); + $this->assertEquals($expected, $result); + + $a = array('key' => 'value', 'another' => null, 'name' => 'me'); + $b = array(0 => 'differentValue', 1 => 'value'); + $expected = $a + $b; + $result = Hash::diff($a, $b); + $this->assertEquals($expected, $result); + } + +/** + * Test merge() + * + * @return void + */ + public function testMerge() { + $result = Hash::merge(array('foo'), array('bar')); + $this->assertEquals($result, array('foo', 'bar')); + + $result = Hash::merge(array('foo'), array('user' => 'bob', 'no-bar'), 'bar'); + $this->assertEquals($result, array('foo', 'user' => 'bob', 'no-bar', 'bar')); + + $a = array('foo', 'foo2'); + $b = array('bar', 'bar2'); + $expected = array('foo', 'foo2', 'bar', 'bar2'); + $this->assertEquals($expected, Hash::merge($a, $b)); + + $a = array('foo' => 'bar', 'bar' => 'foo'); + $b = array('foo' => 'no-bar', 'bar' => 'no-foo'); + $expected = array('foo' => 'no-bar', 'bar' => 'no-foo'); + $this->assertEquals($expected, Hash::merge($a, $b)); + + $a = array('users' => array('bob', 'jim')); + $b = array('users' => array('lisa', 'tina')); + $expected = array('users' => array('bob', 'jim', 'lisa', 'tina')); + $this->assertEquals($expected, Hash::merge($a, $b)); + + $a = array('users' => array('jim', 'bob')); + $b = array('users' => 'none'); + $expected = array('users' => 'none'); + $this->assertEquals($expected, Hash::merge($a, $b)); + + $a = array('users' => array('lisa' => array('id' => 5, 'pw' => 'secret')), 'cakephp'); + $b = array('users' => array('lisa' => array('pw' => 'new-pass', 'age' => 23)), 'ice-cream'); + $expected = array( + 'users' => array('lisa' => array('id' => 5, 'pw' => 'new-pass', 'age' => 23)), + 'cakephp', + 'ice-cream' + ); + $result = Hash::merge($a, $b); + $this->assertEquals($expected, $result); + + $c = array( + 'users' => array('lisa' => array('pw' => 'you-will-never-guess', 'age' => 25, 'pet' => 'dog')), + 'chocolate' + ); + $expected = array( + 'users' => array('lisa' => array('id' => 5, 'pw' => 'you-will-never-guess', 'age' => 25, 'pet' => 'dog')), + 'cakephp', + 'ice-cream', + 'chocolate' + ); + $this->assertEquals($expected, Hash::merge($a, $b, $c)); + + $this->assertEquals($expected, Hash::merge($a, $b, array(), $c)); + + $a = array( + 'Tree', + 'CounterCache', + 'Upload' => array( + 'folder' => 'products', + 'fields' => array('image_1_id', 'image_2_id', 'image_3_id', 'image_4_id', 'image_5_id') + ) + ); + $b = array( + 'Cacheable' => array('enabled' => false), + 'Limit', + 'Bindable', + 'Validator', + 'Transactional' + ); + $expected = array( + 'Tree', + 'CounterCache', + 'Upload' => array( + 'folder' => 'products', + 'fields' => array('image_1_id', 'image_2_id', 'image_3_id', 'image_4_id', 'image_5_id') + ), + 'Cacheable' => array('enabled' => false), + 'Limit', + 'Bindable', + 'Validator', + 'Transactional' + ); + $this->assertEquals(Hash::merge($a, $b), $expected); + } + +/** + * test normalizing arrays + * + * @return void + */ + public function testNormalize() { + $result = Hash::normalize(array('one', 'two', 'three')); + $expected = array('one' => null, 'two' => null, 'three' => null); + $this->assertEquals($expected, $result); + + $result = Hash::normalize(array('one', 'two', 'three'), false); + $expected = array('one', 'two', 'three'); + $this->assertEquals($expected, $result); + + $result = Hash::normalize(array('one' => 1, 'two' => 2, 'three' => 3, 'four'), false); + $expected = array('one' => 1, 'two' => 2, 'three' => 3, 'four' => null); + $this->assertEquals($expected, $result); + + $result = Hash::normalize(array('one' => 1, 'two' => 2, 'three' => 3, 'four')); + $expected = array('one' => 1, 'two' => 2, 'three' => 3, 'four' => null); + $this->assertEquals($expected, $result); + + $result = Hash::normalize(array('one' => array('a', 'b', 'c' => 'cee'), 'two' => 2, 'three')); + $expected = array('one' => array('a', 'b', 'c' => 'cee'), 'two' => 2, 'three' => null); + $this->assertEquals($expected, $result); + } + +/** + * testContains method + * + * @return void + */ + public function testContains() { + $data = array('apple', 'bee', 'cyclops'); + $this->assertTrue(Hash::contains($data, array('apple'))); + $this->assertFalse(Hash::contains($data, array('data'))); + + $a = array( + 0 => array('name' => 'main'), + 1 => array('name' => 'about') + ); + $b = array( + 0 => array('name' => 'main'), + 1 => array('name' => 'about'), + 2 => array('name' => 'contact'), + 'a' => 'b' + ); + + $this->assertTrue(Hash::contains($a, $a)); + $this->assertFalse(Hash::contains($a, $b)); + $this->assertTrue(Hash::contains($b, $a)); + + $a = array( + array('User' => array('id' => 1)), + array('User' => array('id' => 2)), + ); + $b = array( + array('User' => array('id' => 1)), + array('User' => array('id' => 2)), + array('User' => array('id' => 3)) + ); + $this->assertTrue(Hash::contains($b, $a)); + $this->assertFalse(Hash::contains($a, $b)); + } + +/** + * testFilter method + * + * @return void + */ + public function testFilter() { + $result = Hash::filter(array('0', false, true, 0, array('one thing', 'I can tell you', 'is you got to be', false))); + $expected = array('0', 2 => true, 3 => 0, 4 => array('one thing', 'I can tell you', 'is you got to be')); + $this->assertSame($expected, $result); + + $result = Hash::filter(array(1, array(false))); + $expected = array(1); + $this->assertEquals($expected, $result); + + $result = Hash::filter(array(1, array(false, false))); + $expected = array(1); + $this->assertEquals($expected, $result); + + $result = Hash::filter(array(1, array('empty', false))); + $expected = array(1, array('empty')); + $this->assertEquals($expected, $result); + + $result = Hash::filter(array(1, array('2', false, array(3, null)))); + $expected = array(1, array('2', 2 => array(3))); + $this->assertEquals($expected, $result); + + $this->assertSame(array(), Hash::filter(array())); + } + +/** + * testNumericArrayCheck method + * + * @return void + */ + public function testNumeric() { + $data = array('one'); + $this->assertTrue(Hash::numeric(array_keys($data))); + + $data = array(1 => 'one'); + $this->assertFalse(Hash::numeric($data)); + + $data = array('one'); + $this->assertFalse(Hash::numeric($data)); + + $data = array('one' => 'two'); + $this->assertFalse(Hash::numeric($data)); + + $data = array('one' => 1); + $this->assertTrue(Hash::numeric($data)); + + $data = array(0); + $this->assertTrue(Hash::numeric($data)); + + $data = array('one', 'two', 'three', 'four', 'five'); + $this->assertTrue(Hash::numeric(array_keys($data))); + + $data = array(1 => 'one', 2 => 'two', 3 => 'three', 4 => 'four', 5 => 'five'); + $this->assertTrue(Hash::numeric(array_keys($data))); + + $data = array('1' => 'one', 2 => 'two', 3 => 'three', 4 => 'four', 5 => 'five'); + $this->assertTrue(Hash::numeric(array_keys($data))); + + $data = array('one', 2 => 'two', 3 => 'three', 4 => 'four', 'a' => 'five'); + $this->assertFalse(Hash::numeric(array_keys($data))); + } + +/** + * Test simple paths. + * + * @return void + */ + public function testExtractBasic() { + $data = self::articleData(); + + $result = Hash::extract($data, ''); + $this->assertEquals($data, $result); + + $result = Hash::extract($data, '0.Article.title'); + $this->assertEquals(array('First Article'), $result); + + $result = Hash::extract($data, '1.Article.title'); + $this->assertEquals(array('Second Article'), $result); + } + +/** + * Test the {n} selector + * + * @return void + */ + public function testExtractNumericKey() { + $data = self::articleData(); + $result = Hash::extract($data, '{n}.Article.title'); + $expected = array( + 'First Article', 'Second Article', + 'Third Article', 'Fourth Article', + 'Fifth Article' + ); + $this->assertEquals($expected, $result); + + $result = Hash::extract($data, '0.Comment.{n}.user_id'); + $expected = array( + '2', '4' + ); + $this->assertEquals($expected, $result); + } + +/** + * Test the {n} selector with inconsistent arrays + * + * @return void + */ + public function testExtractNumericMixedKeys() { + $data = array( + 'User' => array( + 0 => array( + 'id' => 4, + 'name' => 'Neo' + ), + 1 => array( + 'id' => 5, + 'name' => 'Morpheus' + ), + 'stringKey' => array( + 'name' => 'Fail' + ) + ) + ); + $result = Hash::extract($data, 'User.{n}.name'); + $expected = array('Neo', 'Morpheus'); + $this->assertEquals($expected, $result); + } + +/** + * Test the {n} selector with non-zero based arrays + * + * @return void + */ + public function testExtractNumericNonZero() { + $data = array( + 1 => array( + 'User' => array( + 'id' => 1, + 'name' => 'John', + ) + ), + 2 => array( + 'User' => array( + 'id' => 2, + 'name' => 'Bob', + ) + ), + 3 => array( + 'User' => array( + 'id' => 3, + 'name' => 'Tony', + ) + ) + ); + $result = Hash::extract($data, '{n}.User.name'); + $expected = array('John', 'Bob', 'Tony'); + $this->assertEquals($expected, $result); + } + +/** + * Test the {s} selector. + * + * @return void + */ + public function testExtractStringKey() { + $data = self::articleData(); + $result = Hash::extract($data, '{n}.{s}.user'); + $expected = array( + 'mariano', + 'mariano', + 'mariano', + 'mariano', + 'mariano' + ); + $this->assertEquals($expected, $result); + + $result = Hash::extract($data, '{n}.{s}.Nesting.test.1'); + $this->assertEquals(array('foo'), $result); + } + +/** + * Test the attribute presense selector. + * + * @return void + */ + public function testExtractAttributePresence() { + $data = self::articleData(); + + $result = Hash::extract($data, '{n}.Article[published]'); + $expected = array($data[1]['Article']); + $this->assertEquals($expected, $result); + + $result = Hash::extract($data, '{n}.Article[id][published]'); + $expected = array($data[1]['Article']); + $this->assertEquals($expected, $result); + } + +/** + * Test = and != operators. + * + * @return void + */ + public function testExtractAttributeEquality() { + $data = self::articleData(); + + $result = Hash::extract($data, '{n}.Article[id=3]'); + $expected = array($data[2]['Article']); + $this->assertEquals($expected, $result); + + $result = Hash::extract($data, '{n}.Article[id = 3]'); + $expected = array($data[2]['Article']); + $this->assertEquals($expected, $result, 'Whitespace should not matter.'); + + $result = Hash::extract($data, '{n}.Article[id!=3]'); + $this->assertEquals(1, $result[0]['id']); + $this->assertEquals(2, $result[1]['id']); + $this->assertEquals(4, $result[2]['id']); + $this->assertEquals(5, $result[3]['id']); + } + +/** + * Test comparison operators. + * + * @return void + */ + public function testExtractAttributeComparison() { + $data = self::articleData(); + + $result = Hash::extract($data, '{n}.Comment.{n}[user_id > 2]'); + $expected = array($data[0]['Comment'][1]); + $this->assertEquals($expected, $result); + $this->assertEquals(4, $expected[0]['user_id']); + + $result = Hash::extract($data, '{n}.Comment.{n}[user_id >= 4]'); + $expected = array($data[0]['Comment'][1]); + $this->assertEquals($expected, $result); + $this->assertEquals(4, $expected[0]['user_id']); + + $result = Hash::extract($data, '{n}.Comment.{n}[user_id < 3]'); + $expected = array($data[0]['Comment'][0]); + $this->assertEquals($expected, $result); + $this->assertEquals(2, $expected[0]['user_id']); + + $result = Hash::extract($data, '{n}.Comment.{n}[user_id <= 2]'); + $expected = array($data[0]['Comment'][0]); + $this->assertEquals($expected, $result); + $this->assertEquals(2, $expected[0]['user_id']); + } + +/** + * Test multiple attributes with conditions. + * + * @return void + */ + public function testExtractAttributeMultiple() { + $data = self::articleData(); + + $result = Hash::extract($data, '{n}.Comment.{n}[user_id > 2][id=1]'); + $this->assertEmpty($result); + + $result = Hash::extract($data, '{n}.Comment.{n}[user_id > 2][id=2]'); + $expected = array($data[0]['Comment'][1]); + $this->assertEquals($expected, $result); + $this->assertEquals(4, $expected[0]['user_id']); + } + +/** + * Test attribute pattern matching. + * + * @return void + */ + public function testExtractAttributePattern() { + $data = self::articleData(); + + $result = Hash::extract($data, '{n}.Article[title=/^First/]'); + $expected = array($data[0]['Article']); + $this->assertEquals($expected, $result); + } + +/** + * Test that extract() + matching can hit null things. + */ + public function testExtractMatchesNull() { + $data = array( + 'Country' => array( + array('name' => 'Canada'), + array('name' => 'Australia'), + array('name' => null), + ) + ); + $result = Hash::extract($data, 'Country.{n}[name=/Canada|^$/]'); + $expected = array( + array( + 'name' => 'Canada', + ), + array( + 'name' => null, + ), + ); + $this->assertEquals($expected, $result); + } + +/** + * Test that uneven keys are handled correctly. + * + * @return void + */ + public function testExtractUnevenKeys() { + $data = array( + 'Level1' => array( + 'Level2' => array('test1', 'test2'), + 'Level2bis' => array('test3', 'test4') + ) + ); + $this->assertEquals( + array('test1', 'test2'), + Hash::extract($data, 'Level1.Level2') + ); + $this->assertEquals( + array('test3', 'test4'), + Hash::extract($data, 'Level1.Level2bis') + ); + + $data = array( + 'Level1' => array( + 'Level2bis' => array( + array('test3', 'test4'), + array('test5', 'test6') + ) + ) + ); + $expected = array( + array('test3', 'test4'), + array('test5', 'test6') + ); + $this->assertEquals($expected, Hash::extract($data, 'Level1.Level2bis')); + + $data['Level1']['Level2'] = array('test1', 'test2'); + $this->assertEquals($expected, Hash::extract($data, 'Level1.Level2bis')); + } + +/** + * testSort method + * + * @return void + */ + public function testSort() { + $a = array( + 0 => array( + 'Person' => array('name' => 'Jeff'), + 'Friend' => array(array('name' => 'Nate')) + ), + 1 => array( + 'Person' => array('name' => 'Tracy'), + 'Friend' => array(array('name' => 'Lindsay')) + ) + ); + $b = array( + 0 => array( + 'Person' => array('name' => 'Tracy'), + 'Friend' => array(array('name' => 'Lindsay')) + ), + 1 => array( + 'Person' => array('name' => 'Jeff'), + 'Friend' => array(array('name' => 'Nate')) + ) + ); + $a = Hash::sort($a, '{n}.Friend.{n}.name', 'asc'); + $this->assertEquals($a, $b); + + $b = array( + 0 => array( + 'Person' => array('name' => 'Jeff'), + 'Friend' => array(array('name' => 'Nate')) + ), + 1 => array( + 'Person' => array('name' => 'Tracy'), + 'Friend' => array(array('name' => 'Lindsay')) + ) + ); + $a = array( + 0 => array( + 'Person' => array('name' => 'Tracy'), + 'Friend' => array(array('name' => 'Lindsay')) + ), + 1 => array( + 'Person' => array('name' => 'Jeff'), + 'Friend' => array(array('name' => 'Nate')) + ) + ); + $a = Hash::sort($a, '{n}.Friend.{n}.name', 'desc'); + $this->assertEquals($a, $b); + + $a = array( + 0 => array( + 'Person' => array('name' => 'Jeff'), + 'Friend' => array(array('name' => 'Nate')) + ), + 1 => array( + 'Person' => array('name' => 'Tracy'), + 'Friend' => array(array('name' => 'Lindsay')) + ), + 2 => array( + 'Person' => array('name' => 'Adam'), + 'Friend' => array(array('name' => 'Bob')) + ) + ); + $b = array( + 0 => array( + 'Person' => array('name' => 'Adam'), + 'Friend' => array(array('name' => 'Bob')) + ), + 1 => array( + 'Person' => array('name' => 'Jeff'), + 'Friend' => array(array('name' => 'Nate')) + ), + 2 => array( + 'Person' => array('name' => 'Tracy'), + 'Friend' => array(array('name' => 'Lindsay')) + ) + ); + $a = Hash::sort($a, '{n}.Person.name', 'asc'); + $this->assertEquals($a, $b); + + $a = array( + 0 => array('Person' => array('name' => 'Jeff')), + 1 => array('Shirt' => array('color' => 'black')) + ); + $b = array( + 0 => array('Shirt' => array('color' => 'black')), + 1 => array('Person' => array('name' => 'Jeff')), + ); + $a = Hash::sort($a, '{n}.Person.name', 'ASC', 'STRING'); + $this->assertEquals($a, $b); + + $names = array( + array('employees' => array( + array('name' => array('first' => 'John', 'last' => 'Doe'))) + ), + array('employees' => array( + array('name' => array('first' => 'Jane', 'last' => 'Doe'))) + ), + array('employees' => array(array('name' => array()))), + array('employees' => array(array('name' => array()))) + ); + $result = Hash::sort($names, '{n}.employees.0.name', 'asc'); + $expected = array( + array('employees' => array( + array('name' => array('first' => 'John', 'last' => 'Doe'))) + ), + array('employees' => array( + array('name' => array('first' => 'Jane', 'last' => 'Doe'))) + ), + array('employees' => array(array('name' => array()))), + array('employees' => array(array('name' => array()))) + ); + $this->assertEquals($expected, $result); + } + +/** + * Test sort() with numeric option. + * + * @return void + */ + public function testSortNumeric() { + $items = array( + array('Item' => array('price' => '155,000')), + array('Item' => array('price' => '139,000')), + array('Item' => array('price' => '275,622')), + array('Item' => array('price' => '230,888')), + array('Item' => array('price' => '66,000')), + ); + $result = Hash::sort($items, '{n}.Item.price', 'asc', 'numeric'); + $expected = array( + array('Item' => array('price' => '66,000')), + array('Item' => array('price' => '139,000')), + array('Item' => array('price' => '155,000')), + array('Item' => array('price' => '230,888')), + array('Item' => array('price' => '275,622')), + ); + $this->assertEquals($expected, $result); + + $result = Hash::sort($items, '{n}.Item.price', 'desc', 'numeric'); + $expected = array( + array('Item' => array('price' => '275,622')), + array('Item' => array('price' => '230,888')), + array('Item' => array('price' => '155,000')), + array('Item' => array('price' => '139,000')), + array('Item' => array('price' => '66,000')), + ); + $this->assertEquals($expected, $result); + } + +/** + * Test natural sorting. + * + * @return void + */ + public function testSortNatural() { + if (version_compare(PHP_VERSION, '5.4.0', '<')) { + $this->markTestSkipped('SORT_NATURAL is available since PHP 5.4.'); + } + $items = array( + array('Item' => array('image' => 'img1.jpg')), + array('Item' => array('image' => 'img99.jpg')), + array('Item' => array('image' => 'img12.jpg')), + array('Item' => array('image' => 'img10.jpg')), + array('Item' => array('image' => 'img2.jpg')), + ); + $result = Hash::sort($items, '{n}.Item.image', 'desc', 'natural'); + $expected = array( + array('Item' => array('image' => 'img99.jpg')), + array('Item' => array('image' => 'img12.jpg')), + array('Item' => array('image' => 'img10.jpg')), + array('Item' => array('image' => 'img2.jpg')), + array('Item' => array('image' => 'img1.jpg')), + ); + $this->assertEquals($expected, $result); + + $result = Hash::sort($items, '{n}.Item.image', 'asc', 'natural'); + $expected = array( + array('Item' => array('image' => 'img1.jpg')), + array('Item' => array('image' => 'img2.jpg')), + array('Item' => array('image' => 'img10.jpg')), + array('Item' => array('image' => 'img12.jpg')), + array('Item' => array('image' => 'img99.jpg')), + ); + $this->assertEquals($expected, $result); + } + +/** + * test sorting with out of order keys. + * + * @return void + */ + public function testSortWithOutOfOrderKeys() { + $data = array( + 9 => array('class' => 510, 'test2' => 2), + 1 => array('class' => 500, 'test2' => 1), + 2 => array('class' => 600, 'test2' => 2), + 5 => array('class' => 625, 'test2' => 4), + 0 => array('class' => 605, 'test2' => 3), + ); + $expected = array( + array('class' => 500, 'test2' => 1), + array('class' => 510, 'test2' => 2), + array('class' => 600, 'test2' => 2), + array('class' => 605, 'test2' => 3), + array('class' => 625, 'test2' => 4), + ); + $result = Hash::sort($data, '{n}.class', 'asc'); + $this->assertEquals($expected, $result); + + $result = Hash::sort($data, '{n}.test2', 'asc'); + $this->assertEquals($expected, $result); + } + +/** + * test sorting with string keys. + * + * @return void + */ + public function testSortString() { + $toSort = array( + 'four' => array('number' => 4, 'some' => 'foursome'), + 'six' => array('number' => 6, 'some' => 'sixsome'), + 'five' => array('number' => 5, 'some' => 'fivesome'), + 'two' => array('number' => 2, 'some' => 'twosome'), + 'three' => array('number' => 3, 'some' => 'threesome') + ); + $sorted = Hash::sort($toSort, '{s}.number', 'asc'); + $expected = array( + 'two' => array('number' => 2, 'some' => 'twosome'), + 'three' => array('number' => 3, 'some' => 'threesome'), + 'four' => array('number' => 4, 'some' => 'foursome'), + 'five' => array('number' => 5, 'some' => 'fivesome'), + 'six' => array('number' => 6, 'some' => 'sixsome') + ); + $this->assertEquals($expected, $sorted); + + $menus = array( + 'blogs' => array('title' => 'Blogs', 'weight' => 3), + 'comments' => array('title' => 'Comments', 'weight' => 2), + 'users' => array('title' => 'Users', 'weight' => 1), + ); + $expected = array( + 'users' => array('title' => 'Users', 'weight' => 1), + 'comments' => array('title' => 'Comments', 'weight' => 2), + 'blogs' => array('title' => 'Blogs', 'weight' => 3), + ); + $result = Hash::sort($menus, '{s}.weight', 'ASC'); + $this->assertEquals($expected, $result); + } + +/** + * Test insert() + * + * @return void + */ + public function testInsertSimple() { + $a = array( + 'pages' => array('name' => 'page') + ); + $result = Hash::insert($a, 'files', array('name' => 'files')); + $expected = array( + 'pages' => array('name' => 'page'), + 'files' => array('name' => 'files') + ); + $this->assertEquals($expected, $result); + + $a = array( + 'pages' => array('name' => 'page') + ); + $result = Hash::insert($a, 'pages.name', array()); + $expected = array( + 'pages' => array('name' => array()), + ); + $this->assertEquals($expected, $result); + } + +/** + * Test inserting with multiple values. + * + * @return void + */ + public function testInsertMulti() { + $data = self::articleData(); + + $result = Hash::insert($data, '{n}.Article.insert', 'value'); + $this->assertEquals('value', $result[0]['Article']['insert']); + $this->assertEquals('value', $result[1]['Article']['insert']); + + $result = Hash::insert($data, '{n}.Comment.{n}.insert', 'value'); + $this->assertEquals('value', $result[0]['Comment'][0]['insert']); + $this->assertEquals('value', $result[0]['Comment'][1]['insert']); + } + +/** + * Test that insert() can insert data over a string value. + * + * @return void + */ + public function testInsertOverwriteStringValue() { + $data = array( + 'Some' => array( + 'string' => 'value' + ) + ); + $result = Hash::insert($data, 'Some.string.value', array('values')); + $expected = array( + 'Some' => array( + 'string' => array( + 'value' => array('values') + ) + ) + ); + $this->assertEquals($expected, $result); + } + +/** + * Test remove() method. + * + * @return void + */ + public function testRemove() { + $a = array( + 'pages' => array('name' => 'page'), + 'files' => array('name' => 'files') + ); + + $result = Hash::remove($a, 'files'); + $expected = array( + 'pages' => array('name' => 'page') + ); + $this->assertEquals($expected, $result); + + $a = array( + 'pages' => array( + 0 => array('name' => 'main'), + 1 => array( + 'name' => 'about', + 'vars' => array('title' => 'page title') + ) + ) + ); + + $result = Hash::remove($a, 'pages.1.vars'); + $expected = array( + 'pages' => array( + 0 => array('name' => 'main'), + 1 => array('name' => 'about') + ) + ); + $this->assertEquals($expected, $result); + + $result = Hash::remove($a, 'pages.2.vars'); + $expected = $a; + $this->assertEquals($expected, $result); + } + +/** + * Test removing multiple values. + * + * @return void + */ + public function testRemoveMulti() { + $data = self::articleData(); + + $result = Hash::remove($data, '{n}.Article.title'); + $this->assertFalse(isset($result[0]['Article']['title'])); + $this->assertFalse(isset($result[1]['Article']['title'])); + + $result = Hash::remove($data, '{n}.Article.{s}'); + $this->assertFalse(isset($result[0]['Article']['id'])); + $this->assertFalse(isset($result[0]['Article']['user_id'])); + $this->assertFalse(isset($result[0]['Article']['title'])); + $this->assertFalse(isset($result[0]['Article']['body'])); + } + +/** + * testCheck method + * + * @return void + */ + public function testCheck() { + $set = array( + 'My Index 1' => array('First' => 'The first item') + ); + $this->assertTrue(Hash::check($set, 'My Index 1.First')); + $this->assertTrue(Hash::check($set, 'My Index 1')); + + $set = array( + 'My Index 1' => array( + 'First' => array( + 'Second' => array( + 'Third' => array( + 'Fourth' => 'Heavy. Nesting.' + ) + ) + ) + ) + ); + $this->assertTrue(Hash::check($set, 'My Index 1.First.Second')); + $this->assertTrue(Hash::check($set, 'My Index 1.First.Second.Third')); + $this->assertTrue(Hash::check($set, 'My Index 1.First.Second.Third.Fourth')); + $this->assertFalse(Hash::check($set, 'My Index 1.First.Seconds.Third.Fourth')); + } + +/** + * testCombine method + * + * @return void + */ + public function testCombine() { + $result = Hash::combine(array(), '{n}.User.id', '{n}.User.Data'); + $this->assertTrue(empty($result)); + + $a = self::userData(); + + $result = Hash::combine($a, '{n}.User.id'); + $expected = array(2 => null, 14 => null, 25 => null); + $this->assertEquals($expected, $result); + + $result = Hash::combine($a, '{n}.User.id', '{n}.User.non-existant'); + $expected = array(2 => null, 14 => null, 25 => null); + $this->assertEquals($expected, $result); + + $result = Hash::combine($a, '{n}.User.id', '{n}.User.Data'); + $expected = array( + 2 => array('user' => 'mariano.iglesias', 'name' => 'Mariano Iglesias'), + 14 => array('user' => 'phpnut', 'name' => 'Larry E. Masters'), + 25 => array('user' => 'gwoo', 'name' => 'The Gwoo')); + $this->assertEquals($expected, $result); + + $result = Hash::combine($a, '{n}.User.id', '{n}.User.Data.name'); + $expected = array( + 2 => 'Mariano Iglesias', + 14 => 'Larry E. Masters', + 25 => 'The Gwoo'); + $this->assertEquals($expected, $result); + } + +/** + * test combine() with a group path. + * + * @return void + */ + public function testCombineWithGroupPath() { + $a = self::userData(); + + $result = Hash::combine($a, '{n}.User.id', '{n}.User.Data', '{n}.User.group_id'); + $expected = array( + 1 => array( + 2 => array('user' => 'mariano.iglesias', 'name' => 'Mariano Iglesias'), + 25 => array('user' => 'gwoo', 'name' => 'The Gwoo') + ), + 2 => array( + 14 => array('user' => 'phpnut', 'name' => 'Larry E. Masters') + ) + ); + $this->assertEquals($expected, $result); + + $result = Hash::combine($a, '{n}.User.id', '{n}.User.Data.name', '{n}.User.group_id'); + $expected = array( + 1 => array( + 2 => 'Mariano Iglesias', + 25 => 'The Gwoo' + ), + 2 => array( + 14 => 'Larry E. Masters' + ) + ); + $this->assertEquals($expected, $result); + + $result = Hash::combine($a, '{n}.User.id', '{n}.User.Data', '{n}.User.group_id'); + $expected = array( + 1 => array( + 2 => array('user' => 'mariano.iglesias', 'name' => 'Mariano Iglesias'), + 25 => array('user' => 'gwoo', 'name' => 'The Gwoo') + ), + 2 => array( + 14 => array('user' => 'phpnut', 'name' => 'Larry E. Masters') + ) + ); + $this->assertEquals($expected, $result); + + $result = Hash::combine($a, '{n}.User.id', '{n}.User.Data.name', '{n}.User.group_id'); + $expected = array( + 1 => array( + 2 => 'Mariano Iglesias', + 25 => 'The Gwoo' + ), + 2 => array( + 14 => 'Larry E. Masters' + ) + ); + $this->assertEquals($expected, $result); + } + +/** + * Test combine with formatting rules. + * + * @return void + */ + public function testCombineWithFormatting() { + $a = self::userData(); + + $result = Hash::combine( + $a, + '{n}.User.id', + array('%1$s: %2$s', '{n}.User.Data.user', '{n}.User.Data.name'), + '{n}.User.group_id' + ); + $expected = array( + 1 => array( + 2 => 'mariano.iglesias: Mariano Iglesias', + 25 => 'gwoo: The Gwoo' + ), + 2 => array( + 14 => 'phpnut: Larry E. Masters' + ) + ); + $this->assertEquals($expected, $result); + + $result = Hash::combine( + $a, + array( + '%s: %s', + '{n}.User.Data.user', + '{n}.User.Data.name' + ), + '{n}.User.id' + ); + $expected = array( + 'mariano.iglesias: Mariano Iglesias' => 2, + 'phpnut: Larry E. Masters' => 14, + 'gwoo: The Gwoo' => 25 + ); + $this->assertEquals($expected, $result); + + $result = Hash::combine( + $a, + array('%1$s: %2$d', '{n}.User.Data.user', '{n}.User.id'), + '{n}.User.Data.name' + ); + $expected = array( + 'mariano.iglesias: 2' => 'Mariano Iglesias', + 'phpnut: 14' => 'Larry E. Masters', + 'gwoo: 25' => 'The Gwoo' + ); + $this->assertEquals($expected, $result); + + $result = Hash::combine( + $a, + array('%2$d: %1$s', '{n}.User.Data.user', '{n}.User.id'), + '{n}.User.Data.name' + ); + $expected = array( + '2: mariano.iglesias' => 'Mariano Iglesias', + '14: phpnut' => 'Larry E. Masters', + '25: gwoo' => 'The Gwoo' + ); + $this->assertEquals($expected, $result); + } + +/** + * testFormat method + * + * @return void + */ + public function testFormat() { + $data = self::userData(); + + $result = Hash::format( + $data, + array('{n}.User.Data.user', '{n}.User.id'), + '%s, %s' + ); + $expected = array( + 'mariano.iglesias, 2', + 'phpnut, 14', + 'gwoo, 25' + ); + $this->assertEquals($expected, $result); + + $result = Hash::format( + $data, + array('{n}.User.Data.user', '{n}.User.id'), + '%2$s, %1$s' + ); + $expected = array( + '2, mariano.iglesias', + '14, phpnut', + '25, gwoo' + ); + $this->assertEquals($expected, $result); + } + +/** + * testFormattingNullValues method + * + * @return void + */ + public function testFormatNullValues() { + $data = array( + array('Person' => array( + 'first_name' => 'Nate', 'last_name' => 'Abele', 'city' => 'Boston', 'state' => 'MA', 'something' => '42' + )), + array('Person' => array( + 'first_name' => 'Larry', 'last_name' => 'Masters', 'city' => 'Boondock', 'state' => 'TN', 'something' => null + )), + array('Person' => array( + 'first_name' => 'Garrett', 'last_name' => 'Woodworth', 'city' => 'Venice Beach', 'state' => 'CA', 'something' => null + )) + ); + + $result = Hash::format($data, array('{n}.Person.something'), '%s'); + $expected = array('42', '', ''); + $this->assertEquals($expected, $result); + + $result = Hash::format($data, array('{n}.Person.city', '{n}.Person.something'), '%s, %s'); + $expected = array('Boston, 42', 'Boondock, ', 'Venice Beach, '); + $this->assertEquals($expected, $result); + } + +/** + * Test map() + * + * @return void + */ + public function testMap() { + $data = self::articleData(); + + $result = Hash::map($data, '{n}.Article.id', array($this, 'mapCallback')); + $expected = array(2, 4, 6, 8, 10); + $this->assertEquals($expected, $result); + } + + public function testApply() { + $data = self::articleData(); + + $result = Hash::apply($data, '{n}.Article.id', 'array_sum'); + $this->assertEquals(15, $result); + } + +/** + * Test reduce() + * + * @return void + */ + public function testReduce() { + $data = self::articleData(); + + $result = Hash::reduce($data, '{n}.Article.id', array($this, 'reduceCallback')); + $this->assertEquals(15, $result); + } + +/** + * testing method for map callbacks. + * + * @param mixed $value + * @return mixed. + */ + public function mapCallback($value) { + return $value * 2; + } + +/** + * testing method for reduce callbacks. + * + * @param mixed $one + * @param mixed $two + * @return mixed. + */ + public function reduceCallback($one, $two) { + return $one + $two; + } + +/** + * test Hash nest with a normal model result set. For kicks rely on Hash nest detecting the key names + * automatically + * + * @return void + */ + public function testNestModel() { + $input = array( + array( + 'ModelName' => array( + 'id' => 1, + 'parent_id' => null + ), + ), + array( + 'ModelName' => array( + 'id' => 2, + 'parent_id' => 1 + ), + ), + array( + 'ModelName' => array( + 'id' => 3, + 'parent_id' => 1 + ), + ), + array( + 'ModelName' => array( + 'id' => 4, + 'parent_id' => 1 + ), + ), + array( + 'ModelName' => array( + 'id' => 5, + 'parent_id' => 1 + ), + ), + array( + 'ModelName' => array( + 'id' => 6, + 'parent_id' => null + ), + ), + array( + 'ModelName' => array( + 'id' => 7, + 'parent_id' => 6 + ), + ), + array( + 'ModelName' => array( + 'id' => 8, + 'parent_id' => 6 + ), + ), + array( + 'ModelName' => array( + 'id' => 9, + 'parent_id' => 6 + ), + ), + array( + 'ModelName' => array( + 'id' => 10, + 'parent_id' => 6 + ) + ) + ); + $expected = array( + array( + 'ModelName' => array( + 'id' => 1, + 'parent_id' => null + ), + 'children' => array( + array( + 'ModelName' => array( + 'id' => 2, + 'parent_id' => 1 + ), + 'children' => array() + ), + array( + 'ModelName' => array( + 'id' => 3, + 'parent_id' => 1 + ), + 'children' => array() + ), + array( + 'ModelName' => array( + 'id' => 4, + 'parent_id' => 1 + ), + 'children' => array() + ), + array( + 'ModelName' => array( + 'id' => 5, + 'parent_id' => 1 + ), + 'children' => array() + ), + + ) + ), + array( + 'ModelName' => array( + 'id' => 6, + 'parent_id' => null + ), + 'children' => array( + array( + 'ModelName' => array( + 'id' => 7, + 'parent_id' => 6 + ), + 'children' => array() + ), + array( + 'ModelName' => array( + 'id' => 8, + 'parent_id' => 6 + ), + 'children' => array() + ), + array( + 'ModelName' => array( + 'id' => 9, + 'parent_id' => 6 + ), + 'children' => array() + ), + array( + 'ModelName' => array( + 'id' => 10, + 'parent_id' => 6 + ), + 'children' => array() + ) + ) + ) + ); + $result = Hash::nest($input); + $this->assertEquals($expected, $result); + } + +/** + * test Hash nest with a normal model result set, and a nominated root id + * + * @return void + */ + public function testNestModelExplicitRoot() { + $input = array( + array( + 'ModelName' => array( + 'id' => 1, + 'parent_id' => null + ), + ), + array( + 'ModelName' => array( + 'id' => 2, + 'parent_id' => 1 + ), + ), + array( + 'ModelName' => array( + 'id' => 3, + 'parent_id' => 1 + ), + ), + array( + 'ModelName' => array( + 'id' => 4, + 'parent_id' => 1 + ), + ), + array( + 'ModelName' => array( + 'id' => 5, + 'parent_id' => 1 + ), + ), + array( + 'ModelName' => array( + 'id' => 6, + 'parent_id' => null + ), + ), + array( + 'ModelName' => array( + 'id' => 7, + 'parent_id' => 6 + ), + ), + array( + 'ModelName' => array( + 'id' => 8, + 'parent_id' => 6 + ), + ), + array( + 'ModelName' => array( + 'id' => 9, + 'parent_id' => 6 + ), + ), + array( + 'ModelName' => array( + 'id' => 10, + 'parent_id' => 6 + ) + ) + ); + $expected = array( + array( + 'ModelName' => array( + 'id' => 6, + 'parent_id' => null + ), + 'children' => array( + array( + 'ModelName' => array( + 'id' => 7, + 'parent_id' => 6 + ), + 'children' => array() + ), + array( + 'ModelName' => array( + 'id' => 8, + 'parent_id' => 6 + ), + 'children' => array() + ), + array( + 'ModelName' => array( + 'id' => 9, + 'parent_id' => 6 + ), + 'children' => array() + ), + array( + 'ModelName' => array( + 'id' => 10, + 'parent_id' => 6 + ), + 'children' => array() + ) + ) + ) + ); + $result = Hash::nest($input, array('root' => 6)); + $this->assertEquals($expected, $result); + } + +/** + * test Hash nest with a 1d array - this method should be able to handle any type of array input + * + * @return void + */ + public function testNest1Dimensional() { + $input = array( + array( + 'id' => 1, + 'parent_id' => null + ), + array( + 'id' => 2, + 'parent_id' => 1 + ), + array( + 'id' => 3, + 'parent_id' => 1 + ), + array( + 'id' => 4, + 'parent_id' => 1 + ), + array( + 'id' => 5, + 'parent_id' => 1 + ), + array( + 'id' => 6, + 'parent_id' => null + ), + array( + 'id' => 7, + 'parent_id' => 6 + ), + array( + 'id' => 8, + 'parent_id' => 6 + ), + array( + 'id' => 9, + 'parent_id' => 6 + ), + array( + 'id' => 10, + 'parent_id' => 6 + ) + ); + $expected = array( + array( + 'id' => 1, + 'parent_id' => null, + 'children' => array( + array( + 'id' => 2, + 'parent_id' => 1, + 'children' => array() + ), + array( + 'id' => 3, + 'parent_id' => 1, + 'children' => array() + ), + array( + 'id' => 4, + 'parent_id' => 1, + 'children' => array() + ), + array( + 'id' => 5, + 'parent_id' => 1, + 'children' => array() + ), + + ) + ), + array( + 'id' => 6, + 'parent_id' => null, + 'children' => array( + array( + 'id' => 7, + 'parent_id' => 6, + 'children' => array() + ), + array( + 'id' => 8, + 'parent_id' => 6, + 'children' => array() + ), + array( + 'id' => 9, + 'parent_id' => 6, + 'children' => array() + ), + array( + 'id' => 10, + 'parent_id' => 6, + 'children' => array() + ) + ) + ) + ); + $result = Hash::nest($input, array('idPath' => '{n}.id', 'parentPath' => '{n}.parent_id')); + $this->assertEquals($expected, $result); + } + +/** + * test Hash nest with no specified parent data. + * + * The result should be the same as the input. + * For an easier comparison, unset all the empty children arrays from the result + * + * @return void + */ + public function testMissingParent() { + $input = array( + array( + 'id' => 1, + ), + array( + 'id' => 2, + ), + array( + 'id' => 3, + ), + array( + 'id' => 4, + ), + array( + 'id' => 5, + ), + array( + 'id' => 6, + ), + array( + 'id' => 7, + ), + array( + 'id' => 8, + ), + array( + 'id' => 9, + ), + array( + 'id' => 10, + ) + ); + + $result = Hash::nest($input, array('idPath' => '{n}.id', 'parentPath' => '{n}.parent_id')); + foreach ($result as &$row) { + if (empty($row['children'])) { + unset($row['children']); + } + } + $this->assertEquals($input, $result); + } + +/** + * testMergeDiff method + * + * @return void + */ + public function testMergeDiff() { + $first = array( + 'ModelOne' => array( + 'id' => 1001, + 'field_one' => 'a1.m1.f1', + 'field_two' => 'a1.m1.f2' + ) + ); + $second = array( + 'ModelTwo' => array( + 'id' => 1002, + 'field_one' => 'a2.m2.f1', + 'field_two' => 'a2.m2.f2' + ) + ); + $result = Hash::mergeDiff($first, $second); + $this->assertEquals($result, $first + $second); + + $result = Hash::mergeDiff($first, array()); + $this->assertEquals($result, $first); + + $result = Hash::mergeDiff(array(), $first); + $this->assertEquals($result, $first); + + $third = array( + 'ModelOne' => array( + 'id' => 1003, + 'field_one' => 'a3.m1.f1', + 'field_two' => 'a3.m1.f2', + 'field_three' => 'a3.m1.f3' + ) + ); + $result = Hash::mergeDiff($first, $third); + $expected = array( + 'ModelOne' => array( + 'id' => 1001, + 'field_one' => 'a1.m1.f1', + 'field_two' => 'a1.m1.f2', + 'field_three' => 'a3.m1.f3' + ) + ); + $this->assertEquals($expected, $result); + + $first = array( + 0 => array('ModelOne' => array('id' => 1001, 'field_one' => 's1.0.m1.f1', 'field_two' => 's1.0.m1.f2')), + 1 => array('ModelTwo' => array('id' => 1002, 'field_one' => 's1.1.m2.f2', 'field_two' => 's1.1.m2.f2')) + ); + $second = array( + 0 => array('ModelOne' => array('id' => 1001, 'field_one' => 's2.0.m1.f1', 'field_two' => 's2.0.m1.f2')), + 1 => array('ModelTwo' => array('id' => 1002, 'field_one' => 's2.1.m2.f2', 'field_two' => 's2.1.m2.f2')) + ); + + $result = Hash::mergeDiff($first, $second); + $this->assertEquals($result, $first); + + $third = array( + 0 => array( + 'ModelThree' => array( + 'id' => 1003, + 'field_one' => 's3.0.m3.f1', + 'field_two' => 's3.0.m3.f2' + ) + ) + ); + + $result = Hash::mergeDiff($first, $third); + $expected = array( + 0 => array( + 'ModelOne' => array( + 'id' => 1001, + 'field_one' => 's1.0.m1.f1', + 'field_two' => 's1.0.m1.f2' + ), + 'ModelThree' => array( + 'id' => 1003, + 'field_one' => 's3.0.m3.f1', + 'field_two' => 's3.0.m3.f2' + ) + ), + 1 => array( + 'ModelTwo' => array( + 'id' => 1002, + 'field_one' => 's1.1.m2.f2', + 'field_two' => 's1.1.m2.f2' + ) + ) + ); + $this->assertEquals($expected, $result); + + $result = Hash::mergeDiff($first, null); + $this->assertEquals($result, $first); + + $result = Hash::mergeDiff($first, $second); + $this->assertEquals($result, $first + $second); + } + +/** + * Tests Hash::expand + * + * @return void + */ + public function testExpand() { + $data = array('My', 'Array', 'To', 'Flatten'); + $flat = Hash::flatten($data); + $result = Hash::expand($flat); + $this->assertEquals($data, $result); + + $data = array( + '0.Post.id' => '1', '0.Post.author_id' => '1', '0.Post.title' => 'First Post', '0.Author.id' => '1', + '0.Author.user' => 'nate', '0.Author.password' => 'foo', '1.Post.id' => '2', '1.Post.author_id' => '3', + '1.Post.title' => 'Second Post', '1.Post.body' => 'Second Post Body', '1.Author.id' => '3', + '1.Author.user' => 'larry', '1.Author.password' => null + ); + $result = Hash::expand($data); + $expected = array( + array( + 'Post' => array('id' => '1', 'author_id' => '1', 'title' => 'First Post'), + 'Author' => array('id' => '1', 'user' => 'nate', 'password' => 'foo'), + ), + array( + 'Post' => array('id' => '2', 'author_id' => '3', 'title' => 'Second Post', 'body' => 'Second Post Body'), + 'Author' => array('id' => '3', 'user' => 'larry', 'password' => null), + ) + ); + $this->assertEquals($expected, $result); + + $data = array( + '0/Post/id' => 1, + '0/Post/name' => 'test post' + ); + $result = Hash::expand($data, '/'); + $expected = array( + array( + 'Post' => array( + 'id' => 1, + 'name' => 'test post' + ) + ) + ); + $this->assertEquals($result, $expected); + } + +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Utility/InflectorTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Utility/InflectorTest.php new file mode 100644 index 0000000..cd19892 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Utility/InflectorTest.php @@ -0,0 +1,440 @@ +assertEquals(Inflector::singularize('categorias'), 'categoria'); + $this->assertEquals(Inflector::singularize('menus'), 'menu'); + $this->assertEquals(Inflector::singularize('news'), 'news'); + $this->assertEquals(Inflector::singularize('food_menus'), 'food_menu'); + $this->assertEquals(Inflector::singularize('Menus'), 'Menu'); + $this->assertEquals(Inflector::singularize('FoodMenus'), 'FoodMenu'); + $this->assertEquals(Inflector::singularize('houses'), 'house'); + $this->assertEquals(Inflector::singularize('powerhouses'), 'powerhouse'); + $this->assertEquals(Inflector::singularize('quizzes'), 'quiz'); + $this->assertEquals(Inflector::singularize('Buses'), 'Bus'); + $this->assertEquals(Inflector::singularize('buses'), 'bus'); + $this->assertEquals(Inflector::singularize('matrix_rows'), 'matrix_row'); + $this->assertEquals(Inflector::singularize('matrices'), 'matrix'); + $this->assertEquals(Inflector::singularize('vertices'), 'vertex'); + $this->assertEquals(Inflector::singularize('indices'), 'index'); + $this->assertEquals(Inflector::singularize('Aliases'), 'Alias'); + $this->assertEquals(Inflector::singularize('Alias'), 'Alias'); + $this->assertEquals(Inflector::singularize('Media'), 'Media'); + $this->assertEquals(Inflector::singularize('NodeMedia'), 'NodeMedia'); + $this->assertEquals(Inflector::singularize('alumni'), 'alumnus'); + $this->assertEquals(Inflector::singularize('bacilli'), 'bacillus'); + $this->assertEquals(Inflector::singularize('cacti'), 'cactus'); + $this->assertEquals(Inflector::singularize('foci'), 'focus'); + $this->assertEquals(Inflector::singularize('fungi'), 'fungus'); + $this->assertEquals(Inflector::singularize('nuclei'), 'nucleus'); + $this->assertEquals(Inflector::singularize('octopuses'), 'octopus'); + $this->assertEquals(Inflector::singularize('radii'), 'radius'); + $this->assertEquals(Inflector::singularize('stimuli'), 'stimulus'); + $this->assertEquals(Inflector::singularize('syllabi'), 'syllabus'); + $this->assertEquals(Inflector::singularize('termini'), 'terminus'); + $this->assertEquals(Inflector::singularize('viri'), 'virus'); + $this->assertEquals(Inflector::singularize('people'), 'person'); + $this->assertEquals(Inflector::singularize('gloves'), 'glove'); + $this->assertEquals(Inflector::singularize('doves'), 'dove'); + $this->assertEquals(Inflector::singularize('lives'), 'life'); + $this->assertEquals(Inflector::singularize('knives'), 'knife'); + $this->assertEquals(Inflector::singularize('wolves'), 'wolf'); + $this->assertEquals(Inflector::singularize('slaves'), 'slave'); + $this->assertEquals(Inflector::singularize('shelves'), 'shelf'); + $this->assertEquals(Inflector::singularize('taxis'), 'taxi'); + $this->assertEquals(Inflector::singularize('taxes'), 'tax'); + $this->assertEquals(Inflector::singularize('Taxes'), 'Tax'); + $this->assertEquals(Inflector::singularize('AwesomeTaxes'), 'AwesomeTax'); + $this->assertEquals(Inflector::singularize('faxes'), 'fax'); + $this->assertEquals(Inflector::singularize('waxes'), 'wax'); + $this->assertEquals(Inflector::singularize('niches'), 'niche'); + $this->assertEquals(Inflector::singularize('waves'), 'wave'); + $this->assertEquals(Inflector::singularize('bureaus'), 'bureau'); + $this->assertEquals(Inflector::singularize('genetic_analyses'), 'genetic_analysis'); + $this->assertEquals(Inflector::singularize('doctor_diagnoses'), 'doctor_diagnosis'); + $this->assertEquals(Inflector::singularize('parantheses'), 'paranthesis'); + $this->assertEquals(Inflector::singularize('Causes'), 'Cause'); + $this->assertEquals(Inflector::singularize('colossuses'), 'colossus'); + $this->assertEquals(Inflector::singularize('diagnoses'), 'diagnosis'); + $this->assertEquals(Inflector::singularize('bases'), 'basis'); + $this->assertEquals(Inflector::singularize('analyses'), 'analysis'); + $this->assertEquals(Inflector::singularize('curves'), 'curve'); + $this->assertEquals(Inflector::singularize('cafes'), 'cafe'); + $this->assertEquals(Inflector::singularize('roofs'), 'roof'); + $this->assertEquals(Inflector::singularize('foes'), 'foe'); + $this->assertEquals(Inflector::singularize('databases'), 'database'); + + $this->assertEquals(Inflector::singularize(''), ''); + } + +/** + * testInflectingPlurals method + * + * @return void + */ + public function testInflectingPlurals() { + $this->assertEquals(Inflector::pluralize('categoria'), 'categorias'); + $this->assertEquals(Inflector::pluralize('house'), 'houses'); + $this->assertEquals(Inflector::pluralize('powerhouse'), 'powerhouses'); + $this->assertEquals(Inflector::pluralize('Bus'), 'Buses'); + $this->assertEquals(Inflector::pluralize('bus'), 'buses'); + $this->assertEquals(Inflector::pluralize('menu'), 'menus'); + $this->assertEquals(Inflector::pluralize('news'), 'news'); + $this->assertEquals(Inflector::pluralize('food_menu'), 'food_menus'); + $this->assertEquals(Inflector::pluralize('Menu'), 'Menus'); + $this->assertEquals(Inflector::pluralize('FoodMenu'), 'FoodMenus'); + $this->assertEquals(Inflector::pluralize('quiz'), 'quizzes'); + $this->assertEquals(Inflector::pluralize('matrix_row'), 'matrix_rows'); + $this->assertEquals(Inflector::pluralize('matrix'), 'matrices'); + $this->assertEquals(Inflector::pluralize('vertex'), 'vertices'); + $this->assertEquals(Inflector::pluralize('index'), 'indices'); + $this->assertEquals(Inflector::pluralize('Alias'), 'Aliases'); + $this->assertEquals(Inflector::pluralize('Aliases'), 'Aliases'); + $this->assertEquals(Inflector::pluralize('Media'), 'Media'); + $this->assertEquals(Inflector::pluralize('NodeMedia'), 'NodeMedia'); + $this->assertEquals(Inflector::pluralize('alumnus'), 'alumni'); + $this->assertEquals(Inflector::pluralize('bacillus'), 'bacilli'); + $this->assertEquals(Inflector::pluralize('cactus'), 'cacti'); + $this->assertEquals(Inflector::pluralize('focus'), 'foci'); + $this->assertEquals(Inflector::pluralize('fungus'), 'fungi'); + $this->assertEquals(Inflector::pluralize('nucleus'), 'nuclei'); + $this->assertEquals(Inflector::pluralize('octopus'), 'octopuses'); + $this->assertEquals(Inflector::pluralize('radius'), 'radii'); + $this->assertEquals(Inflector::pluralize('stimulus'), 'stimuli'); + $this->assertEquals(Inflector::pluralize('syllabus'), 'syllabi'); + $this->assertEquals(Inflector::pluralize('terminus'), 'termini'); + $this->assertEquals(Inflector::pluralize('virus'), 'viri'); + $this->assertEquals(Inflector::pluralize('person'), 'people'); + $this->assertEquals(Inflector::pluralize('people'), 'people'); + $this->assertEquals(Inflector::pluralize('glove'), 'gloves'); + $this->assertEquals(Inflector::pluralize('crisis'), 'crises'); + $this->assertEquals(Inflector::pluralize('tax'), 'taxes'); + $this->assertEquals(Inflector::pluralize('wave'), 'waves'); + $this->assertEquals(Inflector::pluralize('bureau'), 'bureaus'); + $this->assertEquals(Inflector::pluralize('cafe'), 'cafes'); + $this->assertEquals(Inflector::pluralize('roof'), 'roofs'); + $this->assertEquals(Inflector::pluralize('foe'), 'foes'); + $this->assertEquals(Inflector::pluralize(''), ''); + } + +/** + * testInflectorSlug method + * + * @return void + */ + public function testInflectorSlug() { + $result = Inflector::slug('Foo Bar: Not just for breakfast any-more'); + $expected = 'Foo_Bar_Not_just_for_breakfast_any_more'; + $this->assertEquals($expected, $result); + + $result = Inflector::slug('this/is/a/path'); + $expected = 'this_is_a_path'; + $this->assertEquals($expected, $result); + + $result = Inflector::slug('Foo Bar: Not just for breakfast any-more', "-"); + $expected = 'Foo-Bar-Not-just-for-breakfast-any-more'; + $this->assertEquals($expected, $result); + + $result = Inflector::slug('Foo Bar: Not just for breakfast any-more', "+"); + $expected = 'Foo+Bar+Not+just+for+breakfast+any+more'; + $this->assertEquals($expected, $result); + + $result = Inflector::slug('Äpfel Über Öl grün ärgert groß öko', '-'); + $expected = 'Aepfel-Ueber-Oel-gruen-aergert-gross-oeko'; + $this->assertEquals($expected, $result); + + $result = Inflector::slug('The truth - and- more- news', '-'); + $expected = 'The-truth-and-more-news'; + $this->assertEquals($expected, $result); + + $result = Inflector::slug('The truth: and more news', '-'); + $expected = 'The-truth-and-more-news'; + $this->assertEquals($expected, $result); + + $result = Inflector::slug('La langue française est un attribut de souveraineté en France', '-'); + $expected = 'La-langue-francaise-est-un-attribut-de-souverainete-en-France'; + $this->assertEquals($expected, $result); + + $result = Inflector::slug('!@$#exciting stuff! - what !@-# was that?', '-'); + $expected = 'exciting-stuff-what-was-that'; + $this->assertEquals($expected, $result); + + $result = Inflector::slug('20% of profits went to me!', '-'); + $expected = '20-of-profits-went-to-me'; + $this->assertEquals($expected, $result); + + $result = Inflector::slug('#this melts your face1#2#3', '-'); + $expected = 'this-melts-your-face1-2-3'; + $this->assertEquals($expected, $result); + + $result = Inflector::slug('controller/action/りんご/1'); + $expected = 'controller_action_りんご_1'; + $this->assertEquals($expected, $result); + + $result = Inflector::slug('の話が出たので大丈夫かなあと'); + $expected = 'の話が出たので大丈夫かなあと'; + $this->assertEquals($expected, $result); + + $result = Inflector::slug('posts/view/한국어/page:1/sort:asc'); + $expected = 'posts_view_한국어_page_1_sort_asc'; + $this->assertEquals($expected, $result); + } + +/** + * testInflectorSlugWithMap method + * + * @return void + */ + public function testInflectorSlugWithMap() { + Inflector::rules('transliteration', array('/r/' => '1')); + $result = Inflector::slug('replace every r'); + $expected = '1eplace_eve1y_1'; + $this->assertEquals($expected, $result); + + $result = Inflector::slug('replace every r', '_'); + $expected = '1eplace_eve1y_1'; + $this->assertEquals($expected, $result); + } + +/** + * testInflectorSlugWithMapOverridingDefault method + * + * @return void + */ + public function testInflectorSlugWithMapOverridingDefault() { + Inflector::rules('transliteration', array('/å/' => 'aa', '/ø/' => 'oe')); + $result = Inflector::slug('Testing æ ø å', '-'); + $expected = 'Testing-ae-oe-aa'; + $this->assertEquals($expected, $result); + } + +/** + * testInflectorUnderscore method + * + * @return void + */ + public function testInflectorUnderscore() { + $this->assertSame(Inflector::underscore('TestThing'), 'test_thing'); + $this->assertSame(Inflector::underscore('testThing'), 'test_thing'); + $this->assertSame(Inflector::underscore('TestThingExtra'), 'test_thing_extra'); + $this->assertSame(Inflector::underscore('testThingExtra'), 'test_thing_extra'); + + // Identical checks test the cache code path. + $this->assertSame(Inflector::underscore('TestThing'), 'test_thing'); + $this->assertSame(Inflector::underscore('testThing'), 'test_thing'); + $this->assertSame(Inflector::underscore('TestThingExtra'), 'test_thing_extra'); + $this->assertSame(Inflector::underscore('testThingExtra'), 'test_thing_extra'); + + // Test stupid values + $this->assertSame(Inflector::underscore(''), ''); + $this->assertSame(Inflector::underscore(0), '0'); + $this->assertSame(Inflector::underscore(false), ''); + } + +/** + * testVariableNaming method + * + * @return void + */ + public function testVariableNaming() { + $this->assertEquals(Inflector::variable('test_field'), 'testField'); + $this->assertEquals(Inflector::variable('test_fieLd'), 'testFieLd'); + $this->assertEquals(Inflector::variable('test field'), 'testField'); + $this->assertEquals(Inflector::variable('Test_field'), 'testField'); + } + +/** + * testClassNaming method + * + * @return void + */ + public function testClassNaming() { + $this->assertEquals(Inflector::classify('artists_genres'), 'ArtistsGenre'); + $this->assertEquals(Inflector::classify('file_systems'), 'FileSystem'); + $this->assertEquals(Inflector::classify('news'), 'News'); + $this->assertEquals(Inflector::classify('bureaus'), 'Bureau'); + } + +/** + * testTableNaming method + * + * @return void + */ + public function testTableNaming() { + $this->assertEquals(Inflector::tableize('ArtistsGenre'), 'artists_genres'); + $this->assertEquals(Inflector::tableize('FileSystem'), 'file_systems'); + $this->assertEquals(Inflector::tableize('News'), 'news'); + $this->assertEquals(Inflector::tableize('Bureau'), 'bureaus'); + } + +/** + * testHumanization method + * + * @return void + */ + public function testHumanization() { + $this->assertEquals(Inflector::humanize('posts'), 'Posts'); + $this->assertEquals(Inflector::humanize('posts_tags'), 'Posts Tags'); + $this->assertEquals(Inflector::humanize('file_systems'), 'File Systems'); + } + +/** + * testCustomPluralRule method + * + * @return void + */ + public function testCustomPluralRule() { + Inflector::rules('plural', array('/^(custom)$/i' => '\1izables')); + $this->assertEquals(Inflector::pluralize('custom'), 'customizables'); + + Inflector::rules('plural', array('uninflected' => array('uninflectable'))); + $this->assertEquals(Inflector::pluralize('uninflectable'), 'uninflectable'); + + Inflector::rules('plural', array( + 'rules' => array('/^(alert)$/i' => '\1ables'), + 'uninflected' => array('noflect', 'abtuse'), + 'irregular' => array('amaze' => 'amazable', 'phone' => 'phonezes') + )); + $this->assertEquals(Inflector::pluralize('noflect'), 'noflect'); + $this->assertEquals(Inflector::pluralize('abtuse'), 'abtuse'); + $this->assertEquals(Inflector::pluralize('alert'), 'alertables'); + $this->assertEquals(Inflector::pluralize('amaze'), 'amazable'); + $this->assertEquals(Inflector::pluralize('phone'), 'phonezes'); + } + +/** + * testCustomSingularRule method + * + * @return void + */ + public function testCustomSingularRule() { + Inflector::rules('singular', array('/(eple)r$/i' => '\1', '/(jente)r$/i' => '\1')); + + $this->assertEquals(Inflector::singularize('epler'), 'eple'); + $this->assertEquals(Inflector::singularize('jenter'), 'jente'); + + Inflector::rules('singular', array( + 'rules' => array('/^(bil)er$/i' => '\1', '/^(inflec|contribu)tors$/i' => '\1ta'), + 'uninflected' => array('singulars'), + 'irregular' => array('spins' => 'spinor') + )); + + $this->assertEquals(Inflector::singularize('inflectors'), 'inflecta'); + $this->assertEquals(Inflector::singularize('contributors'), 'contributa'); + $this->assertEquals(Inflector::singularize('spins'), 'spinor'); + $this->assertEquals(Inflector::singularize('singulars'), 'singulars'); + } + +/** + * testCustomTransliterationRule method + * + * @return void + */ + public function testCustomTransliterationRule() { + $this->assertEquals(Inflector::slug('Testing æ ø å'), 'Testing_ae_o_a'); + + Inflector::rules('transliteration', array('/å/' => 'aa', '/ø/' => 'oe')); + $this->assertEquals(Inflector::slug('Testing æ ø å'), 'Testing_ae_oe_aa'); + + Inflector::rules('transliteration', array('/ä|æ/' => 'ae', '/å/' => 'aa'), true); + $this->assertEquals(Inflector::slug('Testing æ ø å'), 'Testing_ae_ø_aa'); + } + +/** + * test that setting new rules clears the inflector caches. + * + * @return void + */ + public function testRulesClearsCaches() { + $this->assertEquals(Inflector::singularize('Bananas'), 'Banana'); + $this->assertEquals(Inflector::tableize('Banana'), 'bananas'); + $this->assertEquals(Inflector::pluralize('Banana'), 'Bananas'); + + Inflector::rules('singular', array( + 'rules' => array('/(.*)nas$/i' => '\1zzz') + )); + $this->assertEquals('Banazzz', Inflector::singularize('Bananas'), 'Was inflected with old rules.'); + + Inflector::rules('plural', array( + 'rules' => array('/(.*)na$/i' => '\1zzz'), + 'irregular' => array('corpus' => 'corpora') + )); + $this->assertEquals(Inflector::pluralize('Banana'), 'Banazzz', 'Was inflected with old rules.'); + $this->assertEquals(Inflector::pluralize('corpus'), 'corpora', 'Was inflected with old irregular form.'); + } + +/** + * Test resetting inflection rules. + * + * @return void + */ + public function testCustomRuleWithReset() { + $uninflected = array('atlas', 'lapis', 'onibus', 'pires', 'virus', '.*x'); + $pluralIrregular = array('as' => 'ases'); + + Inflector::rules('singular', array( + 'rules' => array('/^(.*)(a|e|o|u)is$/i' => '\1\2l'), + 'uninflected' => $uninflected, + ), true); + + Inflector::rules('plural', array( + 'rules' => array( + '/^(.*)(a|e|o|u)l$/i' => '\1\2is', + ), + 'uninflected' => $uninflected, + 'irregular' => $pluralIrregular + ), true); + + $this->assertEquals(Inflector::pluralize('Alcool'), 'Alcoois'); + $this->assertEquals(Inflector::pluralize('Atlas'), 'Atlas'); + $this->assertEquals(Inflector::singularize('Alcoois'), 'Alcool'); + $this->assertEquals(Inflector::singularize('Atlas'), 'Atlas'); + } + +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Utility/ObjectCollectionTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Utility/ObjectCollectionTest.php new file mode 100644 index 0000000..c8adc05 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Utility/ObjectCollectionTest.php @@ -0,0 +1,595 @@ +_Collection = $collection; + $this->settings = $settings; + } + +} + +/** + * First Extension of Generic Object + */ +class FirstGenericObject extends GenericObject { + +/** + * A generic callback + */ + public function callback() { + } + +} + +/** + * Second Extension of Generic Object + */ +class SecondGenericObject extends GenericObject { + + public function callback() { + } + +} + +/** + * Third Extension of Generic Object + */ +class ThirdGenericObject extends GenericObject { + + public function callback() { + } + +} + +/** + * A collection of Generic objects + */ +class GenericObjectCollection extends ObjectCollection { + +/** + * Loads a generic object + * + * @param string $object Object name + * @param array $settings Settings array + * @return array List of loaded objects + */ + public function load($object, $settings = array()) { + list($plugin, $name) = pluginSplit($object); + if (isset($this->_loaded[$name])) { + return $this->_loaded[$name]; + } + $objectClass = $name . 'GenericObject'; + $this->_loaded[$name] = new $objectClass($this, $settings); + $enable = isset($settings['enabled']) ? $settings['enabled'] : true; + if ($enable === true) { + $this->enable($name); + } + return $this->_loaded[$name]; + } + +} + +class ObjectCollectionTest extends CakeTestCase { + +/** + * setUp + * + * @return void + */ + public function setUp() { + parent::setUp(); + $this->Objects = new GenericObjectCollection(); + } + +/** + * tearDown + * + * @return void + */ + public function tearDown() { + parent::tearDown(); + unset($this->Objects); + } + +/** + * test triggering callbacks on loaded helpers + * + * @return void + */ + public function testLoad() { + $result = $this->Objects->load('First'); + $this->assertInstanceOf('FirstGenericObject', $result); + $this->assertInstanceOf('FirstGenericObject', $this->Objects->First); + + $result = $this->Objects->attached(); + $this->assertEquals(array('First'), $result, 'attached() results are wrong.'); + + $this->assertTrue($this->Objects->enabled('First')); + + $result = $this->Objects->load('First'); + $this->assertSame($result, $this->Objects->First); + } + +/** + * test unload() + * + * @return void + */ + public function testUnload() { + $this->Objects->load('First'); + $this->Objects->load('Second'); + + $result = $this->Objects->attached(); + $this->assertEquals(array('First', 'Second'), $result, 'loaded objects are wrong'); + + $this->Objects->unload('First'); + $this->assertFalse(isset($this->Objects->First)); + $this->assertTrue(isset($this->Objects->Second)); + + $result = $this->Objects->attached(); + $this->assertEquals(array('Second'), $result, 'loaded objects are wrong'); + + $result = $this->Objects->enabled(); + $this->assertEquals(array('Second'), $result, 'enabled objects are wrong'); + } + +/** + * Tests set() + * + * @return void + */ + public function testSet() { + $this->Objects->load('First'); + + $result = $this->Objects->attached(); + $this->assertEquals(array('First'), $result, 'loaded objects are wrong'); + + $result = $this->Objects->set('First', new SecondGenericObject($this->Objects)); + $this->assertInstanceOf('SecondGenericObject', $result['First'], 'set failed'); + + $result = $this->Objects->set('Second', new SecondGenericObject($this->Objects)); + $this->assertInstanceOf('SecondGenericObject', $result['Second'], 'set failed'); + + $this->assertEquals(2, count($result)); + } + +/** + * creates mock classes for testing + * + * @return void + */ + protected function _makeMockClasses() { + if (!class_exists('TriggerMockFirstGenericObject')) { + $this->getMock('FirstGenericObject', array(), array(), 'TriggerMockFirstGenericObject', false); + } + if (!class_exists('TriggerMockSecondGenericObject')) { + $this->getMock('SecondGenericObject', array(), array(), 'TriggerMockSecondGenericObject', false); + } + if (!class_exists('TriggerMockThirdGenericObject')) { + $this->getMock('ThirdGenericObject', array(), array(), 'TriggerMockThirdGenericObject', false); + } + } + +/** + * test triggering callbacks. + * + * @return void + */ + public function testTrigger() { + $this->_makeMockClasses(); + $this->Objects->load('TriggerMockFirst'); + $this->Objects->load('TriggerMockSecond'); + + $this->mockObjects[] = $this->Objects->TriggerMockFirst; + $this->mockObjects[] = $this->Objects->TriggerMockSecond; + + $this->Objects->TriggerMockFirst->expects($this->once()) + ->method('callback') + ->will($this->returnValue(true)); + $this->Objects->TriggerMockSecond->expects($this->once()) + ->method('callback') + ->will($this->returnValue(true)); + + $this->assertTrue($this->Objects->trigger('callback')); + } + +/** + * test trigger and disabled objects + * + * @return void + */ + public function testTriggerWithDisabledObjects() { + $this->_makeMockClasses(); + $this->Objects->load('TriggerMockFirst'); + $this->Objects->load('TriggerMockSecond'); + + $this->mockObjects[] = $this->Objects->TriggerMockFirst; + $this->mockObjects[] = $this->Objects->TriggerMockSecond; + + $this->Objects->TriggerMockFirst->expects($this->once()) + ->method('callback') + ->will($this->returnValue(true)); + $this->Objects->TriggerMockSecond->expects($this->never()) + ->method('callback') + ->will($this->returnValue(true)); + + $this->Objects->disable('TriggerMockSecond'); + + $this->assertTrue($this->Objects->trigger('callback', array())); + } + +/** + * test that the collectReturn option works. + * + * @return void + */ + public function testTriggerWithCollectReturn() { + $this->_makeMockClasses(); + $this->Objects->load('TriggerMockFirst'); + $this->Objects->load('TriggerMockSecond'); + + $this->mockObjects[] = $this->Objects->TriggerMockFirst; + $this->mockObjects[] = $this->Objects->TriggerMockSecond; + + $this->Objects->TriggerMockFirst->expects($this->once()) + ->method('callback') + ->will($this->returnValue(array('one', 'two'))); + $this->Objects->TriggerMockSecond->expects($this->once()) + ->method('callback') + ->will($this->returnValue(array('three', 'four'))); + + $result = $this->Objects->trigger('callback', array(), array('collectReturn' => true)); + $expected = array( + array('one', 'two'), + array('three', 'four') + ); + $this->assertEquals($expected, $result); + } + +/** + * test that trigger with break & breakOn works. + * + * @return void + */ + public function testTriggerWithBreak() { + $this->_makeMockClasses(); + $this->Objects->load('TriggerMockFirst'); + $this->Objects->load('TriggerMockSecond'); + + $this->mockObjects[] = $this->Objects->TriggerMockFirst; + $this->mockObjects[] = $this->Objects->TriggerMockSecond; + + $this->Objects->TriggerMockFirst->expects($this->once()) + ->method('callback') + ->will($this->returnValue(false)); + $this->Objects->TriggerMockSecond->expects($this->never()) + ->method('callback'); + + $result = $this->Objects->trigger( + 'callback', + array(), + array('break' => true, 'breakOn' => false) + ); + $this->assertFalse($result); + } + +/** + * test that trigger with modParams works. + * + * @return void + */ + public function testTriggerWithModParams() { + $this->_makeMockClasses(); + $this->Objects->load('TriggerMockFirst'); + $this->Objects->load('TriggerMockSecond'); + + $this->mockObjects[] = $this->Objects->TriggerMockFirst; + $this->mockObjects[] = $this->Objects->TriggerMockSecond; + + $this->Objects->TriggerMockFirst->expects($this->once()) + ->method('callback') + ->with(array('value')) + ->will($this->returnValue(array('new value'))); + + $this->Objects->TriggerMockSecond->expects($this->once()) + ->method('callback') + ->with(array('new value')) + ->will($this->returnValue(array('newer value'))); + + $result = $this->Objects->trigger( + 'callback', + array(array('value')), + array('modParams' => 0) + ); + $this->assertEquals(array('newer value'), $result); + } + +/** + * test that setting modParams to an index that doesn't exist doesn't cause errors. + * + * @expectedException CakeException + * @return void + */ + public function testTriggerModParamsInvalidIndex() { + $this->_makeMockClasses(); + $this->Objects->load('TriggerMockFirst'); + $this->Objects->load('TriggerMockSecond'); + + $this->mockObjects[] = $this->Objects->TriggerMockFirst; + $this->mockObjects[] = $this->Objects->TriggerMockSecond; + + $this->Objects->TriggerMockFirst->expects($this->never()) + ->method('callback'); + + $this->Objects->TriggerMockSecond->expects($this->never()) + ->method('callback'); + + $result = $this->Objects->trigger( + 'callback', + array(array('value')), + array('modParams' => 2) + ); + } + +/** + * test that returning null doesn't modify parameters. + * + * @return void + */ + public function testTriggerModParamsNullIgnored() { + $this->_makeMockClasses(); + $this->Objects->load('TriggerMockFirst'); + $this->Objects->load('TriggerMockSecond'); + + $this->mockObjects[] = $this->Objects->TriggerMockFirst; + $this->mockObjects[] = $this->Objects->TriggerMockSecond; + + $this->Objects->TriggerMockFirst->expects($this->once()) + ->method('callback') + ->with(array('value')) + ->will($this->returnValue(null)); + + $this->Objects->TriggerMockSecond->expects($this->once()) + ->method('callback') + ->with(array('value')) + ->will($this->returnValue(array('new value'))); + + $result = $this->Objects->trigger( + 'callback', + array(array('value')), + array('modParams' => 0) + ); + $this->assertEquals(array('new value'), $result); + } + +/** + * test order of callbacks triggering based on priority. + * + * @return void + */ + public function testTriggerPriority() { + $this->_makeMockClasses(); + $this->Objects->load('TriggerMockFirst'); + $this->Objects->load('TriggerMockSecond', array('priority' => 5)); + + $this->mockObjects[] = $this->Objects->TriggerMockFirst; + $this->mockObjects[] = $this->Objects->TriggerMockSecond; + + $this->Objects->TriggerMockFirst->expects($this->any()) + ->method('callback') + ->will($this->returnValue('1st')); + $this->Objects->TriggerMockSecond->expects($this->any()) + ->method('callback') + ->will($this->returnValue('2nd')); + + $result = $this->Objects->trigger('callback', array(), array('collectReturn' => true)); + $expected = array( + '2nd', + '1st' + ); + $this->assertEquals($expected, $result); + + $this->Objects->load('TriggerMockThird', array('priority' => 7)); + $this->mockObjects[] = $this->Objects->TriggerMockThird; + $this->Objects->TriggerMockThird->expects($this->any()) + ->method('callback') + ->will($this->returnValue('3rd')); + + $result = $this->Objects->trigger('callback', array(), array('collectReturn' => true)); + $expected = array( + '2nd', + '3rd', + '1st' + ); + $this->assertEquals($expected, $result); + + $this->Objects->disable('TriggerMockFirst'); + $result = $this->Objects->trigger('callback', array(), array('collectReturn' => true)); + $expected = array( + '2nd', + '3rd' + ); + $this->assertEquals($expected, $result); + + $this->Objects->enable('TriggerMockFirst'); + $result = $this->Objects->trigger('callback', array(), array('collectReturn' => true)); + $expected = array( + '2nd', + '3rd', + '1st' + ); + $this->assertEquals($expected, $result); + + $this->Objects->disable('TriggerMockThird'); + $result = $this->Objects->trigger('callback', array(), array('collectReturn' => true)); + $expected = array( + '2nd', + '1st' + ); + $this->assertEquals($expected, $result); + + $this->Objects->enable('TriggerMockThird', false); + $result = $this->Objects->trigger('callback', array(), array('collectReturn' => true)); + $expected = array( + '2nd', + '1st', + '3rd' + ); + $this->assertEquals($expected, $result); + + $this->Objects->setPriority('TriggerMockThird', 1); + $result = $this->Objects->trigger('callback', array(), array('collectReturn' => true)); + $expected = array( + '3rd', + '2nd', + '1st' + ); + $this->assertEquals($expected, $result); + + $this->Objects->disable('TriggerMockThird'); + $this->Objects->setPriority('TriggerMockThird', 11); + $result = $this->Objects->trigger('callback', array(), array('collectReturn' => true)); + $expected = array( + '2nd', + '1st' + ); + $this->assertEquals($expected, $result); + + $this->Objects->enable('TriggerMockThird'); + $result = $this->Objects->trigger('callback', array(), array('collectReturn' => true)); + $expected = array( + '2nd', + '1st', + '3rd' + ); + $this->assertEquals($expected, $result); + + $this->Objects->setPriority('TriggerMockThird'); + $result = $this->Objects->trigger('callback', array(), array('collectReturn' => true)); + $expected = array( + '2nd', + '1st', + '3rd' + ); + $this->assertEquals($expected, $result); + } + +/** + * test normalizeObjectArray + * + * @return void + */ + public function testnormalizeObjectArray() { + $components = array( + 'Html', + 'Foo.Bar' => array('one', 'two'), + 'Something', + 'Banana.Apple' => array('foo' => 'bar') + ); + $result = ObjectCollection::normalizeObjectArray($components); + $expected = array( + 'Html' => array('class' => 'Html', 'settings' => array()), + 'Bar' => array('class' => 'Foo.Bar', 'settings' => array('one', 'two')), + 'Something' => array('class' => 'Something', 'settings' => array()), + 'Apple' => array('class' => 'Banana.Apple', 'settings' => array('foo' => 'bar')), + ); + $this->assertEquals($expected, $result); + + // This is the result after Controller::_mergeVars + $components = array( + 'Html' => null, + 'Foo.Bar' => array('one', 'two'), + 'Something' => null, + 'Banana.Apple' => array('foo' => 'bar') + ); + $result = ObjectCollection::normalizeObjectArray($components); + $this->assertEquals($expected, $result); + } + +/** + * tests that passing an instance of CakeEvent to trigger will prepend the subject to the list of arguments + * + * @return void + */ + public function testDispatchEventWithSubject() { + $this->_makeMockClasses(); + $this->Objects->load('TriggerMockFirst'); + $this->Objects->load('TriggerMockSecond'); + + $this->mockObjects[] = $this->Objects->TriggerMockFirst; + $this->mockObjects[] = $this->Objects->TriggerMockSecond; + + $subjectClass = new Object(); + $this->Objects->TriggerMockFirst->expects($this->once()) + ->method('callback') + ->with($subjectClass, 'first argument') + ->will($this->returnValue(true)); + $this->Objects->TriggerMockSecond->expects($this->once()) + ->method('callback') + ->with($subjectClass, 'first argument') + ->will($this->returnValue(true)); + + $event = new CakeEvent('callback', $subjectClass, array('first argument')); + $this->assertTrue($this->Objects->trigger($event)); + } + +/** + * tests that passing an instance of CakeEvent to trigger with omitSubject property + * will NOT prepend the subject to the list of arguments + * + * @return void + */ + public function testDispatchEventNoSubject() { + $this->_makeMockClasses(); + $this->Objects->load('TriggerMockFirst'); + $this->Objects->load('TriggerMockSecond'); + + $this->mockObjects[] = $this->Objects->TriggerMockFirst; + $this->mockObjects[] = $this->Objects->TriggerMockSecond; + + $subjectClass = new Object(); + $this->Objects->TriggerMockFirst->expects($this->once()) + ->method('callback') + ->with('first argument') + ->will($this->returnValue(true)); + $this->Objects->TriggerMockSecond->expects($this->once()) + ->method('callback') + ->with('first argument') + ->will($this->returnValue(true)); + + $event = new CakeEvent('callback', $subjectClass, array('first argument')); + $event->omitSubject = true; + $this->assertTrue($this->Objects->trigger($event)); + } + +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Utility/SanitizeTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Utility/SanitizeTest.php new file mode 100644 index 0000000..13ba63c --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Utility/SanitizeTest.php @@ -0,0 +1,462 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Utility + * @since CakePHP(tm) v 1.2.0.5428 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ +App::uses('Sanitize', 'Utility'); + +/** + * DataTest class + * + * @package Cake.Test.Case.Utility + */ +class SanitizeDataTest extends CakeTestModel { + +/** + * name property + * + * @var string 'SanitizeDataTest' + */ + public $name = 'SanitizeDataTest'; + +/** + * useTable property + * + * @var string 'data_tests' + */ + public $useTable = 'data_tests'; +} + +/** + * Article class + * + * @package Cake.Test.Case.Utility + */ +class SanitizeArticle extends CakeTestModel { + +/** + * name property + * + * @var string 'Article' + */ + public $name = 'SanitizeArticle'; + +/** + * useTable property + * + * @var string 'articles' + */ + public $useTable = 'articles'; +} + +/** + * SanitizeTest class + * + * @package Cake.Test.Case.Utility + */ +class SanitizeTest extends CakeTestCase { + +/** + * autoFixtures property + * + * @var bool false + */ + public $autoFixtures = false; + +/** + * fixtures property + * + * @var array + */ + public $fixtures = array('core.data_test', 'core.article'); + +/** + * testEscapeAlphaNumeric method + * + * @return void + */ + public function testEscapeAlphaNumeric() { + $resultAlpha = Sanitize::escape('abc', 'test'); + $this->assertEquals('abc', $resultAlpha); + + $resultNumeric = Sanitize::escape('123', 'test'); + $this->assertEquals('123', $resultNumeric); + + $resultNumeric = Sanitize::escape(1234, 'test'); + $this->assertEquals(1234, $resultNumeric); + + $resultNumeric = Sanitize::escape(1234.23, 'test'); + $this->assertEquals(1234.23, $resultNumeric); + + $resultNumeric = Sanitize::escape('#1234.23', 'test'); + $this->assertEquals('#1234.23', $resultNumeric); + + $resultNull = Sanitize::escape(null, 'test'); + $this->assertEquals(null, $resultNull); + + $resultNull = Sanitize::escape(false, 'test'); + $this->assertEquals(false, $resultNull); + + $resultNull = Sanitize::escape(true, 'test'); + $this->assertEquals(true, $resultNull); + } + +/** + * testClean method + * + * @return void + */ + public function testClean() { + $string = 'test & "quote" \'other\' ;.$ symbol.' . "\r" . 'another line'; + $expected = 'test & "quote" 'other' ;.$ symbol.another line'; + $result = Sanitize::clean($string, array('connection' => 'test')); + $this->assertEquals($expected, $result); + + $string = 'test & "quote" \'other\' ;.$ symbol.' . "\r" . 'another line'; + $expected = 'test & ' . Sanitize::escape('"quote"', 'test') . ' ' . Sanitize::escape('\'other\'', 'test') . ' ;.$ symbol.another line'; + $result = Sanitize::clean($string, array('encode' => false, 'connection' => 'test')); + $this->assertEquals($expected, $result); + + $string = 'test & "quote" \'other\' ;.$ \\$ symbol.' . "\r" . 'another line'; + $expected = 'test & "quote" \'other\' ;.$ $ symbol.another line'; + $result = Sanitize::clean($string, array('encode' => false, 'escape' => false, 'connection' => 'test')); + $this->assertEquals($expected, $result); + + $string = 'test & "quote" \'other\' ;.$ \\$ symbol.' . "\r" . 'another line'; + $expected = 'test & "quote" \'other\' ;.$ \\$ symbol.another line'; + $result = Sanitize::clean($string, array('encode' => false, 'escape' => false, 'dollar' => false, 'connection' => 'test')); + $this->assertEquals($expected, $result); + + $string = 'test & "quote" \'other\' ;.$ symbol.' . "\r" . 'another line'; + $expected = 'test & "quote" \'other\' ;.$ symbol.' . "\r" . 'another line'; + $result = Sanitize::clean($string, array('encode' => false, 'escape' => false, 'carriage' => false, 'connection' => 'test')); + $this->assertEquals($expected, $result); + + $array = array(array('test & "quote" \'other\' ;.$ symbol.' . "\r" . 'another line')); + $expected = array(array('test & "quote" 'other' ;.$ symbol.another line')); + $result = Sanitize::clean($array, array('connection' => 'test')); + $this->assertEquals($expected, $result); + + $array = array(array('test & "quote" \'other\' ;.$ \\$ symbol.' . "\r" . 'another line')); + $expected = array(array('test & "quote" \'other\' ;.$ $ symbol.another line')); + $result = Sanitize::clean($array, array('encode' => false, 'escape' => false, 'connection' => 'test')); + $this->assertEquals($expected, $result); + + $array = array(array('test odd Ä spacesé')); + $expected = array(array('test odd Ä spacesé')); + $result = Sanitize::clean($array, array('odd_spaces' => false, 'escape' => false, 'connection' => 'test')); + $this->assertEquals($expected, $result); + + $array = array(array('\\$', array('key' => 'test & "quote" \'other\' ;.$ \\$ symbol.' . "\r" . 'another line'))); + $expected = array(array('$', array('key' => 'test & "quote" \'other\' ;.$ $ symbol.another line'))); + $result = Sanitize::clean($array, array('encode' => false, 'escape' => false, 'connection' => 'test')); + $this->assertEquals($expected, $result); + + $string = ''; + $expected = ''; + $result = Sanitize::clean($string, array('connection' => 'test')); + $this->assertEquals($expected, $string); + + $data = array( + 'Grant' => array( + 'title' => '2 o clock grant', + 'grant_peer_review_id' => 3, + 'institution_id' => 5, + 'created_by' => 1, + 'modified_by' => 1, + 'created' => '2010-07-15 14:11:00', + 'modified' => '2010-07-19 10:45:41' + ), + 'GrantsMember' => array( + 0 => array( + 'id' => 68, + 'grant_id' => 120, + 'member_id' => 16, + 'program_id' => 29, + 'pi_percent_commitment' => 1 + ) + ) + ); + $result = Sanitize::clean($data, array('connection' => 'test')); + $this->assertEquals($data, $result); + } + +/** + * testHtml method + * + * @return void + */ + public function testHtml() { + $string = '

This is a test string & so is this

'; + $expected = 'This is a test string & so is this'; + $result = Sanitize::html($string, array('remove' => true)); + $this->assertEquals($expected, $result); + + $string = 'The "lazy" dog \'jumped\' & flew over the moon. If (1+1) = 2 is true, (2-1) = 1 is also true'; + $expected = 'The "lazy" dog 'jumped' & flew over the moon. If (1+1) = 2 <em>is</em> true, (2-1) = 1 is also true'; + $result = Sanitize::html($string); + $this->assertEquals($expected, $result); + + $string = 'The "lazy" dog \'jumped\''; + $expected = 'The "lazy" dog \'jumped\''; + $result = Sanitize::html($string, array('quotes' => ENT_COMPAT)); + $this->assertEquals($expected, $result); + + $string = 'The "lazy" dog \'jumped\''; + $result = Sanitize::html($string, array('quotes' => ENT_NOQUOTES)); + $this->assertEquals($string, $result); + + $string = 'The "lazy" dog \'jumped\' & flew over the moon. If (1+1) = 2 is true, (2-1) = 1 is also true'; + $expected = 'The "lazy" dog 'jumped' & flew over the moon. If (1+1) = 2 <em>is</em> true, (2-1) = 1 is also true'; + $result = Sanitize::html($string); + $this->assertEquals($expected, $result); + + $string = 'The "lazy" dog & his friend Apple® conquered the world'; + $expected = 'The "lazy" dog & his friend Apple&reg; conquered the world'; + $result = Sanitize::html($string); + $this->assertEquals($expected, $result); + + $string = 'The "lazy" dog & his friend Apple® conquered the world'; + $expected = 'The "lazy" dog & his friend Apple® conquered the world'; + $result = Sanitize::html($string, array('double' => false)); + $this->assertEquals($expected, $result); + } + +/** + * testStripWhitespace method + * + * @return void + */ + public function testStripWhitespace() { + $string = "This sentence \t\t\t has lots of \n\n white\nspace \rthat \r\n needs to be \t \n trimmed."; + $expected = "This sentence has lots of whitespace that needs to be trimmed."; + $result = Sanitize::stripWhitespace($string); + $this->assertEquals($expected, $result); + + $text = 'I love ßá†ö√ letters.'; + $result = Sanitize::stripWhitespace($text); + $expected = 'I love ßá†ö√ letters.'; + $this->assertEquals($expected, $result); + } + +/** + * testParanoid method + * + * @return void + */ + public function testParanoid() { + $string = 'I would like to !%@#% & dance & sing ^$&*()-+'; + $expected = 'Iwouldliketodancesing'; + $result = Sanitize::paranoid($string); + $this->assertEquals($expected, $result); + + $string = array('This |s th% s0ng that never ends it g*es', + 'on and on my friends, b^ca#use it is the', + 'so&g th===t never ends.'); + $expected = array('This s th% s0ng that never ends it g*es', + 'on and on my friends bcause it is the', + 'sog tht never ends.'); + $result = Sanitize::paranoid($string, array('%', '*', '.', ' ')); + $this->assertEquals($expected, $result); + + $string = "anything' OR 1 = 1"; + $expected = 'anythingOR11'; + $result = Sanitize::paranoid($string); + $this->assertEquals($expected, $result); + + $string = "x' AND email IS NULL; --"; + $expected = 'xANDemailISNULL'; + $result = Sanitize::paranoid($string); + $this->assertEquals($expected, $result); + + $string = "x' AND 1=(SELECT COUNT(*) FROM users); --"; + $expected = "xAND1SELECTCOUNTFROMusers"; + $result = Sanitize::paranoid($string); + $this->assertEquals($expected, $result); + + $string = "x'; DROP TABLE members; --"; + $expected = "xDROPTABLEmembers"; + $result = Sanitize::paranoid($string); + $this->assertEquals($expected, $result); + } + +/** + * testStripImages method + * + * @return void + */ + public function testStripImages() { + $string = 'my image'; + $expected = 'my image
'; + $result = Sanitize::stripImages($string); + $this->assertEquals($expected, $result); + + $string = ''; + $expected = ''; + $result = Sanitize::stripImages($string); + $this->assertEquals($expected, $result); + + $string = 'test image alt'; + $expected = 'test image alt
'; + $result = Sanitize::stripImages($string); + $this->assertEquals($expected, $result); + + $string = ''; + $expected = ''; + $result = Sanitize::stripImages($string); + $this->assertEquals($expected, $result); + } + +/** + * testStripScripts method + * + * @return void + */ + public function testStripScripts() { + $string = ''; + $expected = ''; + $result = Sanitize::stripScripts($string); + $this->assertEquals($expected, $result); + + $string = '' . "\n" . + '' . "\n" . + '' . "\n" . + ''; + $expected = "\n" . '' . "\n" . + '' . "\n" . + ''; + $result = Sanitize::stripScripts($string); + $this->assertEquals($expected, $result); + + $string = ''; + $expected = ''; + $result = Sanitize::stripScripts($string); + $this->assertEquals($expected, $result); + + $string = ''; + $expected = ''; + $result = Sanitize::stripScripts($string); + $this->assertEquals($expected, $result); + + $string = ''; + $expected = ''; + $result = Sanitize::stripScripts($string); + $this->assertEquals($expected, $result); + + $string = ''; + $expected = ''; + $result = Sanitize::stripScripts($string); + $this->assertEquals($expected, $result); + + $string = << + + +text +HTML; + $expected = "text\n\ntext"; + $result = Sanitize::stripScripts($string); + $this->assertTextEquals($expected, $result); + + $string = << + + +text +HTML; + $expected = "text\n\ntext"; + $result = Sanitize::stripScripts($string); + $this->assertTextEquals($expected, $result); + } + +/** + * testStripAll method + * + * @return void + */ + public function testStripAll() { + $string = '"/>'; + $expected = '"/>'; + $result = Sanitize::stripAll($string); + $this->assertEquals($expected, $result); + + $string = ''; + $expected = ''; + $result = Sanitize::stripAll($string); + $this->assertEquals($expected, $result); + + $string = '<'; + $expected = '<'; + $result = Sanitize::stripAll($string); + $this->assertEquals($expected, $result); + + $string = '' . "\n" . + "

This is ok \t\n text

\n" . + '' . "\n" . + ''; + $expected = '

This is ok text

'; + $result = Sanitize::stripAll($string); + $this->assertEquals($expected, $result); + } + +/** + * testStripTags method + * + * @return void + */ + public function testStripTags() { + $string = '

Headline

My Link could go to a bad site

'; + $expected = 'Headline

My Link could go to a bad site

'; + $result = Sanitize::stripTags($string, 'h2', 'a'); + $this->assertEquals($expected, $result); + + $string = ''; + $expected = ' '; + $result = Sanitize::stripTags($string, 'script'); + $this->assertEquals($expected, $result); + + $string = '

Important

Additional information here . Read even more here

'; + $expected = 'Important

Additional information here . Read even more here

'; + $result = Sanitize::stripTags($string, 'h2', 'a'); + $this->assertEquals($expected, $result); + + $string = '

Important

Additional information here . Read even more here

'; + $expected = 'Important

Additional information here . Read even more here

'; + $result = Sanitize::stripTags($string, 'h2', 'a', 'img'); + $this->assertEquals($expected, $result); + + $string = 'Important message!
This message will self destruct!'; + $expected = 'Important message!
This message will self destruct!'; + $result = Sanitize::stripTags($string, 'b'); + $this->assertEquals($expected, $result); + + $string = 'Important message!
This message will self destruct!'; + $expected = 'Important message!
This message will self destruct!'; + $result = Sanitize::stripTags($string, 'b'); + $this->assertEquals($expected, $result); + + $string = '

Important

Additional information here . Read even more here

'; + $expected = 'Important

Additional information here . Read even more here

'; + $result = Sanitize::stripTags($string, 'h2', 'a', 'img'); + $this->assertEquals($expected, $result); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Utility/SecurityTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Utility/SecurityTest.php new file mode 100644 index 0000000..cb323d9 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Utility/SecurityTest.php @@ -0,0 +1,207 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Utility + * @since CakePHP(tm) v 1.2.0.5432 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ +App::uses('Security', 'Utility'); + +/** + * SecurityTest class + * + * @package Cake.Test.Case.Utility + */ +class SecurityTest extends CakeTestCase { + +/** + * sut property + * + * @var mixed null + */ + public $sut = null; + +/** + * testInactiveMins method + * + * @return void + */ + public function testInactiveMins() { + Configure::write('Security.level', 'high'); + $this->assertEquals(10, Security::inactiveMins()); + + Configure::write('Security.level', 'medium'); + $this->assertEquals(100, Security::inactiveMins()); + + Configure::write('Security.level', 'low'); + $this->assertEquals(300, Security::inactiveMins()); + } + +/** + * testGenerateAuthkey method + * + * @return void + */ + public function testGenerateAuthkey() { + $this->assertEquals(strlen(Security::generateAuthKey()), 40); + } + +/** + * testValidateAuthKey method + * + * @return void + */ + public function testValidateAuthKey() { + $authKey = Security::generateAuthKey(); + $this->assertTrue(Security::validateAuthKey($authKey)); + } + +/** + * testHash method + * + * @return void + */ + public function testHash() { + $_hashType = Security::$hashType; + + $key = 'someKey'; + $hash = 'someHash'; + + $this->assertSame(strlen(Security::hash($key, null, false)), 40); + $this->assertSame(strlen(Security::hash($key, 'sha1', false)), 40); + $this->assertSame(strlen(Security::hash($key, null, true)), 40); + $this->assertSame(strlen(Security::hash($key, 'sha1', true)), 40); + + $result = Security::hash($key, null, $hash); + $this->assertSame($result, 'e38fcb877dccb6a94729a81523851c931a46efb1'); + + $result = Security::hash($key, 'sha1', $hash); + $this->assertSame($result, 'e38fcb877dccb6a94729a81523851c931a46efb1'); + + $hashType = 'sha1'; + Security::setHash($hashType); + $this->assertSame(Security::$hashType, $hashType); + $this->assertSame(strlen(Security::hash($key, null, true)), 40); + $this->assertSame(strlen(Security::hash($key, null, false)), 40); + + $this->assertSame(strlen(Security::hash($key, 'md5', false)), 32); + $this->assertSame(strlen(Security::hash($key, 'md5', true)), 32); + + $hashType = 'md5'; + Security::setHash($hashType); + $this->assertSame(Security::$hashType, $hashType); + $this->assertSame(strlen(Security::hash($key, null, false)), 32); + $this->assertSame(strlen(Security::hash($key, null, true)), 32); + + if (!function_exists('hash') && !function_exists('mhash')) { + $this->assertSame(strlen(Security::hash($key, 'sha256', false)), 32); + $this->assertSame(strlen(Security::hash($key, 'sha256', true)), 32); + } else { + $this->assertSame(strlen(Security::hash($key, 'sha256', false)), 64); + $this->assertSame(strlen(Security::hash($key, 'sha256', true)), 64); + } + + Security::setHash($_hashType); + } + +/** + * testCipher method + * + * @return void + */ + public function testCipher() { + $length = 10; + $txt = ''; + for ($i = 0; $i < $length; $i++) { + $txt .= mt_rand(0, 255); + } + $key = 'my_key'; + $result = Security::cipher($txt, $key); + $this->assertEquals($txt, Security::cipher($result, $key)); + + $txt = ''; + $key = 'my_key'; + $result = Security::cipher($txt, $key); + $this->assertEquals($txt, Security::cipher($result, $key)); + + $txt = 123456; + $key = 'my_key'; + $result = Security::cipher($txt, $key); + $this->assertEquals($txt, Security::cipher($result, $key)); + + $txt = '123456'; + $key = 'my_key'; + $result = Security::cipher($txt, $key); + $this->assertEquals($txt, Security::cipher($result, $key)); + } + +/** + * testCipherEmptyKey method + * + * @expectedException PHPUnit_Framework_Error + * @return void + */ + public function testCipherEmptyKey() { + $txt = 'some_text'; + $key = ''; + $result = Security::cipher($txt, $key); + } + +/** + * testRijndael method + * + * @return void + */ + public function testRijndael() { + $txt = 'The quick brown fox jumped over the lazy dog.'; + $key = 'DYhG93b0qyJfIxfs2guVoUubWwvniR2G0FgaC9mi'; + + $result = Security::rijndael($txt, $key, 'encrypt'); + $this->assertEquals($txt, Security::rijndael($result, $key, 'decrypt')); + + $result = Security::rijndael($key, $txt, 'encrypt'); + $this->assertEquals($key, Security::rijndael($result, $txt, 'decrypt')); + + $result = Security::rijndael('', $key, 'encrypt'); + $this->assertEquals('', Security::rijndael($result, $key, 'decrypt')); + + $result = Security::rijndael($txt, $key = 'this is my key of over 32 chars, yes it is', 'encrypt'); + $this->assertEquals($txt, Security::rijndael($result, $key, 'decrypt')); + } + +/** + * testRijndaelInvalidOperation method + * + * @expectedException PHPUnit_Framework_Error + * @return void + */ + public function testRijndaelInvalidOperation() { + $txt = 'The quick brown fox jumped over the lazy dog.'; + $key = 'DYhG93b0qyJfIxfs2guVoUubWwvniR2G0FgaC9mi'; + $result = Security::rijndael($txt, $key, 'foo'); + } + +/** + * testRijndaelInvalidKey method + * + * @expectedException PHPUnit_Framework_Error + * @return void + */ + public function testRijndaelInvalidKey() { + $txt = 'The quick brown fox jumped over the lazy dog.'; + $key = 'too small'; + $result = Security::rijndael($txt, $key, 'encrypt'); + } + +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Utility/SetTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Utility/SetTest.php new file mode 100644 index 0000000..e1c18a8 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Utility/SetTest.php @@ -0,0 +1,3542 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Utility + * @since CakePHP(tm) v 1.2.0.4206 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ +App::uses('Set', 'Utility'); +App::uses('Model', 'Model'); + +/** + * SetTest class + * + * @package Cake.Test.Case.Utility + */ +class SetTest extends CakeTestCase { + +/** + * testNumericKeyExtraction method + * + * @return void + */ + public function testNumericKeyExtraction() { + $data = array('plugin' => null, 'controller' => '', 'action' => '', 1, 'whatever'); + $this->assertEquals(array(1, 'whatever'), Set::extract($data, '{n}')); + $this->assertEquals(array('plugin' => null, 'controller' => '', 'action' => ''), Set::diff($data, Set::extract($data, '{n}'))); + } + +/** + * testEnum method + * + * @return void + */ + public function testEnum() { + $result = Set::enum(1, 'one, two'); + $this->assertEquals('two', $result); + $result = Set::enum(2, 'one, two'); + $this->assertNull($result); + + $set = array('one', 'two'); + $result = Set::enum(0, $set); + $this->assertEquals('one', $result); + $result = Set::enum(1, $set); + $this->assertEquals('two', $result); + + $result = Set::enum(1, array('one', 'two')); + $this->assertEquals('two', $result); + $result = Set::enum(2, array('one', 'two')); + $this->assertNull($result); + + $result = Set::enum('first', array('first' => 'one', 'second' => 'two')); + $this->assertEquals('one', $result); + $result = Set::enum('third', array('first' => 'one', 'second' => 'two')); + $this->assertNull($result); + + $result = Set::enum('no', array('no' => 0, 'yes' => 1)); + $this->assertEquals(0, $result); + $result = Set::enum('not sure', array('no' => 0, 'yes' => 1)); + $this->assertNull($result); + + $result = Set::enum(0); + $this->assertEquals('no', $result); + $result = Set::enum(1); + $this->assertEquals('yes', $result); + $result = Set::enum(2); + $this->assertNull($result); + } + +/** + * testFilter method + * + * @see Hash test cases, as Set::filter() is just a proxy. + * @return void + */ + public function testFilter() { + $result = Set::filter(array('0', false, true, 0, array('one thing', 'I can tell you', 'is you got to be', false))); + $expected = array('0', 2 => true, 3 => 0, 4 => array('one thing', 'I can tell you', 'is you got to be')); + $this->assertSame($expected, $result); + } + +/** + * testNumericArrayCheck method + * + * @see Hash test cases, as Set::numeric() is just a proxy. + * @return void + */ + public function testNumericArrayCheck() { + $data = array('one'); + $this->assertTrue(Set::numeric(array_keys($data))); + } + +/** + * testKeyCheck method + * + * @return void + */ + public function testKeyCheck() { + $data = array('Multi' => array('dimensonal' => array('array'))); + $this->assertTrue(Set::check($data, 'Multi.dimensonal')); + $this->assertFalse(Set::check($data, 'Multi.dimensonal.array')); + + $data = array( + array( + 'Article' => array('id' => '1', 'user_id' => '1', 'title' => 'First Article', 'body' => 'First Article Body', 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31'), + 'User' => array('id' => '1', 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'), + 'Comment' => array( + array('id' => '1', 'article_id' => '1', 'user_id' => '2', 'comment' => 'First Comment for First Article', 'published' => 'Y', 'created' => '2007-03-18 10:45:23', 'updated' => '2007-03-18 10:47:31'), + array('id' => '2', 'article_id' => '1', 'user_id' => '4', 'comment' => 'Second Comment for First Article', 'published' => 'Y', 'created' => '2007-03-18 10:47:23', 'updated' => '2007-03-18 10:49:31'), + ), + 'Tag' => array( + array('id' => '1', 'tag' => 'tag1', 'created' => '2007-03-18 12:22:23', 'updated' => '2007-03-18 12:24:31'), + array('id' => '2', 'tag' => 'tag2', 'created' => '2007-03-18 12:24:23', 'updated' => '2007-03-18 12:26:31') + ) + ), + array( + 'Article' => array('id' => '3', 'user_id' => '1', 'title' => 'Third Article', 'body' => 'Third Article Body', 'published' => 'Y', 'created' => '2007-03-18 10:43:23', 'updated' => '2007-03-18 10:45:31'), + 'User' => array('id' => '1', 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'), + 'Comment' => array(), + 'Tag' => array() + ) + ); + $this->assertTrue(Set::check($data, '0.Article.user_id')); + $this->assertTrue(Set::check($data, '0.Comment.0.id')); + $this->assertFalse(Set::check($data, '0.Comment.0.id.0')); + $this->assertTrue(Set::check($data, '0.Article.user_id')); + $this->assertFalse(Set::check($data, '0.Article.user_id.a')); + } + +/** + * testMerge method + * + * @return void + */ + public function testMerge() { + $r = Set::merge(array('foo')); + $this->assertEquals(array('foo'), $r); + + $r = Set::merge('foo'); + $this->assertEquals(array('foo'), $r); + + $r = Set::merge('foo', 'bar'); + $this->assertEquals(array('foo', 'bar'), $r); + + $r = Set::merge('foo', array('user' => 'bob', 'no-bar'), 'bar'); + $this->assertEquals(array('foo', 'user' => 'bob', 'no-bar', 'bar'), $r); + + $a = array('foo', 'foo2'); + $b = array('bar', 'bar2'); + $this->assertEquals(array('foo', 'foo2', 'bar', 'bar2'), Set::merge($a, $b)); + + $a = array('foo' => 'bar', 'bar' => 'foo'); + $b = array('foo' => 'no-bar', 'bar' => 'no-foo'); + $this->assertEquals(array('foo' => 'no-bar', 'bar' => 'no-foo'), Set::merge($a, $b)); + + $a = array('users' => array('bob', 'jim')); + $b = array('users' => array('lisa', 'tina')); + $this->assertEquals(array('users' => array('bob', 'jim', 'lisa', 'tina')), Set::merge($a, $b)); + + $a = array('users' => array('jim', 'bob')); + $b = array('users' => 'none'); + $this->assertEquals(array('users' => 'none'), Set::merge($a, $b)); + + $a = array('users' => array('lisa' => array('id' => 5, 'pw' => 'secret')), 'cakephp'); + $b = array('users' => array('lisa' => array('pw' => 'new-pass', 'age' => 23)), 'ice-cream'); + $this->assertEquals(array('users' => array('lisa' => array('id' => 5, 'pw' => 'new-pass', 'age' => 23)), 'cakephp', 'ice-cream'), Set::merge($a, $b)); + + $c = array('users' => array('lisa' => array('pw' => 'you-will-never-guess', 'age' => 25, 'pet' => 'dog')), 'chocolate'); + $expected = array('users' => array('lisa' => array('id' => 5, 'pw' => 'you-will-never-guess', 'age' => 25, 'pet' => 'dog')), 'cakephp', 'ice-cream', 'chocolate'); + $this->assertEquals($expected, Set::merge($a, $b, $c)); + + $this->assertEquals(Set::merge($a, $b, array(), $c), $expected); + + $r = Set::merge($a, $b, $c); + $this->assertEquals($expected, $r); + + $a = array('Tree', 'CounterCache', + 'Upload' => array('folder' => 'products', + 'fields' => array('image_1_id', 'image_2_id', 'image_3_id', 'image_4_id', 'image_5_id'))); + $b = array('Cacheable' => array('enabled' => false), + 'Limit', + 'Bindable', + 'Validator', + 'Transactional'); + + $expected = array('Tree', 'CounterCache', + 'Upload' => array('folder' => 'products', + 'fields' => array('image_1_id', 'image_2_id', 'image_3_id', 'image_4_id', 'image_5_id')), + 'Cacheable' => array('enabled' => false), + 'Limit', + 'Bindable', + 'Validator', + 'Transactional'); + + $this->assertEquals($expected, Set::merge($a, $b)); + + $expected = array('Tree' => null, 'CounterCache' => null, + 'Upload' => array('folder' => 'products', + 'fields' => array('image_1_id', 'image_2_id', 'image_3_id', 'image_4_id', 'image_5_id')), + 'Cacheable' => array('enabled' => false), + 'Limit' => null, + 'Bindable' => null, + 'Validator' => null, + 'Transactional' => null); + + $this->assertEquals($expected, Set::normalize(Set::merge($a, $b))); + } + +/** + * testSort method + * + * @return void + */ + public function testSort() { + $a = array( + 0 => array('Person' => array('name' => 'Jeff'), 'Friend' => array(array('name' => 'Nate'))), + 1 => array('Person' => array('name' => 'Tracy'),'Friend' => array(array('name' => 'Lindsay'))) + ); + $b = array( + 0 => array('Person' => array('name' => 'Tracy'),'Friend' => array(array('name' => 'Lindsay'))), + 1 => array('Person' => array('name' => 'Jeff'), 'Friend' => array(array('name' => 'Nate'))) + + ); + $a = Set::sort($a, '{n}.Friend.{n}.name', 'asc'); + $this->assertEquals($a, $b); + + $b = array( + 0 => array('Person' => array('name' => 'Jeff'), 'Friend' => array(array('name' => 'Nate'))), + 1 => array('Person' => array('name' => 'Tracy'),'Friend' => array(array('name' => 'Lindsay'))) + ); + $a = array( + 0 => array('Person' => array('name' => 'Tracy'),'Friend' => array(array('name' => 'Lindsay'))), + 1 => array('Person' => array('name' => 'Jeff'), 'Friend' => array(array('name' => 'Nate'))) + + ); + $a = Set::sort($a, '{n}.Friend.{n}.name', 'desc'); + $this->assertEquals($a, $b); + + $a = array( + 0 => array('Person' => array('name' => 'Jeff'), 'Friend' => array(array('name' => 'Nate'))), + 1 => array('Person' => array('name' => 'Tracy'),'Friend' => array(array('name' => 'Lindsay'))), + 2 => array('Person' => array('name' => 'Adam'),'Friend' => array(array('name' => 'Bob'))) + ); + $b = array( + 0 => array('Person' => array('name' => 'Adam'),'Friend' => array(array('name' => 'Bob'))), + 1 => array('Person' => array('name' => 'Jeff'), 'Friend' => array(array('name' => 'Nate'))), + 2 => array('Person' => array('name' => 'Tracy'),'Friend' => array(array('name' => 'Lindsay'))) + ); + $a = Set::sort($a, '{n}.Person.name', 'asc'); + $this->assertEquals($a, $b); + + $a = array( + array(7,6,4), + array(3,4,5), + array(3,2,1), + ); + + $b = array( + array(3,2,1), + array(3,4,5), + array(7,6,4), + ); + + $a = Set::sort($a, '{n}.{n}', 'asc'); + $this->assertEquals($a, $b); + + $a = array( + array(7,6,4), + array(3,4,5), + array(3,2,array(1,1,1)), + ); + + $b = array( + array(3,2,array(1,1,1)), + array(3,4,5), + array(7,6,4), + ); + + $a = Set::sort($a, '{n}', 'asc'); + $this->assertEquals($a, $b); + + $a = array( + 0 => array('Person' => array('name' => 'Jeff')), + 1 => array('Shirt' => array('color' => 'black')) + ); + $b = array( + 0 => array('Shirt' => array('color' => 'black')), + 1 => array('Person' => array('name' => 'Jeff')), + ); + $a = Set::sort($a, '{n}.Person.name', 'ASC'); + $this->assertEquals($a, $b); + + $names = array( + array('employees' => array(array('name' => array('first' => 'John', 'last' => 'Doe')))), + array('employees' => array(array('name' => array('first' => 'Jane', 'last' => 'Doe')))), + array('employees' => array(array('name' => array()))), + array('employees' => array(array('name' => array()))) + ); + $result = Set::sort($names, '{n}.employees.0.name', 'asc', 1); + $expected = array( + array('employees' => array(array('name' => array('first' => 'John', 'last' => 'Doe')))), + array('employees' => array(array('name' => array('first' => 'Jane', 'last' => 'Doe')))), + array('employees' => array(array('name' => array()))), + array('employees' => array(array('name' => array()))) + ); + $this->assertEquals($expected, $result); + + $menus = array( + 'blogs' => array('title' => 'Blogs', 'weight' => 3), + 'comments' => array('title' => 'Comments', 'weight' => 2), + 'users' => array('title' => 'Users', 'weight' => 1), + ); + $expected = array( + 'users' => array('title' => 'Users', 'weight' => 1), + 'comments' => array('title' => 'Comments', 'weight' => 2), + 'blogs' => array('title' => 'Blogs', 'weight' => 3), + ); + $result = Set::sort($menus, '{[a-z]+}.weight', 'ASC'); + $this->assertEquals($expected, $result); + } + +/** + * test sorting with string keys. + * + * @return void + */ + public function testSortString() { + $toSort = array( + 'four' => array('number' => 4, 'some' => 'foursome'), + 'six' => array('number' => 6, 'some' => 'sixsome'), + 'five' => array('number' => 5, 'some' => 'fivesome'), + 'two' => array('number' => 2, 'some' => 'twosome'), + 'three' => array('number' => 3, 'some' => 'threesome') + ); + $sorted = Set::sort($toSort, '{s}.number', 'asc'); + $expected = array( + 'two' => array('number' => 2, 'some' => 'twosome'), + 'three' => array('number' => 3, 'some' => 'threesome'), + 'four' => array('number' => 4, 'some' => 'foursome'), + 'five' => array('number' => 5, 'some' => 'fivesome'), + 'six' => array('number' => 6, 'some' => 'sixsome') + ); + $this->assertEquals($expected, $sorted); + } + +/** + * test sorting with out of order keys. + * + * @return void + */ + public function testSortWithOutOfOrderKeys() { + $data = array( + 9 => array('class' => 510, 'test2' => 2), + 1 => array('class' => 500, 'test2' => 1), + 2 => array('class' => 600, 'test2' => 2), + 5 => array('class' => 625, 'test2' => 4), + 0 => array('class' => 605, 'test2' => 3), + ); + $expected = array( + array('class' => 500, 'test2' => 1), + array('class' => 510, 'test2' => 2), + array('class' => 600, 'test2' => 2), + array('class' => 605, 'test2' => 3), + array('class' => 625, 'test2' => 4), + ); + $result = Set::sort($data, '{n}.class', 'asc'); + $this->assertEquals($expected, $result); + + $result = Set::sort($data, '{n}.test2', 'asc'); + $this->assertEquals($expected, $result); + } + +/** + * testExtract method + * + * @return void + */ + public function testExtract() { + $a = array( + array( + 'Article' => array('id' => '1', 'user_id' => '1', 'title' => 'First Article', 'body' => 'First Article Body', 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31'), + 'User' => array('id' => '1', 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'), + 'Comment' => array( + array('id' => '1', 'article_id' => '1', 'user_id' => '2', 'comment' => 'First Comment for First Article', 'published' => 'Y', 'created' => '2007-03-18 10:45:23', 'updated' => '2007-03-18 10:47:31'), + array('id' => '2', 'article_id' => '1', 'user_id' => '4', 'comment' => 'Second Comment for First Article', 'published' => 'Y', 'created' => '2007-03-18 10:47:23', 'updated' => '2007-03-18 10:49:31'), + ), + 'Tag' => array( + array('id' => '1', 'tag' => 'tag1', 'created' => '2007-03-18 12:22:23', 'updated' => '2007-03-18 12:24:31'), + array('id' => '2', 'tag' => 'tag2', 'created' => '2007-03-18 12:24:23', 'updated' => '2007-03-18 12:26:31') + ), + 'Deep' => array( + 'Nesting' => array( + 'test' => array( + 1 => 'foo', + 2 => array( + 'and' => array('more' => 'stuff') + ) + ) + ) + ) + ), + array( + 'Article' => array('id' => '3', 'user_id' => '1', 'title' => 'Third Article', 'body' => 'Third Article Body', 'published' => 'Y', 'created' => '2007-03-18 10:43:23', 'updated' => '2007-03-18 10:45:31'), + 'User' => array('id' => '2', 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'), + 'Comment' => array(), + 'Tag' => array() + ), + array( + 'Article' => array('id' => '3', 'user_id' => '1', 'title' => 'Third Article', 'body' => 'Third Article Body', 'published' => 'Y', 'created' => '2007-03-18 10:43:23', 'updated' => '2007-03-18 10:45:31'), + 'User' => array('id' => '3', 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'), + 'Comment' => array(), + 'Tag' => array() + ), + array( + 'Article' => array('id' => '3', 'user_id' => '1', 'title' => 'Third Article', 'body' => 'Third Article Body', 'published' => 'Y', 'created' => '2007-03-18 10:43:23', 'updated' => '2007-03-18 10:45:31'), + 'User' => array('id' => '4', 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'), + 'Comment' => array(), + 'Tag' => array() + ), + array( + 'Article' => array('id' => '3', 'user_id' => '1', 'title' => 'Third Article', 'body' => 'Third Article Body', 'published' => 'Y', 'created' => '2007-03-18 10:43:23', 'updated' => '2007-03-18 10:45:31'), + 'User' => array('id' => '5', 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'), + 'Comment' => array(), + 'Tag' => array() + ) + ); + $b = array('Deep' => $a[0]['Deep']); + $c = array( + array('a' => array('I' => array('a' => 1))), + array( + 'a' => array( + 2 + ) + ), + array('a' => array('II' => array('a' => 3, 'III' => array('a' => array('foo' => 4))))), + ); + + $expected = array(array('a' => $c[2]['a'])); + $r = Set::extract('/a/II[a=3]/..', $c); + $this->assertEquals($expected, $r); + + $expected = array(1, 2, 3, 4, 5); + $this->assertEquals($expected, Set::extract('/User/id', $a)); + + $expected = array(1, 2, 3, 4, 5); + $this->assertEquals($expected, Set::extract('/User/id', $a)); + + $expected = array( + array('id' => 1), array('id' => 2), array('id' => 3), array('id' => 4), array('id' => 5) + ); + + $r = Set::extract('/User/id', $a, array('flatten' => false)); + $this->assertEquals($expected, $r); + + $expected = array(array('test' => $a[0]['Deep']['Nesting']['test'])); + $this->assertEquals($expected, Set::extract('/Deep/Nesting/test', $a)); + $this->assertEquals($expected, Set::extract('/Deep/Nesting/test', $b)); + + $expected = array(array('test' => $a[0]['Deep']['Nesting']['test'])); + $r = Set::extract('/Deep/Nesting/test/1/..', $a); + $this->assertEquals($expected, $r); + + $expected = array(array('test' => $a[0]['Deep']['Nesting']['test'])); + $r = Set::extract('/Deep/Nesting/test/2/and/../..', $a); + $this->assertEquals($expected, $r); + + $expected = array(array('test' => $a[0]['Deep']['Nesting']['test'])); + $r = Set::extract('/Deep/Nesting/test/2/../../../Nesting/test/2/..', $a); + $this->assertEquals($expected, $r); + + $expected = array(2); + $r = Set::extract('/User[2]/id', $a); + $this->assertEquals($expected, $r); + + $expected = array(4, 5); + $r = Set::extract('/User[id>3]/id', $a); + $this->assertEquals($expected, $r); + + $expected = array(2, 3); + $r = Set::extract('/User[id>1][id<=3]/id', $a); + $this->assertEquals($expected, $r); + + $expected = array(array('I'), array('II')); + $r = Set::extract('/a/@*', $c); + $this->assertEquals($expected, $r); + + $single = array( + 'User' => array( + 'id' => 4, + 'name' => 'Neo', + ) + ); + $tricky = array( + 0 => array( + 'User' => array( + 'id' => 1, + 'name' => 'John', + ) + ), + 1 => array( + 'User' => array( + 'id' => 2, + 'name' => 'Bob', + ) + ), + 2 => array( + 'User' => array( + 'id' => 3, + 'name' => 'Tony', + ) + ), + 'User' => array( + 'id' => 4, + 'name' => 'Neo', + ) + ); + + $expected = array(1, 2, 3, 4); + $r = Set::extract('/User/id', $tricky); + $this->assertEquals($expected, $r); + + $expected = array(4); + $r = Set::extract('/User/id', $single); + $this->assertEquals($expected, $r); + + $expected = array(1, 3); + $r = Set::extract('/User[name=/n/]/id', $tricky); + $this->assertEquals($expected, $r); + + $expected = array(4); + $r = Set::extract('/User[name=/N/]/id', $tricky); + $this->assertEquals($expected, $r); + + $expected = array(1, 3, 4); + $r = Set::extract('/User[name=/N/i]/id', $tricky); + $this->assertEquals($expected, $r); + + $expected = array(array('id', 'name'), array('id', 'name'), array('id', 'name'), array('id', 'name')); + $r = Set::extract('/User/@*', $tricky); + $this->assertEquals($expected, $r); + + $common = array( + array( + 'Article' => array( + 'id' => 1, + 'name' => 'Article 1', + ), + 'Comment' => array( + array( + 'id' => 1, + 'user_id' => 5, + 'article_id' => 1, + 'text' => 'Comment 1', + ), + array( + 'id' => 2, + 'user_id' => 23, + 'article_id' => 1, + 'text' => 'Comment 2', + ), + array( + 'id' => 3, + 'user_id' => 17, + 'article_id' => 1, + 'text' => 'Comment 3', + ), + ), + ), + array( + 'Article' => array( + 'id' => 2, + 'name' => 'Article 2', + ), + 'Comment' => array( + array( + 'id' => 4, + 'user_id' => 2, + 'article_id' => 2, + 'text' => 'Comment 4', + 'addition' => '', + ), + array( + 'id' => 5, + 'user_id' => 23, + 'article_id' => 2, + 'text' => 'Comment 5', + 'addition' => 'foo', + ), + ), + ), + array( + 'Article' => array( + 'id' => 3, + 'name' => 'Article 3', + ), + 'Comment' => array(), + ) + ); + + $r = Set::extract('/Comment/id', $common); + $expected = array(1, 2, 3, 4, 5); + $this->assertEquals($expected, $r); + + $expected = array(1, 2, 4, 5); + $r = Set::extract('/Comment[id!=3]/id', $common); + $this->assertEquals($expected, $r); + + $r = Set::extract('/', $common); + $this->assertEquals($r, $common); + + $expected = array(1, 2, 4, 5); + $r = Set::extract($common, '/Comment[id!=3]/id'); + $this->assertEquals($expected, $r); + + $expected = array($common[0]['Comment'][2]); + $r = Set::extract($common, '/Comment/2'); + $this->assertEquals($expected, $r); + + $expected = array($common[0]['Comment'][0]); + $r = Set::extract($common, '/Comment[1]/.[id=1]'); + $this->assertEquals($expected, $r); + + $expected = array($common[1]['Comment'][1]); + $r = Set::extract($common, '/1/Comment/.[2]'); + $this->assertEquals($expected, $r); + + $expected = array(); + $r = Set::extract('/User/id', array()); + $this->assertEquals($expected, $r); + + $expected = array(5); + $r = Set::extract('/Comment/id[:last]', $common); + $this->assertEquals($expected, $r); + + $expected = array(1); + $r = Set::extract('/Comment/id[:first]', $common); + $this->assertEquals($expected, $r); + + $expected = array(3); + $r = Set::extract('/Article[:last]/id', $common); + $this->assertEquals($expected, $r); + + $expected = array(array('Comment' => $common[1]['Comment'][0])); + $r = Set::extract('/Comment[addition=]', $common); + $this->assertEquals($expected, $r); + + $habtm = array( + array( + 'Post' => array( + 'id' => 1, + 'title' => 'great post', + ), + 'Comment' => array( + array( + 'id' => 1, + 'text' => 'foo', + 'User' => array( + 'id' => 1, + 'name' => 'bob' + ), + ), + array( + 'id' => 2, + 'text' => 'bar', + 'User' => array( + 'id' => 2, + 'name' => 'tod' + ), + ), + ), + ), + array( + 'Post' => array( + 'id' => 2, + 'title' => 'fun post', + ), + 'Comment' => array( + array( + 'id' => 3, + 'text' => '123', + 'User' => array( + 'id' => 3, + 'name' => 'dan' + ), + ), + array( + 'id' => 4, + 'text' => '987', + 'User' => array( + 'id' => 4, + 'name' => 'jim' + ), + ), + ), + ), + ); + + $r = Set::extract('/Comment/User[name=/bob|dan/]/..', $habtm); + $this->assertEquals('bob', $r[0]['Comment']['User']['name']); + $this->assertEquals('dan', $r[1]['Comment']['User']['name']); + $this->assertEquals(2, count($r)); + + $r = Set::extract('/Comment/User[name=/bob|tod/]/..', $habtm); + $this->assertEquals('bob', $r[0]['Comment']['User']['name']); + + $this->assertEquals('tod', $r[1]['Comment']['User']['name']); + $this->assertEquals(2, count($r)); + + $tree = array( + array( + 'Category' => array('name' => 'Category 1'), + 'children' => array(array('Category' => array('name' => 'Category 1.1'))) + ), + array( + 'Category' => array('name' => 'Category 2'), + 'children' => array( + array('Category' => array('name' => 'Category 2.1')), + array('Category' => array('name' => 'Category 2.2')) + ) + ), + array( + 'Category' => array('name' => 'Category 3'), + 'children' => array(array('Category' => array('name' => 'Category 3.1'))) + ) + ); + + $expected = array(array('Category' => $tree[1]['Category'])); + $r = Set::extract('/Category[name=Category 2]', $tree); + $this->assertEquals($expected, $r); + + $expected = array( + array('Category' => $tree[1]['Category'], 'children' => $tree[1]['children']) + ); + $r = Set::extract('/Category[name=Category 2]/..', $tree); + $this->assertEquals($expected, $r); + + $expected = array( + array('children' => $tree[1]['children'][0]), + array('children' => $tree[1]['children'][1]) + ); + $r = Set::extract('/Category[name=Category 2]/../children', $tree); + $this->assertEquals($expected, $r); + + $habtm = array( + array( + 'Post' => array( + 'id' => 1, + 'title' => 'great post', + ), + 'Comment' => array( + array( + 'id' => 1, + 'text' => 'foo', + 'User' => array( + 'id' => 1, + 'name' => 'bob' + ), + ), + array( + 'id' => 2, + 'text' => 'bar', + 'User' => array( + 'id' => 2, + 'name' => 'tod' + ), + ), + ), + ), + array( + 'Post' => array( + 'id' => 2, + 'title' => 'fun post', + ), + 'Comment' => array( + array( + 'id' => 3, + 'text' => '123', + 'User' => array( + 'id' => 3, + 'name' => 'dan' + ), + ), + array( + 'id' => 4, + 'text' => '987', + 'User' => array( + 'id' => 4, + 'name' => 'jim' + ), + ), + ), + ), + ); + + $r = Set::extract('/Comment/User[name=/\w+/]/..', $habtm); + $this->assertEquals('bob', $r[0]['Comment']['User']['name']); + $this->assertEquals('tod', $r[1]['Comment']['User']['name']); + $this->assertEquals('dan', $r[2]['Comment']['User']['name']); + $this->assertEquals('dan', $r[3]['Comment']['User']['name']); + $this->assertEquals(4, count($r)); + + $r = Set::extract('/Comment/User[name=/[a-z]+/]/..', $habtm); + $this->assertEquals('bob', $r[0]['Comment']['User']['name']); + $this->assertEquals('tod', $r[1]['Comment']['User']['name']); + $this->assertEquals('dan', $r[2]['Comment']['User']['name']); + $this->assertEquals('dan', $r[3]['Comment']['User']['name']); + $this->assertEquals(4, count($r)); + + $r = Set::extract('/Comment/User[name=/bob|dan/]/..', $habtm); + $this->assertEquals('bob', $r[0]['Comment']['User']['name']); + $this->assertEquals('dan', $r[1]['Comment']['User']['name']); + $this->assertEquals(2, count($r)); + + $r = Set::extract('/Comment/User[name=/bob|tod/]/..', $habtm); + $this->assertEquals('bob', $r[0]['Comment']['User']['name']); + $this->assertEquals('tod', $r[1]['Comment']['User']['name']); + $this->assertEquals(2, count($r)); + + $mixedKeys = array( + 'User' => array( + 0 => array( + 'id' => 4, + 'name' => 'Neo' + ), + 1 => array( + 'id' => 5, + 'name' => 'Morpheus' + ), + 'stringKey' => array() + ) + ); + $expected = array('Neo', 'Morpheus'); + $r = Set::extract('/User/name', $mixedKeys); + $this->assertEquals($expected, $r); + + $f = array( + array( + 'file' => array( + 'name' => 'zipfile.zip', + 'type' => 'application/zip', + 'tmp_name' => '/tmp/php178.tmp', + 'error' => 0, + 'size' => '564647' + ) + ), + array( + 'file' => array( + 'name' => 'zipfile2.zip', + 'type' => 'application/x-zip-compressed', + 'tmp_name' => '/tmp/php179.tmp', + 'error' => 0, + 'size' => '354784' + ) + ), + array( + 'file' => array( + 'name' => 'picture.jpg', + 'type' => 'image/jpeg', + 'tmp_name' => '/tmp/php180.tmp', + 'error' => 0, + 'size' => '21324' + ) + ) + ); + $expected = array(array('name' => 'zipfile2.zip','type' => 'application/x-zip-compressed','tmp_name' => '/tmp/php179.tmp','error' => 0,'size' => '354784')); + $r = Set::extract('/file/.[type=application/x-zip-compressed]', $f); + $this->assertEquals($expected, $r); + + $expected = array(array('name' => 'zipfile.zip','type' => 'application/zip','tmp_name' => '/tmp/php178.tmp','error' => 0,'size' => '564647')); + $r = Set::extract('/file/.[type=application/zip]', $f); + $this->assertEquals($expected, $r); + + $f = array( + array( + 'file' => array( + 'name' => 'zipfile.zip', + 'type' => 'application/zip', + 'tmp_name' => '/tmp/php178.tmp', + 'error' => 0, + 'size' => '564647' + ) + ), + array( + 'file' => array( + 'name' => 'zipfile2.zip', + 'type' => 'application/x zip compressed', + 'tmp_name' => '/tmp/php179.tmp', + 'error' => 0, + 'size' => '354784' + ) + ), + array( + 'file' => array( + 'name' => 'picture.jpg', + 'type' => 'image/jpeg', + 'tmp_name' => '/tmp/php180.tmp', + 'error' => 0, + 'size' => '21324' + ) + ) + ); + $expected = array(array('name' => 'zipfile2.zip','type' => 'application/x zip compressed','tmp_name' => '/tmp/php179.tmp','error' => 0,'size' => '354784')); + $r = Set::extract('/file/.[type=application/x zip compressed]', $f); + $this->assertEquals($expected, $r); + + $expected = array( + array('name' => 'zipfile.zip','type' => 'application/zip','tmp_name' => '/tmp/php178.tmp','error' => 0,'size' => '564647'), + array('name' => 'zipfile2.zip','type' => 'application/x zip compressed','tmp_name' => '/tmp/php179.tmp','error' => 0,'size' => '354784') + ); + $r = Set::extract('/file/.[tmp_name=/tmp\/php17/]', $f); + $this->assertEquals($expected, $r); + + $hasMany = array( + 'Node' => array( + 'id' => 1, + 'name' => 'First', + 'state' => 50 + ), + 'ParentNode' => array( + 0 => array( + 'id' => 2, + 'name' => 'Second', + 'state' => 60, + ) + ) + ); + $result = Set::extract('/ParentNode/name', $hasMany); + $expected = array('Second'); + $this->assertEquals($expected, $result); + + $data = array( + array( + 'Category' => array( + 'id' => 1, + 'name' => 'First' + ), + 0 => array( + 'value' => 50 + ) + ), + array( + 'Category' => array( + 'id' => 2, + 'name' => 'Second' + ), + 0 => array( + 'value' => 60 + ) + ) + ); + $expected = array( + array( + 'Category' => array( + 'id' => 1, + 'name' => 'First' + ), + 0 => array( + 'value' => 50 + ) + ) + ); + $result = Set::extract('/Category[id=1]/..', $data); + $this->assertEquals($expected, $result); + + $data = array( + array( + 'ChildNode' => array('id' => 1), + array('name' => 'Item 1') + ), + array( + 'ChildNode' => array('id' => 2), + array('name' => 'Item 2') + ), + ); + + $expected = array( + 'Item 1', + 'Item 2' + ); + $result = Set::extract('/0/name', $data); + $this->assertEquals($expected, $result); + + $data = array( + array('A1', 'B1'), + array('A2', 'B2') + ); + $expected = array('A1', 'A2'); + $result = Set::extract('/0', $data); + $this->assertEquals($expected, $result); + } + +/** + * test parent selectors with extract + * + * @return void + */ + public function testExtractParentSelector() { + $tree = array( + array( + 'Category' => array( + 'name' => 'Category 1' + ), + 'children' => array( + array( + 'Category' => array( + 'name' => 'Category 1.1' + ) + ) + ) + ), + array( + 'Category' => array( + 'name' => 'Category 2' + ), + 'children' => array( + array( + 'Category' => array( + 'name' => 'Category 2.1' + ) + ), + array( + 'Category' => array( + 'name' => 'Category 2.2' + ) + ), + ) + ), + array( + 'Category' => array( + 'name' => 'Category 3' + ), + 'children' => array( + array( + 'Category' => array( + 'name' => 'Category 3.1' + ) + ) + ) + ) + ); + $expected = array(array('Category' => $tree[1]['Category'])); + $r = Set::extract('/Category[name=Category 2]', $tree); + $this->assertEquals($expected, $r); + + $expected = array(array('Category' => $tree[1]['Category'], 'children' => $tree[1]['children'])); + $r = Set::extract('/Category[name=Category 2]/..', $tree); + $this->assertEquals($expected, $r); + + $expected = array(array('children' => $tree[1]['children'][0]), array('children' => $tree[1]['children'][1])); + $r = Set::extract('/Category[name=Category 2]/../children', $tree); + $this->assertEquals($expected, $r); + + $single = array( + array( + 'CallType' => array( + 'name' => 'Internal Voice' + ), + 'x' => array( + 'hour' => 7 + ) + ) + ); + + $expected = array(7); + $r = Set::extract('/CallType[name=Internal Voice]/../x/hour', $single); + $this->assertEquals($expected, $r); + + $multiple = array( + array( + 'CallType' => array( + 'name' => 'Internal Voice' + ), + 'x' => array( + 'hour' => 7 + ) + ), + array( + 'CallType' => array( + 'name' => 'Internal Voice' + ), + 'x' => array( + 'hour' => 2 + ) + ), + array( + 'CallType' => array( + 'name' => 'Internal Voice' + ), + 'x' => array( + 'hour' => 1 + ) + ) + ); + + $expected = array(7,2,1); + $r = Set::extract('/CallType[name=Internal Voice]/../x/hour', $multiple); + $this->assertEquals($expected, $r); + + $a = array( + 'Model' => array( + '0' => array( + 'id' => 18, + 'SubModelsModel' => array( + 'id' => 1, + 'submodel_id' => 66, + 'model_id' => 18, + 'type' => 1 + ), + ), + '1' => array( + 'id' => 0, + 'SubModelsModel' => array( + 'id' => 2, + 'submodel_id' => 66, + 'model_id' => 0, + 'type' => 1 + ), + ), + '2' => array( + 'id' => 17, + 'SubModelsModel' => array( + 'id' => 3, + 'submodel_id' => 66, + 'model_id' => 17, + 'type' => 2 + ), + ), + '3' => array( + 'id' => 0, + 'SubModelsModel' => array( + 'id' => 4, + 'submodel_id' => 66, + 'model_id' => 0, + 'type' => 2 + ) + ) + ) + ); + + $expected = array( + array( + 'Model' => array( + 'id' => 17, + 'SubModelsModel' => array( + 'id' => 3, + 'submodel_id' => 66, + 'model_id' => 17, + 'type' => 2 + ), + ) + ), + array( + 'Model' => array( + 'id' => 0, + 'SubModelsModel' => array( + 'id' => 4, + 'submodel_id' => 66, + 'model_id' => 0, + 'type' => 2 + ) + ) + ) + ); + $r = Set::extract('/Model/SubModelsModel[type=2]/..', $a); + $this->assertEquals($expected, $r); + } + +/** + * test that extract() still works when arrays don't contain a 0 index. + * + * @return void + */ + public function testExtractWithNonZeroArrays() { + $nonZero = array( + 1 => array( + 'User' => array( + 'id' => 1, + 'name' => 'John', + ) + ), + 2 => array( + 'User' => array( + 'id' => 2, + 'name' => 'Bob', + ) + ), + 3 => array( + 'User' => array( + 'id' => 3, + 'name' => 'Tony', + ) + ) + ); + $expected = array(1, 2, 3); + $r = Set::extract('/User/id', $nonZero); + $this->assertEquals($expected, $r); + + $expected = array( + array('User' => array('id' => 1, 'name' => 'John')), + array('User' => array('id' => 2, 'name' => 'Bob')), + array('User' => array('id' => 3, 'name' => 'Tony')), + ); + $result = Set::extract('/User', $nonZero); + $this->assertEquals($expected, $result); + + $nonSequential = array( + 'User' => array( + 0 => array('id' => 1), + 2 => array('id' => 2), + 6 => array('id' => 3), + 9 => array('id' => 4), + 3 => array('id' => 5), + ), + ); + + $nonZero = array( + 'User' => array( + 2 => array('id' => 1), + 4 => array('id' => 2), + 6 => array('id' => 3), + 9 => array('id' => 4), + 3 => array('id' => 5), + ), + ); + + $expected = array(1, 2, 3, 4, 5); + $this->assertEquals($expected, Set::extract('/User/id', $nonSequential)); + + $result = Set::extract('/User/id', $nonZero); + $this->assertEquals($expected, $result, 'Failed non zero array key extract'); + + $expected = array(1, 2, 3, 4, 5); + $this->assertEquals($expected, Set::extract('/User/id', $nonSequential)); + + $result = Set::extract('/User/id', $nonZero); + $this->assertEquals($expected, $result, 'Failed non zero array key extract'); + + $startingAtOne = array( + 'Article' => array( + 1 => array( + 'id' => 1, + 'approved' => 1, + ), + ) + ); + + $expected = array(0 => array('Article' => array('id' => 1, 'approved' => 1))); + $result = Set::extract('/Article[approved=1]', $startingAtOne); + $this->assertEquals($expected, $result); + + $items = array( + 240 => array( + 'A' => array( + 'field1' => 'a240', + 'field2' => 'a240', + ), + 'B' => array( + 'field1' => 'b240', + 'field2' => 'b240' + ), + ) + ); + + $expected = array( + 0 => 'b240' + ); + + $result = Set::extract('/B/field1', $items); + $this->assertSame($expected, $result); + $this->assertSame($result, Set::extract('{n}.B.field1', $items)); + } + +/** + * testExtractWithArrays method + * + * @return void + */ + public function testExtractWithArrays() { + $data = array( + 'Level1' => array( + 'Level2' => array('test1', 'test2'), + 'Level2bis' => array('test3', 'test4') + ) + ); + $this->assertEquals(array(array('Level2' => array('test1', 'test2'))), Set::extract('/Level1/Level2', $data)); + $this->assertEquals(array(array('Level2bis' => array('test3', 'test4'))), Set::extract('/Level1/Level2bis', $data)); + } + +/** + * test extract() with elements that have non-array children. + * + * @return void + */ + public function testExtractWithNonArrayElements() { + $data = array( + 'node' => array( + array('foo'), + 'bar' + ) + ); + $result = Set::extract('/node', $data); + $expected = array( + array('node' => array('foo')), + 'bar' + ); + $this->assertEquals($expected, $result); + + $data = array( + 'node' => array( + 'foo' => array('bar'), + 'bar' => array('foo') + ) + ); + $result = Set::extract('/node', $data); + $expected = array( + array('foo' => array('bar')), + array('bar' => array('foo')), + ); + $this->assertEquals($expected, $result); + + $data = array( + 'node' => array( + 'foo' => array( + 'bar' + ), + 'bar' => 'foo' + ) + ); + $result = Set::extract('/node', $data); + $expected = array( + array('foo' => array('bar')), + 'foo' + ); + $this->assertEquals($expected, $result); + } + +/** + * Test that extract() + matching can hit null things. + */ + public function testExtractMatchesNull() { + $data = array( + 'Country' => array( + array('name' => 'Canada'), + array('name' => 'Australia'), + array('name' => null), + ) + ); + $result = Set::extract('/Country[name=/Canada|^$/]', $data); + $expected = array( + array( + 'Country' => array( + 'name' => 'Canada', + ), + ), + array( + 'Country' => array( + 'name' => null, + ), + ), + ); + $this->assertEquals($expected, $result); + } + +/** + * testMatches method + * + * @return void + */ + public function testMatches() { + $a = array( + array('Article' => array('id' => 1, 'title' => 'Article 1')), + array('Article' => array('id' => 2, 'title' => 'Article 2')), + array('Article' => array('id' => 3, 'title' => 'Article 3')) + ); + + $this->assertTrue(Set::matches(array('id=2'), $a[1]['Article'])); + $this->assertFalse(Set::matches(array('id>2'), $a[1]['Article'])); + $this->assertTrue(Set::matches(array('id>=2'), $a[1]['Article'])); + $this->assertFalse(Set::matches(array('id>=3'), $a[1]['Article'])); + $this->assertTrue(Set::matches(array('id<=2'), $a[1]['Article'])); + $this->assertFalse(Set::matches(array('id<2'), $a[1]['Article'])); + $this->assertTrue(Set::matches(array('id>1'), $a[1]['Article'])); + $this->assertTrue(Set::matches(array('id>1', 'id<3', 'id!=0'), $a[1]['Article'])); + + $this->assertTrue(Set::matches(array('3'), null, 3)); + $this->assertTrue(Set::matches(array('5'), null, 5)); + + $this->assertTrue(Set::matches(array('id'), $a[1]['Article'])); + $this->assertTrue(Set::matches(array('id', 'title'), $a[1]['Article'])); + $this->assertFalse(Set::matches(array('non-existant'), $a[1]['Article'])); + + $this->assertTrue(Set::matches('/Article[id=2]', $a)); + $this->assertFalse(Set::matches('/Article[id=4]', $a)); + $this->assertTrue(Set::matches(array(), $a)); + + $r = array( + 'Attachment' => array( + 'keep' => array() + ), + 'Comment' => array( + 'keep' => array( + 'Attachment' => array( + 'fields' => array( + 0 => 'attachment', + ), + ), + ) + ), + 'User' => array( + 'keep' => array() + ), + 'Article' => array( + 'keep' => array( + 'Comment' => array( + 'fields' => array( + 0 => 'comment', + 1 => 'published', + ), + ), + 'User' => array( + 'fields' => array( + 0 => 'user', + ), + ), + ) + ) + ); + + $this->assertTrue(Set::matches('/Article/keep/Comment', $r)); + $this->assertEquals(array('comment', 'published'), Set::extract('/Article/keep/Comment/fields', $r)); + $this->assertEquals(array('user'), Set::extract('/Article/keep/User/fields', $r)); + } + +/** + * testSetExtractReturnsEmptyArray method + * + * @return void + */ + public function testSetExtractReturnsEmptyArray() { + $this->assertEquals(Set::extract(array(), '/Post/id'), array()); + + $this->assertEquals(Set::extract('/Post/id', array()), array()); + + $this->assertEquals(Set::extract('/Post/id', array( + array('Post' => array('name' => 'bob')), + array('Post' => array('name' => 'jim')) + )), array()); + + $this->assertEquals(Set::extract(array(), 'Message.flash'), null); + } + +/** + * testClassicExtract method + * + * @return void + */ + public function testClassicExtract() { + $a = array( + array('Article' => array('id' => 1, 'title' => 'Article 1')), + array('Article' => array('id' => 2, 'title' => 'Article 2')), + array('Article' => array('id' => 3, 'title' => 'Article 3')) + ); + + $result = Set::extract($a, '{n}.Article.id'); + $expected = array(1, 2, 3); + $this->assertEquals($expected, $result); + + $result = Set::extract($a, '{n}.Article.title'); + $expected = array('Article 1', 'Article 2', 'Article 3'); + $this->assertEquals($expected, $result); + + $result = Set::extract($a, '1.Article.title'); + $expected = 'Article 2'; + $this->assertEquals($expected, $result); + + $result = Set::extract($a, '3.Article.title'); + $expected = null; + $this->assertEquals($expected, $result); + + $a = array( + array( + 'Article' => array('id' => 1, 'title' => 'Article 1', + 'User' => array('id' => 1, 'username' => 'mariano.iglesias')) + ), + array( + 'Article' => array('id' => 2, 'title' => 'Article 2', + 'User' => array('id' => 1, 'username' => 'mariano.iglesias')) + ), + array( + 'Article' => array('id' => 3, 'title' => 'Article 3', + 'User' => array('id' => 2, 'username' => 'phpnut')) + ) + ); + + $result = Set::extract($a, '{n}.Article.User.username'); + $expected = array('mariano.iglesias', 'mariano.iglesias', 'phpnut'); + $this->assertEquals($expected, $result); + + $a = array( + array( + 'Article' => array( + 'id' => 1, 'title' => 'Article 1', + 'Comment' => array( + array('id' => 10, 'title' => 'Comment 10'), + array('id' => 11, 'title' => 'Comment 11'), + array('id' => 12, 'title' => 'Comment 12') + ) + ) + ), + array( + 'Article' => array( + 'id' => 2, 'title' => 'Article 2', + 'Comment' => array( + array('id' => 13, 'title' => 'Comment 13'), + array('id' => 14, 'title' => 'Comment 14') + ) + ) + ), + array('Article' => array('id' => 3, 'title' => 'Article 3')) + ); + + $result = Set::extract($a, '{n}.Article.Comment.{n}.id'); + $expected = array(array(10, 11, 12), array(13, 14), null); + $this->assertEquals($expected, $result); + + $result = Set::extract($a, '{n}.Article.Comment.{n}.title'); + $expected = array( + array('Comment 10', 'Comment 11', 'Comment 12'), + array('Comment 13', 'Comment 14'), + null + ); + $this->assertEquals($expected, $result); + + $a = array(array('1day' => '20 sales'), array('1day' => '2 sales')); + $result = Set::extract($a, '{n}.1day'); + $expected = array('20 sales', '2 sales'); + $this->assertEquals($expected, $result); + + $a = array( + 'pages' => array('name' => 'page'), + 'fruites' => array('name' => 'fruit'), + 0 => array('name' => 'zero') + ); + $result = Set::extract($a, '{s}.name'); + $expected = array('page','fruit'); + $this->assertEquals($expected, $result); + + $a = array( + 0 => array('pages' => array('name' => 'page')), + 1 => array('fruites' => array('name' => 'fruit')), + 'test' => array(array('name' => 'jippi')), + 'dot.test' => array(array('name' => 'jippi')) + ); + + $result = Set::extract($a, '{n}.{s}.name'); + $expected = array(0 => array('page'), 1 => array('fruit')); + $this->assertEquals($expected, $result); + + $result = Set::extract($a, '{s}.{n}.name'); + $expected = array(array('jippi'), array('jippi')); + $this->assertEquals($expected, $result); + + $result = Set::extract($a, '{\w+}.{\w+}.name'); + $expected = array( + array('pages' => 'page'), + array('fruites' => 'fruit'), + 'test' => array('jippi'), + 'dot.test' => array('jippi') + ); + $this->assertEquals($expected, $result); + + $result = Set::extract($a, '{\d+}.{\w+}.name'); + $expected = array(array('pages' => 'page'), array('fruites' => 'fruit')); + $this->assertEquals($expected, $result); + + $result = Set::extract($a, '{n}.{\w+}.name'); + $expected = array(array('pages' => 'page'), array('fruites' => 'fruit')); + $this->assertEquals($expected, $result); + + $result = Set::extract($a, '{s}.{\d+}.name'); + $expected = array(array('jippi'), array('jippi')); + $this->assertEquals($expected, $result); + + $result = Set::extract($a, '{s}'); + $expected = array(array(array('name' => 'jippi')), array(array('name' => 'jippi'))); + $this->assertEquals($expected, $result); + + $result = Set::extract($a, '{[a-z]}'); + $expected = array( + 'test' => array(array('name' => 'jippi')), + 'dot.test' => array(array('name' => 'jippi')) + ); + $this->assertEquals($expected, $result); + + $result = Set::extract($a, '{dot\.test}.{n}'); + $expected = array('dot.test' => array(array('name' => 'jippi'))); + $this->assertEquals($expected, $result); + + $a = new stdClass(); + $a->articles = array( + array('Article' => array('id' => 1, 'title' => 'Article 1')), + array('Article' => array('id' => 2, 'title' => 'Article 2')), + array('Article' => array('id' => 3, 'title' => 'Article 3')) + ); + + $result = Set::extract($a, 'articles.{n}.Article.id'); + $expected = array(1, 2, 3); + $this->assertEquals($expected, $result); + + $result = Set::extract($a, 'articles.{n}.Article.title'); + $expected = array('Article 1', 'Article 2', 'Article 3'); + $this->assertEquals($expected, $result); + + $a = new ArrayObject(); + $a['articles'] = array( + array('Article' => array('id' => 1, 'title' => 'Article 1')), + array('Article' => array('id' => 2, 'title' => 'Article 2')), + array('Article' => array('id' => 3, 'title' => 'Article 3')) + ); + + $result = Set::extract($a, 'articles.{n}.Article.id'); + $expected = array(1, 2, 3); + $this->assertEquals($expected, $result); + + $result = Set::extract($a, 'articles.{n}.Article.title'); + $expected = array('Article 1', 'Article 2', 'Article 3'); + $this->assertEquals($expected, $result); + + $result = Set::extract($a, 'articles.0.Article.title'); + $expected = 'Article 1'; + $this->assertEquals($expected, $result); + } + +/** + * test classicExtract with keys that exceed 32bit max int. + * + * @return void + */ + public function testClassicExtractMaxInt() { + $data = array( + 'Data' => array( + '13376924712' => 'abc' + ) + ); + $this->assertEquals('abc', Set::classicExtract($data, 'Data.13376924712')); + } + +/** + * testInsert method + * + * @see Hash tests, as Set::insert() is just a proxy. + * @return void + */ + public function testInsert() { + $a = array( + 'pages' => array('name' => 'page') + ); + + $result = Set::insert($a, 'files', array('name' => 'files')); + $expected = array( + 'pages' => array('name' => 'page'), + 'files' => array('name' => 'files') + ); + $this->assertEquals($expected, $result); + } + +/** + * testRemove method + * + * @return void + */ + public function testRemove() { + $a = array( + 'pages' => array('name' => 'page'), + 'files' => array('name' => 'files') + ); + + $result = Set::remove($a, 'files'); + $expected = array( + 'pages' => array('name' => 'page') + ); + $this->assertEquals($expected, $result); + } + +/** + * testCheck method + * + * @return void + */ + public function testCheck() { + $set = array( + 'My Index 1' => array('First' => 'The first item') + ); + $this->assertTrue(Set::check($set, 'My Index 1.First')); + $this->assertTrue(Set::check($set, 'My Index 1')); + $this->assertEquals(Set::check($set, array()), $set); + + $set = array( + 'My Index 1' => array('First' => array('Second' => array('Third' => array('Fourth' => 'Heavy. Nesting.')))) + ); + $this->assertTrue(Set::check($set, 'My Index 1.First.Second')); + $this->assertTrue(Set::check($set, 'My Index 1.First.Second.Third')); + $this->assertTrue(Set::check($set, 'My Index 1.First.Second.Third.Fourth')); + $this->assertFalse(Set::check($set, 'My Index 1.First.Seconds.Third.Fourth')); + } + +/** + * testWritingWithFunkyKeys method + * + * @return void + */ + public function testWritingWithFunkyKeys() { + $set = Set::insert(array(), 'Session Test', "test"); + $this->assertEquals('test', Set::extract($set, 'Session Test')); + + $set = Set::remove($set, 'Session Test'); + $this->assertFalse(Set::check($set, 'Session Test')); + + $expected = array('Session Test' => array('Test Case' => 'test')); + $this->assertEquals(Set::insert(array(), 'Session Test.Test Case', "test"), $expected); + $this->assertTrue(Set::check($expected, 'Session Test.Test Case')); + } + +/** + * testDiff method + * + * @return void + */ + public function testDiff() { + $a = array( + 0 => array('name' => 'main'), + 1 => array('name' => 'about') + ); + $b = array( + 0 => array('name' => 'main'), + 1 => array('name' => 'about'), + 2 => array('name' => 'contact') + ); + + $result = Set::diff($a, $b); + $expected = array( + 2 => array('name' => 'contact') + ); + $this->assertEquals($expected, $result); + + $result = Set::diff($a, array()); + $expected = $a; + $this->assertEquals($expected, $result); + + $result = Set::diff(array(), $b); + $expected = $b; + $this->assertEquals($expected, $result); + + $b = array( + 0 => array('name' => 'me'), + 1 => array('name' => 'about') + ); + + $result = Set::diff($a, $b); + $expected = array( + 0 => array('name' => 'main') + ); + $this->assertEquals($expected, $result); + + $a = array(); + $b = array('name' => 'bob', 'address' => 'home'); + $result = Set::diff($a, $b); + $this->assertEquals($b, $result); + + $a = array('name' => 'bob', 'address' => 'home'); + $b = array(); + $result = Set::diff($a, $b); + $this->assertEquals($a, $result); + + $a = array('key' => true, 'another' => false, 'name' => 'me'); + $b = array('key' => 1, 'another' => 0); + $expected = array('name' => 'me'); + $result = Set::diff($a, $b); + $this->assertEquals($expected, $result); + + $a = array('key' => 'value', 'another' => null, 'name' => 'me'); + $b = array('key' => 'differentValue', 'another' => null); + $expected = array('key' => 'value', 'name' => 'me'); + $result = Set::diff($a, $b); + $this->assertEquals($expected, $result); + + $a = array('key' => 'value', 'another' => null, 'name' => 'me'); + $b = array('key' => 'differentValue', 'another' => 'value'); + $expected = array('key' => 'value', 'another' => null, 'name' => 'me'); + $result = Set::diff($a, $b); + $this->assertEquals($expected, $result); + + $a = array('key' => 'value', 'another' => null, 'name' => 'me'); + $b = array('key' => 'differentValue', 'another' => 'value'); + $expected = array('key' => 'differentValue', 'another' => 'value', 'name' => 'me'); + $result = Set::diff($b, $a); + $this->assertEquals($expected, $result); + + $a = array('key' => 'value', 'another' => null, 'name' => 'me'); + $b = array(0 => 'differentValue', 1 => 'value'); + $expected = $a + $b; + $result = Set::diff($a, $b); + $this->assertEquals($expected, $result); + } + +/** + * testContains method + * + * @return void + */ + public function testContains() { + $a = array( + 0 => array('name' => 'main'), + 1 => array('name' => 'about') + ); + $b = array( + 0 => array('name' => 'main'), + 1 => array('name' => 'about'), + 2 => array('name' => 'contact'), + 'a' => 'b' + ); + + $this->assertTrue(Set::contains($a, $a)); + $this->assertFalse(Set::contains($a, $b)); + $this->assertTrue(Set::contains($b, $a)); + } + +/** + * testCombine method + * + * @return void + */ + public function testCombine() { + $result = Set::combine(array(), '{n}.User.id', '{n}.User.Data'); + $this->assertTrue(empty($result)); + $result = Set::combine('', '{n}.User.id', '{n}.User.Data'); + $this->assertTrue(empty($result)); + + $a = array( + array('User' => array('id' => 2, 'group_id' => 1, + 'Data' => array('user' => 'mariano.iglesias','name' => 'Mariano Iglesias'))), + array('User' => array('id' => 14, 'group_id' => 2, + 'Data' => array('user' => 'phpnut', 'name' => 'Larry E. Masters'))), + array('User' => array('id' => 25, 'group_id' => 1, + 'Data' => array('user' => 'gwoo','name' => 'The Gwoo')))); + $result = Set::combine($a, '{n}.User.id'); + $expected = array(2 => null, 14 => null, 25 => null); + $this->assertEquals($expected, $result); + + $result = Set::combine($a, '{n}.User.id', '{n}.User.non-existant'); + $expected = array(2 => null, 14 => null, 25 => null); + $this->assertEquals($expected, $result); + + $result = Set::combine($a, '{n}.User.id', '{n}.User.Data'); + $expected = array( + 2 => array('user' => 'mariano.iglesias', 'name' => 'Mariano Iglesias'), + 14 => array('user' => 'phpnut', 'name' => 'Larry E. Masters'), + 25 => array('user' => 'gwoo', 'name' => 'The Gwoo')); + $this->assertEquals($expected, $result); + + $result = Set::combine($a, '{n}.User.id', '{n}.User.Data.name'); + $expected = array( + 2 => 'Mariano Iglesias', + 14 => 'Larry E. Masters', + 25 => 'The Gwoo'); + $this->assertEquals($expected, $result); + + $result = Set::combine($a, '{n}.User.id', '{n}.User.Data', '{n}.User.group_id'); + $expected = array( + 1 => array( + 2 => array('user' => 'mariano.iglesias', 'name' => 'Mariano Iglesias'), + 25 => array('user' => 'gwoo', 'name' => 'The Gwoo')), + 2 => array( + 14 => array('user' => 'phpnut', 'name' => 'Larry E. Masters'))); + $this->assertEquals($expected, $result); + + $result = Set::combine($a, '{n}.User.id', '{n}.User.Data.name', '{n}.User.group_id'); + $expected = array( + 1 => array( + 2 => 'Mariano Iglesias', + 25 => 'The Gwoo'), + 2 => array( + 14 => 'Larry E. Masters')); + $this->assertEquals($expected, $result); + + $result = Set::combine($a, '{n}.User.id'); + $expected = array(2 => null, 14 => null, 25 => null); + $this->assertEquals($expected, $result); + + $result = Set::combine($a, '{n}.User.id', '{n}.User.Data'); + $expected = array( + 2 => array('user' => 'mariano.iglesias', 'name' => 'Mariano Iglesias'), + 14 => array('user' => 'phpnut', 'name' => 'Larry E. Masters'), + 25 => array('user' => 'gwoo', 'name' => 'The Gwoo')); + $this->assertEquals($expected, $result); + + $result = Set::combine($a, '{n}.User.id', '{n}.User.Data.name'); + $expected = array(2 => 'Mariano Iglesias', 14 => 'Larry E. Masters', 25 => 'The Gwoo'); + $this->assertEquals($expected, $result); + + $result = Set::combine($a, '{n}.User.id', '{n}.User.Data', '{n}.User.group_id'); + $expected = array( + 1 => array( + 2 => array('user' => 'mariano.iglesias', 'name' => 'Mariano Iglesias'), + 25 => array('user' => 'gwoo', 'name' => 'The Gwoo')), + 2 => array( + 14 => array('user' => 'phpnut', 'name' => 'Larry E. Masters'))); + $this->assertEquals($expected, $result); + + $result = Set::combine($a, '{n}.User.id', '{n}.User.Data.name', '{n}.User.group_id'); + $expected = array( + 1 => array( + 2 => 'Mariano Iglesias', + 25 => 'The Gwoo'), + 2 => array( + 14 => 'Larry E. Masters')); + $this->assertEquals($expected, $result); + + $result = Set::combine($a, '{n}.User.id', array('{0}: {1}', '{n}.User.Data.user', '{n}.User.Data.name'), '{n}.User.group_id'); + $expected = array( + 1 => array( + 2 => 'mariano.iglesias: Mariano Iglesias', + 25 => 'gwoo: The Gwoo'), + 2 => array(14 => 'phpnut: Larry E. Masters')); + $this->assertEquals($expected, $result); + + $result = Set::combine($a, array('{0}: {1}', '{n}.User.Data.user', '{n}.User.Data.name'), '{n}.User.id'); + $expected = array('mariano.iglesias: Mariano Iglesias' => 2, 'phpnut: Larry E. Masters' => 14, 'gwoo: The Gwoo' => 25); + $this->assertEquals($expected, $result); + + $result = Set::combine($a, array('{1}: {0}', '{n}.User.Data.user', '{n}.User.Data.name'), '{n}.User.id'); + $expected = array('Mariano Iglesias: mariano.iglesias' => 2, 'Larry E. Masters: phpnut' => 14, 'The Gwoo: gwoo' => 25); + $this->assertEquals($expected, $result); + + $result = Set::combine($a, array('%1$s: %2$d', '{n}.User.Data.user', '{n}.User.id'), '{n}.User.Data.name'); + $expected = array('mariano.iglesias: 2' => 'Mariano Iglesias', 'phpnut: 14' => 'Larry E. Masters', 'gwoo: 25' => 'The Gwoo'); + $this->assertEquals($expected, $result); + + $result = Set::combine($a, array('%2$d: %1$s', '{n}.User.Data.user', '{n}.User.id'), '{n}.User.Data.name'); + $expected = array('2: mariano.iglesias' => 'Mariano Iglesias', '14: phpnut' => 'Larry E. Masters', '25: gwoo' => 'The Gwoo'); + $this->assertEquals($expected, $result); + + $b = new stdClass(); + $b->users = array( + array('User' => array('id' => 2, 'group_id' => 1, + 'Data' => array('user' => 'mariano.iglesias','name' => 'Mariano Iglesias'))), + array('User' => array('id' => 14, 'group_id' => 2, + 'Data' => array('user' => 'phpnut', 'name' => 'Larry E. Masters'))), + array('User' => array('id' => 25, 'group_id' => 1, + 'Data' => array('user' => 'gwoo','name' => 'The Gwoo')))); + $result = Set::combine($b, 'users.{n}.User.id'); + $expected = array(2 => null, 14 => null, 25 => null); + $this->assertEquals($expected, $result); + + $result = Set::combine($b, 'users.{n}.User.id', 'users.{n}.User.non-existant'); + $expected = array(2 => null, 14 => null, 25 => null); + $this->assertEquals($expected, $result); + + $result = Set::combine($a, 'fail', 'fail'); + $this->assertEquals(array(), $result); + } + +/** + * testMapReverse method + * + * @return void + */ + public function testMapReverse() { + $result = Set::reverse(null); + $this->assertEquals(null, $result); + + $result = Set::reverse(false); + $this->assertEquals(false, $result); + + $expected = array( + 'Array1' => array( + 'Array1Data1' => 'Array1Data1 value 1', 'Array1Data2' => 'Array1Data2 value 2'), + 'Array2' => array( + 0 => array('Array2Data1' => 1, 'Array2Data2' => 'Array2Data2 value 2', 'Array2Data3' => 'Array2Data3 value 2', 'Array2Data4' => 'Array2Data4 value 4'), + 1 => array('Array2Data1' => 2, 'Array2Data2' => 'Array2Data2 value 2', 'Array2Data3' => 'Array2Data3 value 2', 'Array2Data4' => 'Array2Data4 value 4'), + 2 => array('Array2Data1' => 3, 'Array2Data2' => 'Array2Data2 value 2', 'Array2Data3' => 'Array2Data3 value 2', 'Array2Data4' => 'Array2Data4 value 4'), + 3 => array('Array2Data1' => 4, 'Array2Data2' => 'Array2Data2 value 2', 'Array2Data3' => 'Array2Data3 value 2', 'Array2Data4' => 'Array2Data4 value 4'), + 4 => array('Array2Data1' => 5, 'Array2Data2' => 'Array2Data2 value 2', 'Array2Data3' => 'Array2Data3 value 2', 'Array2Data4' => 'Array2Data4 value 4')), + 'Array3' => array( + 0 => array('Array3Data1' => 1, 'Array3Data2' => 'Array3Data2 value 2', 'Array3Data3' => 'Array3Data3 value 2', 'Array3Data4' => 'Array3Data4 value 4'), + 1 => array('Array3Data1' => 2, 'Array3Data2' => 'Array3Data2 value 2', 'Array3Data3' => 'Array3Data3 value 2', 'Array3Data4' => 'Array3Data4 value 4'), + 2 => array('Array3Data1' => 3, 'Array3Data2' => 'Array3Data2 value 2', 'Array3Data3' => 'Array3Data3 value 2', 'Array3Data4' => 'Array3Data4 value 4'), + 3 => array('Array3Data1' => 4, 'Array3Data2' => 'Array3Data2 value 2', 'Array3Data3' => 'Array3Data3 value 2', 'Array3Data4' => 'Array3Data4 value 4'), + 4 => array('Array3Data1' => 5, 'Array3Data2' => 'Array3Data2 value 2', 'Array3Data3' => 'Array3Data3 value 2', 'Array3Data4' => 'Array3Data4 value 4'))); + $map = Set::map($expected, true); + $this->assertEquals($expected['Array1']['Array1Data1'], $map->Array1->Array1Data1); + $this->assertEquals($expected['Array2'][0]['Array2Data1'], $map->Array2[0]->Array2Data1); + + $result = Set::reverse($map); + $this->assertEquals($expected, $result); + + $expected = array( + 'Post' => array('id' => 1, 'title' => 'First Post'), + 'Comment' => array( + array('id' => 1, 'title' => 'First Comment'), + array('id' => 2, 'title' => 'Second Comment') + ), + 'Tag' => array( + array('id' => 1, 'title' => 'First Tag'), + array('id' => 2, 'title' => 'Second Tag') + ), + ); + $map = Set::map($expected); + $this->assertEquals($expected['Post']['title'], $map->title); + foreach ($map->Comment as $comment) { + $ids[] = $comment->id; + } + $this->assertEquals(array(1, 2), $ids); + + $expected = array( + 'Array1' => array( + 'Array1Data1' => 'Array1Data1 value 1', 'Array1Data2' => 'Array1Data2 value 2', 'Array1Data3' => 'Array1Data3 value 3','Array1Data4' => 'Array1Data4 value 4', + 'Array1Data5' => 'Array1Data5 value 5', 'Array1Data6' => 'Array1Data6 value 6', 'Array1Data7' => 'Array1Data7 value 7', 'Array1Data8' => 'Array1Data8 value 8'), + 'string' => 1, + 'another' => 'string', + 'some' => 'thing else', + 'Array2' => array( + 0 => array('Array2Data1' => 1, 'Array2Data2' => 'Array2Data2 value 2', 'Array2Data3' => 'Array2Data3 value 2', 'Array2Data4' => 'Array2Data4 value 4'), + 1 => array('Array2Data1' => 2, 'Array2Data2' => 'Array2Data2 value 2', 'Array2Data3' => 'Array2Data3 value 2', 'Array2Data4' => 'Array2Data4 value 4'), + 2 => array('Array2Data1' => 3, 'Array2Data2' => 'Array2Data2 value 2', 'Array2Data3' => 'Array2Data3 value 2', 'Array2Data4' => 'Array2Data4 value 4'), + 3 => array('Array2Data1' => 4, 'Array2Data2' => 'Array2Data2 value 2', 'Array2Data3' => 'Array2Data3 value 2', 'Array2Data4' => 'Array2Data4 value 4'), + 4 => array('Array2Data1' => 5, 'Array2Data2' => 'Array2Data2 value 2', 'Array2Data3' => 'Array2Data3 value 2', 'Array2Data4' => 'Array2Data4 value 4')), + 'Array3' => array( + 0 => array('Array3Data1' => 1, 'Array3Data2' => 'Array3Data2 value 2', 'Array3Data3' => 'Array3Data3 value 2', 'Array3Data4' => 'Array3Data4 value 4'), + 1 => array('Array3Data1' => 2, 'Array3Data2' => 'Array3Data2 value 2', 'Array3Data3' => 'Array3Data3 value 2', 'Array3Data4' => 'Array3Data4 value 4'), + 2 => array('Array3Data1' => 3, 'Array3Data2' => 'Array3Data2 value 2', 'Array3Data3' => 'Array3Data3 value 2', 'Array3Data4' => 'Array3Data4 value 4'), + 3 => array('Array3Data1' => 4, 'Array3Data2' => 'Array3Data2 value 2', 'Array3Data3' => 'Array3Data3 value 2', 'Array3Data4' => 'Array3Data4 value 4'), + 4 => array('Array3Data1' => 5, 'Array3Data2' => 'Array3Data2 value 2', 'Array3Data3' => 'Array3Data3 value 2', 'Array3Data4' => 'Array3Data4 value 4'))); + $map = Set::map($expected, true); + $result = Set::reverse($map); + $this->assertEquals($expected, $result); + + $expected = array( + 'Array1' => array( + 'Array1Data1' => 'Array1Data1 value 1', 'Array1Data2' => 'Array1Data2 value 2', 'Array1Data3' => 'Array1Data3 value 3','Array1Data4' => 'Array1Data4 value 4', + 'Array1Data5' => 'Array1Data5 value 5', 'Array1Data6' => 'Array1Data6 value 6', 'Array1Data7' => 'Array1Data7 value 7', 'Array1Data8' => 'Array1Data8 value 8'), + 'string' => 1, + 'another' => 'string', + 'some' => 'thing else', + 'Array2' => array( + 0 => array('Array2Data1' => 1, 'Array2Data2' => 'Array2Data2 value 2', 'Array2Data3' => 'Array2Data3 value 2', 'Array2Data4' => 'Array2Data4 value 4'), + 1 => array('Array2Data1' => 2, 'Array2Data2' => 'Array2Data2 value 2', 'Array2Data3' => 'Array2Data3 value 2', 'Array2Data4' => 'Array2Data4 value 4'), + 2 => array('Array2Data1' => 3, 'Array2Data2' => 'Array2Data2 value 2', 'Array2Data3' => 'Array2Data3 value 2', 'Array2Data4' => 'Array2Data4 value 4'), + 3 => array('Array2Data1' => 4, 'Array2Data2' => 'Array2Data2 value 2', 'Array2Data3' => 'Array2Data3 value 2', 'Array2Data4' => 'Array2Data4 value 4'), + 4 => array('Array2Data1' => 5, 'Array2Data2' => 'Array2Data2 value 2', 'Array2Data3' => 'Array2Data3 value 2', 'Array2Data4' => 'Array2Data4 value 4')), + 'string2' => 1, + 'another2' => 'string', + 'some2' => 'thing else', + 'Array3' => array( + 0 => array('Array3Data1' => 1, 'Array3Data2' => 'Array3Data2 value 2', 'Array3Data3' => 'Array3Data3 value 2', 'Array3Data4' => 'Array3Data4 value 4'), + 1 => array('Array3Data1' => 2, 'Array3Data2' => 'Array3Data2 value 2', 'Array3Data3' => 'Array3Data3 value 2', 'Array3Data4' => 'Array3Data4 value 4'), + 2 => array('Array3Data1' => 3, 'Array3Data2' => 'Array3Data2 value 2', 'Array3Data3' => 'Array3Data3 value 2', 'Array3Data4' => 'Array3Data4 value 4'), + 3 => array('Array3Data1' => 4, 'Array3Data2' => 'Array3Data2 value 2', 'Array3Data3' => 'Array3Data3 value 2', 'Array3Data4' => 'Array3Data4 value 4'), + 4 => array('Array3Data1' => 5, 'Array3Data2' => 'Array3Data2 value 2', 'Array3Data3' => 'Array3Data3 value 2', 'Array3Data4' => 'Array3Data4 value 4')), + 'string3' => 1, + 'another3' => 'string', + 'some3' => 'thing else'); + $map = Set::map($expected, true); + $result = Set::reverse($map); + $this->assertEquals($expected, $result); + + $expected = array('User' => array('psword' => 'whatever', 'Icon' => array('id' => 851))); + $map = Set::map($expected); + $result = Set::reverse($map); + $this->assertEquals($expected, $result); + + $expected = array('User' => array('psword' => 'whatever', 'Icon' => array('id' => 851))); + $class = new stdClass; + $class->User = new stdClass; + $class->User->psword = 'whatever'; + $class->User->Icon = new stdClass; + $class->User->Icon->id = 851; + $result = Set::reverse($class); + $this->assertEquals($expected, $result); + + $expected = array('User' => array('psword' => 'whatever', 'Icon' => array('id' => 851), 'Profile' => array('name' => 'Some Name', 'address' => 'Some Address'))); + $class = new stdClass; + $class->User = new stdClass; + $class->User->psword = 'whatever'; + $class->User->Icon = new stdClass; + $class->User->Icon->id = 851; + $class->User->Profile = new stdClass; + $class->User->Profile->name = 'Some Name'; + $class->User->Profile->address = 'Some Address'; + + $result = Set::reverse($class); + $this->assertEquals($expected, $result); + + $expected = array('User' => array('psword' => 'whatever', + 'Icon' => array('id' => 851), + 'Profile' => array('name' => 'Some Name', 'address' => 'Some Address'), + 'Comment' => array( + array('id' => 1, 'article_id' => 1, 'user_id' => 1, 'comment' => 'First Comment for First Article', 'published' => 'Y', 'created' => '2007-03-18 10:47:23', 'updated' => '2007-03-18 10:49:31'), + array('id' => 2, 'article_id' => 1, 'user_id' => 2, 'comment' => 'Second Comment for First Article', 'published' => 'Y', 'created' => '2007-03-18 10:47:23', 'updated' => '2007-03-18 10:49:31')))); + + $class = new stdClass; + $class->User = new stdClass; + $class->User->psword = 'whatever'; + $class->User->Icon = new stdClass; + $class->User->Icon->id = 851; + $class->User->Profile = new stdClass; + $class->User->Profile->name = 'Some Name'; + $class->User->Profile->address = 'Some Address'; + $class->User->Comment = new stdClass; + $class->User->Comment->{'0'} = new stdClass; + $class->User->Comment->{'0'}->id = 1; + $class->User->Comment->{'0'}->article_id = 1; + $class->User->Comment->{'0'}->user_id = 1; + $class->User->Comment->{'0'}->comment = 'First Comment for First Article'; + $class->User->Comment->{'0'}->published = 'Y'; + $class->User->Comment->{'0'}->created = '2007-03-18 10:47:23'; + $class->User->Comment->{'0'}->updated = '2007-03-18 10:49:31'; + $class->User->Comment->{'1'} = new stdClass; + $class->User->Comment->{'1'}->id = 2; + $class->User->Comment->{'1'}->article_id = 1; + $class->User->Comment->{'1'}->user_id = 2; + $class->User->Comment->{'1'}->comment = 'Second Comment for First Article'; + $class->User->Comment->{'1'}->published = 'Y'; + $class->User->Comment->{'1'}->created = '2007-03-18 10:47:23'; + $class->User->Comment->{'1'}->updated = '2007-03-18 10:49:31'; + + $result = Set::reverse($class); + $this->assertEquals($expected, $result); + + $expected = array('User' => array('psword' => 'whatever', + 'Icon' => array('id' => 851), + 'Profile' => array('name' => 'Some Name', 'address' => 'Some Address'), + 'Comment' => array( + array('id' => 1, 'article_id' => 1, 'user_id' => 1, 'comment' => 'First Comment for First Article', 'published' => 'Y', 'created' => '2007-03-18 10:47:23', 'updated' => '2007-03-18 10:49:31'), + array('id' => 2, 'article_id' => 1, 'user_id' => 2, 'comment' => 'Second Comment for First Article', 'published' => 'Y', 'created' => '2007-03-18 10:47:23', 'updated' => '2007-03-18 10:49:31')))); + + // @codingStandardsIgnoreStart + $class = new stdClass; + $class->User = new stdClass; + $class->User->psword = 'whatever'; + $class->User->Icon = new stdClass; + $class->User->Icon->id = 851; + $class->User->Profile = new stdClass; + $class->User->Profile->name = 'Some Name'; + $class->User->Profile->address = 'Some Address'; + $class->User->Comment = array(); + $comment = new stdClass; + $comment->id = 1; + $comment->article_id = 1; + $comment->user_id = 1; + $comment->comment = 'First Comment for First Article'; + $comment->published = 'Y'; + $comment->created = '2007-03-18 10:47:23'; + $comment->updated = '2007-03-18 10:49:31'; + $comment2 = new stdClass; + $comment2->id = 2; + $comment2->article_id = 1; + $comment2->user_id = 2; + $comment2->comment = 'Second Comment for First Article'; + $comment2->published = 'Y'; + $comment2->created = '2007-03-18 10:47:23'; + $comment2->updated = '2007-03-18 10:49:31'; + // @codingStandardsIgnoreEnd + $class->User->Comment = array($comment, $comment2); + $result = Set::reverse($class); + $this->assertEquals($expected, $result); + + $class = new stdClass; + $class->User = new stdClass; + $class->User->id = 100; + $class->someString = 'this is some string'; + $class->Profile = new stdClass; + $class->Profile->name = 'Joe Mamma'; + + $result = Set::reverse($class); + $expected = array( + 'User' => array('id' => '100'), + 'someString' => 'this is some string', + 'Profile' => array('name' => 'Joe Mamma') + ); + $this->assertEquals($expected, $result); + + // @codingStandardsIgnoreStart + $class = new stdClass; + $class->User = new stdClass; + $class->User->id = 100; + $class->User->_name_ = 'User'; + $class->Profile = new stdClass; + $class->Profile->name = 'Joe Mamma'; + $class->Profile->_name_ = 'Profile'; + // @codingStandardsIgnoreEnd + + $result = Set::reverse($class); + $expected = array('User' => array('id' => '100'), 'Profile' => array('name' => 'Joe Mamma')); + $this->assertEquals($expected, $result); + } + +/** + * testFormatting method + * + * @return void + */ + public function testFormatting() { + $data = array( + array('Person' => array('first_name' => 'Nate', 'last_name' => 'Abele', 'city' => 'Boston', 'state' => 'MA', 'something' => '42')), + array('Person' => array('first_name' => 'Larry', 'last_name' => 'Masters', 'city' => 'Boondock', 'state' => 'TN', 'something' => '{0}')), + array('Person' => array('first_name' => 'Garrett', 'last_name' => 'Woodworth', 'city' => 'Venice Beach', 'state' => 'CA', 'something' => '{1}'))); + + $result = Set::format($data, '{1}, {0}', array('{n}.Person.first_name', '{n}.Person.last_name')); + $expected = array('Abele, Nate', 'Masters, Larry', 'Woodworth, Garrett'); + $this->assertEquals($expected, $result); + + $result = Set::format($data, '{0}, {1}', array('{n}.Person.last_name', '{n}.Person.first_name')); + $this->assertEquals($expected, $result); + + $result = Set::format($data, '{0}, {1}', array('{n}.Person.city', '{n}.Person.state')); + $expected = array('Boston, MA', 'Boondock, TN', 'Venice Beach, CA'); + $this->assertEquals($expected, $result); + + $result = Set::format($data, '{{0}, {1}}', array('{n}.Person.city', '{n}.Person.state')); + $expected = array('{Boston, MA}', '{Boondock, TN}', '{Venice Beach, CA}'); + $this->assertEquals($expected, $result); + + $result = Set::format($data, '{{0}, {1}}', array('{n}.Person.something', '{n}.Person.something')); + $expected = array('{42, 42}', '{{0}, {0}}', '{{1}, {1}}'); + $this->assertEquals($expected, $result); + + $result = Set::format($data, '{%2$d, %1$s}', array('{n}.Person.something', '{n}.Person.something')); + $expected = array('{42, 42}', '{0, {0}}', '{0, {1}}'); + $this->assertEquals($expected, $result); + + $result = Set::format($data, '{%1$s, %1$s}', array('{n}.Person.something', '{n}.Person.something')); + $expected = array('{42, 42}', '{{0}, {0}}', '{{1}, {1}}'); + $this->assertEquals($expected, $result); + + $result = Set::format($data, '%2$d, %1$s', array('{n}.Person.first_name', '{n}.Person.something')); + $expected = array('42, Nate', '0, Larry', '0, Garrett'); + $this->assertEquals($expected, $result); + + $result = Set::format($data, '%1$s, %2$d', array('{n}.Person.first_name', '{n}.Person.something')); + $expected = array('Nate, 42', 'Larry, 0', 'Garrett, 0'); + $this->assertEquals($expected, $result); + } + +/** + * testFormattingNullValues method + * + * @return void + */ + public function testFormattingNullValues() { + $data = array( + array('Person' => array('first_name' => 'Nate', 'last_name' => 'Abele', 'city' => 'Boston', 'state' => 'MA', 'something' => '42')), + array('Person' => array('first_name' => 'Larry', 'last_name' => 'Masters', 'city' => 'Boondock', 'state' => 'TN', 'something' => null)), + array('Person' => array('first_name' => 'Garrett', 'last_name' => 'Woodworth', 'city' => 'Venice Beach', 'state' => 'CA', 'something' => null))); + + $result = Set::format($data, '%s', array('{n}.Person.something')); + $expected = array('42', '', ''); + $this->assertEquals($expected, $result); + + $result = Set::format($data, '{0}, {1}', array('{n}.Person.city', '{n}.Person.something')); + $expected = array('Boston, 42', 'Boondock, ', 'Venice Beach, '); + $this->assertEquals($expected, $result); + } + +/** + * testCountDim method + * + * @return void + */ + public function testCountDim() { + $data = array('one', '2', 'three'); + $result = Set::countDim($data); + $this->assertEquals(1, $result); + + $data = array('1' => '1.1', '2', '3'); + $result = Set::countDim($data); + $this->assertEquals(1, $result); + + $data = array('1' => array('1.1' => '1.1.1'), '2', '3' => array('3.1' => '3.1.1')); + $result = Set::countDim($data); + $this->assertEquals(2, $result); + + $data = array('1' => '1.1', '2', '3' => array('3.1' => '3.1.1')); + $result = Set::countDim($data); + $this->assertEquals(1, $result); + + $data = array('1' => '1.1', '2', '3' => array('3.1' => '3.1.1')); + $result = Set::countDim($data, true); + $this->assertEquals(2, $result); + + $data = array('1' => array('1.1' => '1.1.1'), '2', '3' => array('3.1' => array('3.1.1' => '3.1.1.1'))); + $result = Set::countDim($data); + $this->assertEquals(2, $result); + + $data = array('1' => array('1.1' => '1.1.1'), '2', '3' => array('3.1' => array('3.1.1' => '3.1.1.1'))); + $result = Set::countDim($data, true); + $this->assertEquals(3, $result); + + $data = array('1' => array('1.1' => '1.1.1'), array('2' => array('2.1' => array('2.1.1' => '2.1.1.1'))), '3' => array('3.1' => array('3.1.1' => '3.1.1.1'))); + $result = Set::countDim($data, true); + $this->assertEquals(4, $result); + + $data = array('1' => array('1.1' => '1.1.1'), array('2' => array('2.1' => array('2.1.1' => array('2.1.1.1')))), '3' => array('3.1' => array('3.1.1' => '3.1.1.1'))); + $result = Set::countDim($data, true); + $this->assertEquals(5, $result); + + $data = array('1' => array('1.1' => '1.1.1'), array('2' => array('2.1' => array('2.1.1' => array('2.1.1.1' => '2.1.1.1.1')))), '3' => array('3.1' => array('3.1.1' => '3.1.1.1'))); + $result = Set::countDim($data, true); + $this->assertEquals(5, $result); + + $set = array('1' => array('1.1' => '1.1.1'), array('2' => array('2.1' => array('2.1.1' => array('2.1.1.1' => '2.1.1.1.1')))), '3' => array('3.1' => array('3.1.1' => '3.1.1.1'))); + $result = Set::countDim($set, false, 0); + $this->assertEquals(2, $result); + + $result = Set::countDim($set, true); + $this->assertEquals(5, $result); + } + +/** + * testMapNesting method + * + * @return void + */ + public function testMapNesting() { + $expected = array( + array( + "IndexedPage" => array( + "id" => 1, + "url" => 'http://blah.com/', + 'hash' => '68a9f053b19526d08e36c6a9ad150737933816a5', + 'headers' => array( + 'Date' => "Wed, 14 Nov 2007 15:51:42 GMT", + 'Server' => "Apache", + 'Expires' => "Thu, 19 Nov 1981 08:52:00 GMT", + 'Cache-Control' => "private", + 'Pragma' => "no-cache", + 'Content-Type' => "text/html; charset=UTF-8", + 'X-Original-Transfer-Encoding' => "chunked", + 'Content-Length' => "50210", + ), + 'meta' => array( + 'keywords' => array('testing','tests'), + 'description' => 'describe me', + ), + 'get_vars' => '', + 'post_vars' => array(), + 'cookies' => array('PHPSESSID' => "dde9896ad24595998161ffaf9e0dbe2d"), + 'redirect' => '', + 'created' => "1195055503", + 'updated' => "1195055503", + ) + ), + array( + "IndexedPage" => array( + "id" => 2, + "url" => 'http://blah.com/', + 'hash' => '68a9f053b19526d08e36c6a9ad150737933816a5', + 'headers' => array( + 'Date' => "Wed, 14 Nov 2007 15:51:42 GMT", + 'Server' => "Apache", + 'Expires' => "Thu, 19 Nov 1981 08:52:00 GMT", + 'Cache-Control' => "private", + 'Pragma' => "no-cache", + 'Content-Type' => "text/html; charset=UTF-8", + 'X-Original-Transfer-Encoding' => "chunked", + 'Content-Length' => "50210", + ), + 'meta' => array( + 'keywords' => array('testing','tests'), + 'description' => 'describe me', + ), + 'get_vars' => '', + 'post_vars' => array(), + 'cookies' => array('PHPSESSID' => "dde9896ad24595998161ffaf9e0dbe2d"), + 'redirect' => '', + 'created' => "1195055503", + 'updated' => "1195055503", + ), + ) + ); + + $mapped = Set::map($expected); + $ids = array(); + + foreach ($mapped as $object) { + $ids[] = $object->id; + } + $this->assertEquals(array(1, 2), $ids); + $this->assertEquals($expected[0]['IndexedPage']['headers'], get_object_vars($mapped[0]->headers)); + + $result = Set::reverse($mapped); + $this->assertEquals($expected, $result); + + $data = array( + array( + "IndexedPage" => array( + "id" => 1, + "url" => 'http://blah.com/', + 'hash' => '68a9f053b19526d08e36c6a9ad150737933816a5', + 'get_vars' => '', + 'redirect' => '', + 'created' => "1195055503", + 'updated' => "1195055503", + ) + ), + array( + "IndexedPage" => array( + "id" => 2, + "url" => 'http://blah.com/', + 'hash' => '68a9f053b19526d08e36c6a9ad150737933816a5', + 'get_vars' => '', + 'redirect' => '', + 'created' => "1195055503", + 'updated' => "1195055503", + ), + ) + ); + $mapped = Set::map($data); + + // @codingStandardsIgnoreStart + $expected = new stdClass(); + $expected->_name_ = 'IndexedPage'; + $expected->id = 2; + $expected->url = 'http://blah.com/'; + $expected->hash = '68a9f053b19526d08e36c6a9ad150737933816a5'; + $expected->get_vars = ''; + $expected->redirect = ''; + $expected->created = "1195055503"; + $expected->updated = "1195055503"; + // @codingStandardsIgnoreEnd + $this->assertEquals($expected, $mapped[1]); + + $ids = array(); + + foreach ($mapped as $object) { + $ids[] = $object->id; + } + $this->assertEquals(array(1, 2), $ids); + + $result = Set::map(null); + $expected = null; + $this->assertEquals($expected, $result); + } + +/** + * testNestedMappedData method + * + * @return void + */ + public function testNestedMappedData() { + $result = Set::map(array( + array( + 'Post' => array('id' => '1', 'author_id' => '1', 'title' => 'First Post', 'body' => 'First Post Body', 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31'), + 'Author' => array('id' => '1', 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31', 'test' => 'working'), + ) + , array( + 'Post' => array('id' => '2', 'author_id' => '3', 'title' => 'Second Post', 'body' => 'Second Post Body', 'published' => 'Y', 'created' => '2007-03-18 10:41:23', 'updated' => '2007-03-18 10:43:31'), + 'Author' => array('id' => '3', 'user' => 'larry', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', 'created' => '2007-03-17 01:20:23', 'updated' => '2007-03-17 01:22:31', 'test' => 'working'), + ) + )); + + // @codingStandardsIgnoreStart + $expected = new stdClass; + $expected->_name_ = 'Post'; + $expected->id = '1'; + $expected->author_id = '1'; + $expected->title = 'First Post'; + $expected->body = 'First Post Body'; + $expected->published = 'Y'; + $expected->created = "2007-03-18 10:39:23"; + $expected->updated = "2007-03-18 10:41:31"; + + $expected->Author = new stdClass; + $expected->Author->id = '1'; + $expected->Author->user = 'mariano'; + $expected->Author->password = '5f4dcc3b5aa765d61d8327deb882cf99'; + $expected->Author->created = "2007-03-17 01:16:23"; + $expected->Author->updated = "2007-03-17 01:18:31"; + $expected->Author->test = "working"; + $expected->Author->_name_ = 'Author'; + + $expected2 = new stdClass; + $expected2->_name_ = 'Post'; + $expected2->id = '2'; + $expected2->author_id = '3'; + $expected2->title = 'Second Post'; + $expected2->body = 'Second Post Body'; + $expected2->published = 'Y'; + $expected2->created = "2007-03-18 10:41:23"; + $expected2->updated = "2007-03-18 10:43:31"; + + $expected2->Author = new stdClass; + $expected2->Author->id = '3'; + $expected2->Author->user = 'larry'; + $expected2->Author->password = '5f4dcc3b5aa765d61d8327deb882cf99'; + $expected2->Author->created = "2007-03-17 01:20:23"; + $expected2->Author->updated = "2007-03-17 01:22:31"; + $expected2->Author->test = "working"; + $expected2->Author->_name_ = 'Author'; + // @codingStandardsIgnoreEnd + + $test = array(); + $test[0] = $expected; + $test[1] = $expected2; + + $this->assertEquals($test, $result); + + $result = Set::map( + array( + 'Post' => array('id' => '1', 'author_id' => '1', 'title' => 'First Post', 'body' => 'First Post Body', 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31'), + 'Author' => array('id' => '1', 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31', 'test' => 'working'), + ) + ); + // @codingStandardsIgnoreStart + $expected = new stdClass; + $expected->_name_ = 'Post'; + $expected->id = '1'; + $expected->author_id = '1'; + $expected->title = 'First Post'; + $expected->body = 'First Post Body'; + $expected->published = 'Y'; + $expected->created = "2007-03-18 10:39:23"; + $expected->updated = "2007-03-18 10:41:31"; + + $expected->Author = new stdClass; + $expected->Author->id = '1'; + $expected->Author->user = 'mariano'; + $expected->Author->password = '5f4dcc3b5aa765d61d8327deb882cf99'; + $expected->Author->created = "2007-03-17 01:16:23"; + $expected->Author->updated = "2007-03-17 01:18:31"; + $expected->Author->test = "working"; + $expected->Author->_name_ = 'Author'; + // @codingStandardsIgnoreEnd + $this->assertEquals($expected, $result); + + //Case where extra HABTM fields come back in a result + $data = array( + 'User' => array( + 'id' => 1, + 'email' => 'user@example.com', + 'first_name' => 'John', + 'last_name' => 'Smith', + ), + 'Piece' => array( + array( + 'id' => 1, + 'title' => 'Moonlight Sonata', + 'composer' => 'Ludwig van Beethoven', + 'PiecesUser' => array( + 'id' => 1, + 'created' => '2008-01-01 00:00:00', + 'modified' => '2008-01-01 00:00:00', + 'piece_id' => 1, + 'user_id' => 2, + ) + ), + array( + 'id' => 2, + 'title' => 'Moonlight Sonata 2', + 'composer' => 'Ludwig van Beethoven', + 'PiecesUser' => array( + 'id' => 2, + 'created' => '2008-01-01 00:00:00', + 'modified' => '2008-01-01 00:00:00', + 'piece_id' => 2, + 'user_id' => 2, + ) + ) + ) + ); + + $result = Set::map($data); + + // @codingStandardsIgnoreStart + $expected = new stdClass(); + $expected->_name_ = 'User'; + $expected->id = 1; + $expected->email = 'user@example.com'; + $expected->first_name = 'John'; + $expected->last_name = 'Smith'; + + $piece = new stdClass(); + $piece->id = 1; + $piece->title = 'Moonlight Sonata'; + $piece->composer = 'Ludwig van Beethoven'; + + $piece->PiecesUser = new stdClass(); + $piece->PiecesUser->id = 1; + $piece->PiecesUser->created = '2008-01-01 00:00:00'; + $piece->PiecesUser->modified = '2008-01-01 00:00:00'; + $piece->PiecesUser->piece_id = 1; + $piece->PiecesUser->user_id = 2; + $piece->PiecesUser->_name_ = 'PiecesUser'; + + $piece->_name_ = 'Piece'; + + $piece2 = new stdClass(); + $piece2->id = 2; + $piece2->title = 'Moonlight Sonata 2'; + $piece2->composer = 'Ludwig van Beethoven'; + + $piece2->PiecesUser = new stdClass(); + $piece2->PiecesUser->id = 2; + $piece2->PiecesUser->created = '2008-01-01 00:00:00'; + $piece2->PiecesUser->modified = '2008-01-01 00:00:00'; + $piece2->PiecesUser->piece_id = 2; + $piece2->PiecesUser->user_id = 2; + $piece2->PiecesUser->_name_ = 'PiecesUser'; + + $piece2->_name_ = 'Piece'; + // @codingStandardsIgnoreEnd + + $expected->Piece = array($piece, $piece2); + + $this->assertEquals($expected, $result); + + //Same data, but should work if _name_ has been manually defined: + $data = array( + 'User' => array( + 'id' => 1, + 'email' => 'user@example.com', + 'first_name' => 'John', + 'last_name' => 'Smith', + '_name_' => 'FooUser', + ), + 'Piece' => array( + array( + 'id' => 1, + 'title' => 'Moonlight Sonata', + 'composer' => 'Ludwig van Beethoven', + '_name_' => 'FooPiece', + 'PiecesUser' => array( + 'id' => 1, + 'created' => '2008-01-01 00:00:00', + 'modified' => '2008-01-01 00:00:00', + 'piece_id' => 1, + 'user_id' => 2, + '_name_' => 'FooPiecesUser', + ) + ), + array( + 'id' => 2, + 'title' => 'Moonlight Sonata 2', + 'composer' => 'Ludwig van Beethoven', + '_name_' => 'FooPiece', + 'PiecesUser' => array( + 'id' => 2, + 'created' => '2008-01-01 00:00:00', + 'modified' => '2008-01-01 00:00:00', + 'piece_id' => 2, + 'user_id' => 2, + '_name_' => 'FooPiecesUser', + ) + ) + ) + ); + + $result = Set::map($data); + + // @codingStandardsIgnoreStart + $expected = new stdClass(); + $expected->_name_ = 'FooUser'; + $expected->id = 1; + $expected->email = 'user@example.com'; + $expected->first_name = 'John'; + $expected->last_name = 'Smith'; + + $piece = new stdClass(); + $piece->id = 1; + $piece->title = 'Moonlight Sonata'; + $piece->composer = 'Ludwig van Beethoven'; + $piece->_name_ = 'FooPiece'; + $piece->PiecesUser = new stdClass(); + $piece->PiecesUser->id = 1; + $piece->PiecesUser->created = '2008-01-01 00:00:00'; + $piece->PiecesUser->modified = '2008-01-01 00:00:00'; + $piece->PiecesUser->piece_id = 1; + $piece->PiecesUser->user_id = 2; + $piece->PiecesUser->_name_ = 'FooPiecesUser'; + + $piece2 = new stdClass(); + $piece2->id = 2; + $piece2->title = 'Moonlight Sonata 2'; + $piece2->composer = 'Ludwig van Beethoven'; + $piece2->_name_ = 'FooPiece'; + $piece2->PiecesUser = new stdClass(); + $piece2->PiecesUser->id = 2; + $piece2->PiecesUser->created = '2008-01-01 00:00:00'; + $piece2->PiecesUser->modified = '2008-01-01 00:00:00'; + $piece2->PiecesUser->piece_id = 2; + $piece2->PiecesUser->user_id = 2; + $piece2->PiecesUser->_name_ = 'FooPiecesUser'; + // @codingStandardsIgnoreEnd + + $expected->Piece = array($piece, $piece2); + + $this->assertEquals($expected, $result); + } + +/** + * testPushDiff method + * + * @return void + */ + public function testPushDiff() { + $array1 = array('ModelOne' => array('id' => 1001, 'field_one' => 'a1.m1.f1', 'field_two' => 'a1.m1.f2')); + $array2 = array('ModelTwo' => array('id' => 1002, 'field_one' => 'a2.m2.f1', 'field_two' => 'a2.m2.f2')); + + $result = Set::pushDiff($array1, $array2); + + $this->assertEquals($array1 + $array2, $result); + + $array3 = array('ModelOne' => array('id' => 1003, 'field_one' => 'a3.m1.f1', 'field_two' => 'a3.m1.f2', 'field_three' => 'a3.m1.f3')); + $result = Set::pushDiff($array1, $array3); + + $expected = array('ModelOne' => array('id' => 1001, 'field_one' => 'a1.m1.f1', 'field_two' => 'a1.m1.f2', 'field_three' => 'a3.m1.f3')); + $this->assertEquals($expected, $result); + + $array1 = array( + 0 => array('ModelOne' => array('id' => 1001, 'field_one' => 's1.0.m1.f1', 'field_two' => 's1.0.m1.f2')), + 1 => array('ModelTwo' => array('id' => 1002, 'field_one' => 's1.1.m2.f2', 'field_two' => 's1.1.m2.f2'))); + $array2 = array( + 0 => array('ModelOne' => array('id' => 1001, 'field_one' => 's2.0.m1.f1', 'field_two' => 's2.0.m1.f2')), + 1 => array('ModelTwo' => array('id' => 1002, 'field_one' => 's2.1.m2.f2', 'field_two' => 's2.1.m2.f2'))); + + $result = Set::pushDiff($array1, $array2); + $this->assertEquals($array1, $result); + + $array3 = array(0 => array('ModelThree' => array('id' => 1003, 'field_one' => 's3.0.m3.f1', 'field_two' => 's3.0.m3.f2'))); + + $result = Set::pushDiff($array1, $array3); + $expected = array( + 0 => array('ModelOne' => array('id' => 1001, 'field_one' => 's1.0.m1.f1', 'field_two' => 's1.0.m1.f2'), + 'ModelThree' => array('id' => 1003, 'field_one' => 's3.0.m3.f1', 'field_two' => 's3.0.m3.f2')), + 1 => array('ModelTwo' => array('id' => 1002, 'field_one' => 's1.1.m2.f2', 'field_two' => 's1.1.m2.f2'))); + $this->assertEquals($expected, $result); + + $result = Set::pushDiff($array1, null); + $this->assertEquals($array1, $result); + + $result = Set::pushDiff($array1, $array2); + $this->assertEquals($array1 + $array2, $result); + } + +/** + * testSetApply method + * @return void + * + */ + public function testApply() { + $data = array( + array('Movie' => array('id' => 1, 'title' => 'movie 3', 'rating' => 5)), + array('Movie' => array('id' => 1, 'title' => 'movie 1', 'rating' => 1)), + array('Movie' => array('id' => 1, 'title' => 'movie 2', 'rating' => 3)) + ); + + $result = Set::apply('/Movie/rating', $data, 'array_sum'); + $expected = 9; + $this->assertEquals($expected, $result); + + $result = Set::apply('/Movie/rating', $data, 'array_product'); + $expected = 15; + $this->assertEquals($expected, $result); + + $result = Set::apply('/Movie/title', $data, 'ucfirst', array('type' => 'map')); + $expected = array('Movie 3', 'Movie 1', 'Movie 2'); + $this->assertEquals($expected, $result); + + $result = Set::apply('/Movie/title', $data, 'strtoupper', array('type' => 'map')); + $expected = array('MOVIE 3', 'MOVIE 1', 'MOVIE 2'); + $this->assertEquals($expected, $result); + + $result = Set::apply('/Movie/rating', $data, array('SetTest', 'method'), array('type' => 'reduce')); + $expected = 9; + $this->assertEquals($expected, $result); + + $result = Set::apply('/Movie/rating', $data, 'strtoupper', array('type' => 'non existing type')); + $expected = null; + $this->assertEquals($expected, $result); + } + +/** + * Helper method to test Set::apply() + * + * @return void + */ + public static function method($val1, $val2) { + $val1 += $val2; + return $val1; + } + +/** + * testXmlSetReverse method + * + * @return void + */ + public function testXmlSetReverse() { + App::uses('Xml', 'Utility'); + + $string = ' + + + Cake PHP Google Group + http://groups.google.com/group/cake-php + Search this group before posting anything. There are over 20,000 posts and it&#39;s very likely your question was answered before. Visit the IRC channel #cakephp at irc.freenode.net for live chat with users and developers of Cake. If you post, tell us the version of Cake, PHP, and database. + en + + constructng result array when using findall + http://groups.google.com/group/cake-php/msg/49bc00f3bc651b4f + i'm using cakephp to construct a logical data model array that will be <br> passed to a flex app. I have the following model association: <br> ServiceDay-&gt;(hasMany)ServiceTi me-&gt;(hasMany)ServiceTimePrice. So what <br> the current output from my findall is something like this example: <br> <p>Array( <br> [0] =&gt; Array( + http://groups.google.com/group/cake-php/msg/49bc00f3bc651b4f + bmil...@gmail.com(bpscrugs) + Fri, 28 Dec 2007 00:44:14 UT + + + Re: share views between actions? + http://groups.google.com/group/cake-php/msg/8b350d898707dad8 + Then perhaps you might do us all a favour and refrain from replying to <br> things you do not understand. That goes especially for asinine comments. <br> Indeed. <br> To sum up: <br> No comment. <br> In my day, a simple &quot;RTFM&quot; would suffice. I'll keep in mind to ignore any <br> further responses from you. <br> You (and I) were referring to the *online documentation*, not other + http://groups.google.com/group/cake-php/msg/8b350d898707dad8 + subtropolis.z...@gmail.com(subtropolis zijn) + Fri, 28 Dec 2007 00:45:01 UT + + + '; + $xml = Xml::build($string); + $result = Set::reverse($xml); + $expected = array('rss' => array( + '@version' => '2.0', + 'channel' => array( + 'title' => 'Cake PHP Google Group', + 'link' => 'http://groups.google.com/group/cake-php', + 'description' => 'Search this group before posting anything. There are over 20,000 posts and it's very likely your question was answered before. Visit the IRC channel #cakephp at irc.freenode.net for live chat with users and developers of Cake. If you post, tell us the version of Cake, PHP, and database.', + 'language' => 'en', + 'item' => array( + array( + 'title' => 'constructng result array when using findall', + 'link' => 'http://groups.google.com/group/cake-php/msg/49bc00f3bc651b4f', + 'description' => "i'm using cakephp to construct a logical data model array that will be
passed to a flex app. I have the following model association:
ServiceDay->(hasMany)ServiceTi me->(hasMany)ServiceTimePrice. So what
the current output from my findall is something like this example:

Array(
[0] => Array(", + 'guid' => array('@isPermaLink' => 'true', '@' => 'http://groups.google.com/group/cake-php/msg/49bc00f3bc651b4f'), + 'author' => 'bmil...@gmail.com(bpscrugs)', + 'pubDate' => 'Fri, 28 Dec 2007 00:44:14 UT', + ), + array( + 'title' => 'Re: share views between actions?', + 'link' => 'http://groups.google.com/group/cake-php/msg/8b350d898707dad8', + 'description' => 'Then perhaps you might do us all a favour and refrain from replying to
things you do not understand. That goes especially for asinine comments.
Indeed.
To sum up:
No comment.
In my day, a simple "RTFM" would suffice. I\'ll keep in mind to ignore any
further responses from you.
You (and I) were referring to the *online documentation*, not other', + 'guid' => array('@isPermaLink' => 'true', '@' => 'http://groups.google.com/group/cake-php/msg/8b350d898707dad8'), + 'author' => 'subtropolis.z...@gmail.com(subtropolis zijn)', + 'pubDate' => 'Fri, 28 Dec 2007 00:45:01 UT' + ) + ) + ) + )); + $this->assertEquals($expected, $result); + $string = ''; + + $xml = Xml::build($string); + $result = Set::reverse($xml); + $expected = array('data' => array('post' => array('@title' => 'Title of this post', '@description' => 'cool'))); + $this->assertEquals($expected, $result); + + $xml = Xml::build('An example of a correctly reversed SimpleXMLElement'); + $result = Set::reverse($xml); + $expected = array('example' => + array( + 'item' => array( + 'title' => 'An example of a correctly reversed SimpleXMLElement', + 'desc' => '', + ) + ) + ); + $this->assertEquals($expected, $result); + + $xml = Xml::build('title1title2'); + $result = Set::reverse($xml); + $expected = + array('example' => array( + 'item' => array( + '@attr' => '123', + 'titles' => array( + 'title' => array('title1', 'title2') + ) + ) + ) + ); + $this->assertEquals($expected, $result); + + $xml = Xml::build('listtextforitems'); + $result = Set::reverse($xml); + $expected = + array('example' => array( + '@attr' => 'ex_attr', + 'item' => array( + '@attr' => '123', + 'titles' => 'list', + '@' => 'textforitems' + ) + ) + ); + $this->assertEquals($expected, $result); + + $string = ' + + + Cake PHP Google Group + http://groups.google.com/group/cake-php + Search this group before posting anything. There are over 20,000 posts and it&#39;s very likely your question was answered before. Visit the IRC channel #cakephp at irc.freenode.net for live chat with users and developers of Cake. If you post, tell us the version of Cake, PHP, and database. + en + + constructng result array when using findall + http://groups.google.com/group/cake-php/msg/49bc00f3bc651b4f + i'm using cakephp to construct a logical data model array that will be <br> passed to a flex app. I have the following model association: <br> ServiceDay-&gt;(hasMany)ServiceTi me-&gt;(hasMany)ServiceTimePrice. So what <br> the current output from my findall is something like this example: <br> <p>Array( <br> [0] =&gt; Array( + cakephp + + + http://groups.google.com/group/cake-php/msg/49bc00f3bc651b4f + bmil...@gmail.com(bpscrugs) + Fri, 28 Dec 2007 00:44:14 UT + + + Re: share views between actions? + http://groups.google.com/group/cake-php/msg/8b350d898707dad8 + Then perhaps you might do us all a favour and refrain from replying to <br> things you do not understand. That goes especially for asinine comments. <br> Indeed. <br> To sum up: <br> No comment. <br> In my day, a simple &quot;RTFM&quot; would suffice. I'll keep in mind to ignore any <br> further responses from you. <br> You (and I) were referring to the *online documentation*, not other + cakephp + + + http://groups.google.com/group/cake-php/msg/8b350d898707dad8 + subtropolis.z...@gmail.com(subtropolis zijn) + Fri, 28 Dec 2007 00:45:01 UT + + + '; + + $xml = Xml::build($string); + $result = Set::reverse($xml); + + $expected = array('rss' => array( + '@version' => '2.0', + 'channel' => array( + 'title' => 'Cake PHP Google Group', + 'link' => 'http://groups.google.com/group/cake-php', + 'description' => 'Search this group before posting anything. There are over 20,000 posts and it's very likely your question was answered before. Visit the IRC channel #cakephp at irc.freenode.net for live chat with users and developers of Cake. If you post, tell us the version of Cake, PHP, and database.', + 'language' => 'en', + 'item' => array( + array( + 'title' => 'constructng result array when using findall', + 'link' => 'http://groups.google.com/group/cake-php/msg/49bc00f3bc651b4f', + 'description' => "i'm using cakephp to construct a logical data model array that will be
passed to a flex app. I have the following model association:
ServiceDay->(hasMany)ServiceTi me->(hasMany)ServiceTimePrice. So what
the current output from my findall is something like this example:

Array(
[0] => Array(", + 'dc:creator' => 'cakephp', + 'category' => array('cakephp', 'model'), + 'guid' => array('@isPermaLink' => 'true', '@' => 'http://groups.google.com/group/cake-php/msg/49bc00f3bc651b4f'), + 'author' => 'bmil...@gmail.com(bpscrugs)', + 'pubDate' => 'Fri, 28 Dec 2007 00:44:14 UT', + ), + array( + 'title' => 'Re: share views between actions?', + 'link' => 'http://groups.google.com/group/cake-php/msg/8b350d898707dad8', + 'description' => 'Then perhaps you might do us all a favour and refrain from replying to
things you do not understand. That goes especially for asinine comments.
Indeed.
To sum up:
No comment.
In my day, a simple "RTFM" would suffice. I\'ll keep in mind to ignore any
further responses from you.
You (and I) were referring to the *online documentation*, not other', + 'dc:creator' => 'cakephp', + 'category' => array('cakephp', 'model'), + 'guid' => array('@isPermaLink' => 'true', '@' => 'http://groups.google.com/group/cake-php/msg/8b350d898707dad8'), + 'author' => 'subtropolis.z...@gmail.com(subtropolis zijn)', + 'pubDate' => 'Fri, 28 Dec 2007 00:45:01 UT' + ) + ) + ) + )); + $this->assertEquals($expected, $result); + + $text = ' + + + xri://$xrds*simple + 2008-04-13T07:34:58Z + + http://oauth.net/core/1.0/endpoint/authorize + http://oauth.net/core/1.0/parameters/auth-header + http://oauth.net/core/1.0/parameters/uri-query + https://ma.gnolia.com/oauth/authorize + http://ma.gnolia.com/oauth/authorize + + + + xri://$xrds*simple + + http://oauth.net/discovery/1.0 + #oauth + + + '; + + $xml = Xml::build($text); + $result = Set::reverse($xml); + + $expected = array('XRDS' => array( + 'XRD' => array( + array( + '@xml:id' => 'oauth', + '@version' => '2.0', + 'Type' => 'xri://$xrds*simple', + 'Expires' => '2008-04-13T07:34:58Z', + 'Service' => array( + 'Type' => array( + 'http://oauth.net/core/1.0/endpoint/authorize', + 'http://oauth.net/core/1.0/parameters/auth-header', + 'http://oauth.net/core/1.0/parameters/uri-query' + ), + 'URI' => array( + array( + '@' => 'https://ma.gnolia.com/oauth/authorize', + '@priority' => '10', + ), + array( + '@' => 'http://ma.gnolia.com/oauth/authorize', + '@priority' => '20' + ) + ) + ) + ), + array( + '@version' => '2.0', + 'Type' => 'xri://$xrds*simple', + 'Service' => array( + '@priority' => '10', + 'Type' => 'http://oauth.net/discovery/1.0', + 'URI' => '#oauth' + ) + ) + ) + )); + $this->assertEquals($expected, $result); + } + +/** + * testStrictKeyCheck method + * + * @return void + */ + public function testStrictKeyCheck() { + $set = array('a' => 'hi'); + $this->assertFalse(Set::check($set, 'a.b')); + } + +/** + * Tests Set::flatten + * + * @return void + */ + public function testFlatten() { + $data = array('Larry', 'Curly', 'Moe'); + $result = Set::flatten($data); + $this->assertEquals($data, $result); + + $data[9] = 'Shemp'; + $result = Set::flatten($data); + $this->assertEquals($data, $result); + } + +/** + * Tests Set::expand + * + * @return void + */ + public function testExpand() { + $data = array('My', 'Array', 'To', 'Flatten'); + $flat = Set::flatten($data); + $result = Set::expand($flat); + $this->assertEquals($data, $result); + } + +/** + * test normalization + * + * @return void + */ + public function testNormalizeStrings() { + $result = Set::normalize('one,two,three'); + $expected = array('one' => null, 'two' => null, 'three' => null); + $this->assertEquals($expected, $result); + + $result = Set::normalize('one two three', true, ' '); + $expected = array('one' => null, 'two' => null, 'three' => null); + $this->assertEquals($expected, $result); + + $result = Set::normalize('one , two , three ', true, ',', true); + $expected = array('one' => null, 'two' => null, 'three' => null); + $this->assertEquals($expected, $result); + } + +/** + * test normalizing arrays + * + * @return void + */ + public function testNormalizeArrays() { + $result = Set::normalize(array('one', 'two', 'three')); + $expected = array('one' => null, 'two' => null, 'three' => null); + $this->assertEquals($expected, $result); + + $result = Set::normalize(array('one', 'two', 'three'), false); + $expected = array('one', 'two', 'three'); + $this->assertEquals($expected, $result); + + $result = Set::normalize(array('one' => 1, 'two' => 2, 'three' => 3, 'four'), false); + $expected = array('one' => 1, 'two' => 2, 'three' => 3, 'four' => null); + $this->assertEquals($expected, $result); + + $result = Set::normalize(array('one' => 1, 'two' => 2, 'three' => 3, 'four')); + $expected = array('one' => 1, 'two' => 2, 'three' => 3, 'four' => null); + $this->assertEquals($expected, $result); + + $result = Set::normalize(array('one' => array('a', 'b', 'c' => 'cee'), 'two' => 2, 'three')); + $expected = array('one' => array('a', 'b', 'c' => 'cee'), 'two' => 2, 'three' => null); + $this->assertEquals($expected, $result); + } + +/** + * test Set nest with a normal model result set. For kicks rely on Set nest detecting the key names + * automatically + * + * @return void + */ + public function testNestModel() { + $input = array( + array( + 'ModelName' => array( + 'id' => 1, + 'parent_id' => null + ), + ), + array( + 'ModelName' => array( + 'id' => 2, + 'parent_id' => 1 + ), + ), + array( + 'ModelName' => array( + 'id' => 3, + 'parent_id' => 1 + ), + ), + array( + 'ModelName' => array( + 'id' => 4, + 'parent_id' => 1 + ), + ), + array( + 'ModelName' => array( + 'id' => 5, + 'parent_id' => 1 + ), + ), + array( + 'ModelName' => array( + 'id' => 6, + 'parent_id' => null + ), + ), + array( + 'ModelName' => array( + 'id' => 7, + 'parent_id' => 6 + ), + ), + array( + 'ModelName' => array( + 'id' => 8, + 'parent_id' => 6 + ), + ), + array( + 'ModelName' => array( + 'id' => 9, + 'parent_id' => 6 + ), + ), + array( + 'ModelName' => array( + 'id' => 10, + 'parent_id' => 6 + ) + ) + ); + $expected = array( + array( + 'ModelName' => array( + 'id' => 1, + 'parent_id' => null + ), + 'children' => array( + array( + 'ModelName' => array( + 'id' => 2, + 'parent_id' => 1 + ), + 'children' => array() + ), + array( + 'ModelName' => array( + 'id' => 3, + 'parent_id' => 1 + ), + 'children' => array() + ), + array( + 'ModelName' => array( + 'id' => 4, + 'parent_id' => 1 + ), + 'children' => array() + ), + array( + 'ModelName' => array( + 'id' => 5, + 'parent_id' => 1 + ), + 'children' => array() + ), + + ) + ), + array( + 'ModelName' => array( + 'id' => 6, + 'parent_id' => null + ), + 'children' => array( + array( + 'ModelName' => array( + 'id' => 7, + 'parent_id' => 6 + ), + 'children' => array() + ), + array( + 'ModelName' => array( + 'id' => 8, + 'parent_id' => 6 + ), + 'children' => array() + ), + array( + 'ModelName' => array( + 'id' => 9, + 'parent_id' => 6 + ), + 'children' => array() + ), + array( + 'ModelName' => array( + 'id' => 10, + 'parent_id' => 6 + ), + 'children' => array() + ) + ) + ) + ); + $result = Set::nest($input); + $this->assertEquals($expected, $result); + } + +/** + * test Set nest with a normal model result set, and a nominated root id + * + * @return void + */ + public function testNestModelExplicitRoot() { + $input = array( + array( + 'ModelName' => array( + 'id' => 1, + 'parent_id' => null + ), + ), + array( + 'ModelName' => array( + 'id' => 2, + 'parent_id' => 1 + ), + ), + array( + 'ModelName' => array( + 'id' => 3, + 'parent_id' => 1 + ), + ), + array( + 'ModelName' => array( + 'id' => 4, + 'parent_id' => 1 + ), + ), + array( + 'ModelName' => array( + 'id' => 5, + 'parent_id' => 1 + ), + ), + array( + 'ModelName' => array( + 'id' => 6, + 'parent_id' => null + ), + ), + array( + 'ModelName' => array( + 'id' => 7, + 'parent_id' => 6 + ), + ), + array( + 'ModelName' => array( + 'id' => 8, + 'parent_id' => 6 + ), + ), + array( + 'ModelName' => array( + 'id' => 9, + 'parent_id' => 6 + ), + ), + array( + 'ModelName' => array( + 'id' => 10, + 'parent_id' => 6 + ) + ) + ); + $expected = array( + array( + 'ModelName' => array( + 'id' => 6, + 'parent_id' => null + ), + 'children' => array( + array( + 'ModelName' => array( + 'id' => 7, + 'parent_id' => 6 + ), + 'children' => array() + ), + array( + 'ModelName' => array( + 'id' => 8, + 'parent_id' => 6 + ), + 'children' => array() + ), + array( + 'ModelName' => array( + 'id' => 9, + 'parent_id' => 6 + ), + 'children' => array() + ), + array( + 'ModelName' => array( + 'id' => 10, + 'parent_id' => 6 + ), + 'children' => array() + ) + ) + ) + ); + $result = Set::nest($input, array('root' => 6)); + $this->assertEquals($expected, $result); + } + +/** + * test Set nest with a 1d array - this method should be able to handle any type of array input + * + * @return void + */ + public function testNest1Dimensional() { + $input = array( + array( + 'id' => 1, + 'parent_id' => null + ), + array( + 'id' => 2, + 'parent_id' => 1 + ), + array( + 'id' => 3, + 'parent_id' => 1 + ), + array( + 'id' => 4, + 'parent_id' => 1 + ), + array( + 'id' => 5, + 'parent_id' => 1 + ), + array( + 'id' => 6, + 'parent_id' => null + ), + array( + 'id' => 7, + 'parent_id' => 6 + ), + array( + 'id' => 8, + 'parent_id' => 6 + ), + array( + 'id' => 9, + 'parent_id' => 6 + ), + array( + 'id' => 10, + 'parent_id' => 6 + ) + ); + $expected = array( + array( + 'id' => 1, + 'parent_id' => null, + 'children' => array( + array( + 'id' => 2, + 'parent_id' => 1, + 'children' => array() + ), + array( + 'id' => 3, + 'parent_id' => 1, + 'children' => array() + ), + array( + 'id' => 4, + 'parent_id' => 1, + 'children' => array() + ), + array( + 'id' => 5, + 'parent_id' => 1, + 'children' => array() + ), + + ) + ), + array( + 'id' => 6, + 'parent_id' => null, + 'children' => array( + array( + 'id' => 7, + 'parent_id' => 6, + 'children' => array() + ), + array( + 'id' => 8, + 'parent_id' => 6, + 'children' => array() + ), + array( + 'id' => 9, + 'parent_id' => 6, + 'children' => array() + ), + array( + 'id' => 10, + 'parent_id' => 6, + 'children' => array() + ) + ) + ) + ); + $result = Set::nest($input, array('idPath' => '/id', 'parentPath' => '/parent_id')); + $this->assertEquals($expected, $result); + } + +/** + * test Set nest with no specified parent data. + * + * The result should be the same as the input. + * For an easier comparison, unset all the empty children arrays from the result + * + * @return void + */ + public function testMissingParent() { + $input = array( + array( + 'id' => 1, + ), + array( + 'id' => 2, + ), + array( + 'id' => 3, + ), + array( + 'id' => 4, + ), + array( + 'id' => 5, + ), + array( + 'id' => 6, + ), + array( + 'id' => 7, + ), + array( + 'id' => 8, + ), + array( + 'id' => 9, + ), + array( + 'id' => 10, + ) + ); + + $result = Set::nest($input, array('idPath' => '/id', 'parentPath' => '/parent_id')); + foreach ($result as &$row) { + if (empty($row['children'])) { + unset($row['children']); + } + } + $this->assertEquals($input, $result); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Utility/StringTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Utility/StringTest.php new file mode 100644 index 0000000..efa024b --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Utility/StringTest.php @@ -0,0 +1,650 @@ +Text = new String(); + } + + public function tearDown() { + parent::tearDown(); + unset($this->Text); + } + +/** + * testUuidGeneration method + * + * @return void + */ + public function testUuidGeneration() { + $result = String::uuid(); + $pattern = "/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/"; + $match = (bool)preg_match($pattern, $result); + $this->assertTrue($match); + } + +/** + * testMultipleUuidGeneration method + * + * @return void + */ + public function testMultipleUuidGeneration() { + $check = array(); + $count = mt_rand(10, 1000); + $pattern = "/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/"; + + for ($i = 0; $i < $count; $i++) { + $result = String::uuid(); + $match = (bool)preg_match($pattern, $result); + $this->assertTrue($match); + $this->assertFalse(in_array($result, $check)); + $check[] = $result; + } + } + +/** + * testInsert method + * + * @return void + */ + public function testInsert() { + $string = 'some string'; + $expected = 'some string'; + $result = String::insert($string, array()); + $this->assertEquals($expected, $result); + + $string = '2 + 2 = :sum. Cake is :adjective.'; + $expected = '2 + 2 = 4. Cake is yummy.'; + $result = String::insert($string, array('sum' => '4', 'adjective' => 'yummy')); + $this->assertEquals($expected, $result); + + $string = '2 + 2 = %sum. Cake is %adjective.'; + $result = String::insert($string, array('sum' => '4', 'adjective' => 'yummy'), array('before' => '%')); + $this->assertEquals($expected, $result); + + $string = '2 + 2 = 2sum2. Cake is 9adjective9.'; + $result = String::insert($string, array('sum' => '4', 'adjective' => 'yummy'), array('format' => '/([\d])%s\\1/')); + $this->assertEquals($expected, $result); + + $string = '2 + 2 = 12sum21. Cake is 23adjective45.'; + $expected = '2 + 2 = 4. Cake is 23adjective45.'; + $result = String::insert($string, array('sum' => '4', 'adjective' => 'yummy'), array('format' => '/([\d])([\d])%s\\2\\1/')); + $this->assertEquals($expected, $result); + + $string = ':web :web_site'; + $expected = 'www http'; + $result = String::insert($string, array('web' => 'www', 'web_site' => 'http')); + $this->assertEquals($expected, $result); + + $string = '2 + 2 = .'; + $expected = '2 + 2 = '4', 'adjective' => 'yummy'), array('before' => '<', 'after' => '>')); + $this->assertEquals($expected, $result); + + $string = '2 + 2 = \:sum. Cake is :adjective.'; + $expected = '2 + 2 = :sum. Cake is yummy.'; + $result = String::insert($string, array('sum' => '4', 'adjective' => 'yummy')); + $this->assertEquals($expected, $result); + + $string = '2 + 2 = !:sum. Cake is :adjective.'; + $result = String::insert($string, array('sum' => '4', 'adjective' => 'yummy'), array('escape' => '!')); + $this->assertEquals($expected, $result); + + $string = '2 + 2 = \%sum. Cake is %adjective.'; + $expected = '2 + 2 = %sum. Cake is yummy.'; + $result = String::insert($string, array('sum' => '4', 'adjective' => 'yummy'), array('before' => '%')); + $this->assertEquals($expected, $result); + + $string = ':a :b \:a :a'; + $expected = '1 2 :a 1'; + $result = String::insert($string, array('a' => 1, 'b' => 2)); + $this->assertEquals($expected, $result); + + $string = ':a :b :c'; + $expected = '2 3'; + $result = String::insert($string, array('b' => 2, 'c' => 3), array('clean' => true)); + $this->assertEquals($expected, $result); + + $string = ':a :b :c'; + $expected = '1 3'; + $result = String::insert($string, array('a' => 1, 'c' => 3), array('clean' => true)); + $this->assertEquals($expected, $result); + + $string = ':a :b :c'; + $expected = '2 3'; + $result = String::insert($string, array('b' => 2, 'c' => 3), array('clean' => true)); + $this->assertEquals($expected, $result); + + $string = ':a, :b and :c'; + $expected = '2 and 3'; + $result = String::insert($string, array('b' => 2, 'c' => 3), array('clean' => true)); + $this->assertEquals($expected, $result); + + $string = '":a, :b and :c"'; + $expected = '"1, 2"'; + $result = String::insert($string, array('a' => 1, 'b' => 2), array('clean' => true)); + $this->assertEquals($expected, $result); + + $string = '"${a}, ${b} and ${c}"'; + $expected = '"1, 2"'; + $result = String::insert($string, array('a' => 1, 'b' => 2), array('before' => '${', 'after' => '}', 'clean' => true)); + $this->assertEquals($expected, $result); + + $string = ':alt'; + $expected = ''; + $result = String::insert($string, array('src' => 'foo'), array('clean' => 'html')); + + $this->assertEquals($expected, $result); + + $string = ''; + $expected = ''; + $result = String::insert($string, array('src' => 'foo'), array('clean' => 'html')); + $this->assertEquals($expected, $result); + + $string = ''; + $expected = ''; + $result = String::insert($string, array('src' => 'foo', 'extra' => 'bar'), array('clean' => 'html')); + $this->assertEquals($expected, $result); + + $result = String::insert("this is a ? string", "test"); + $expected = "this is a test string"; + $this->assertEquals($expected, $result); + + $result = String::insert("this is a ? string with a ? ? ?", array('long', 'few?', 'params', 'you know')); + $expected = "this is a long string with a few? params you know"; + $this->assertEquals($expected, $result); + + $result = String::insert('update saved_urls set url = :url where id = :id', array('url' => 'http://www.testurl.com/param1:url/param2:id','id' => 1)); + $expected = "update saved_urls set url = http://www.testurl.com/param1:url/param2:id where id = 1"; + $this->assertEquals($expected, $result); + + $result = String::insert('update saved_urls set url = :url where id = :id', array('id' => 1, 'url' => 'http://www.testurl.com/param1:url/param2:id')); + $expected = "update saved_urls set url = http://www.testurl.com/param1:url/param2:id where id = 1"; + $this->assertEquals($expected, $result); + + $result = String::insert(':me cake. :subject :verb fantastic.', array('me' => 'I :verb', 'subject' => 'cake', 'verb' => 'is')); + $expected = "I :verb cake. cake is fantastic."; + $this->assertEquals($expected, $result); + + $result = String::insert(':I.am: :not.yet: passing.', array('I.am' => 'We are'), array('before' => ':', 'after' => ':', 'clean' => array('replacement' => ' of course', 'method' => 'text'))); + $expected = "We are of course passing."; + $this->assertEquals($expected, $result); + + $result = String::insert( + ':I.am: :not.yet: passing.', + array('I.am' => 'We are'), + array('before' => ':', 'after' => ':', 'clean' => true) + ); + $expected = "We are passing."; + $this->assertEquals($expected, $result); + + $result = String::insert('?-pended result', array('Pre')); + $expected = "Pre-pended result"; + $this->assertEquals($expected, $result); + + $string = 'switching :timeout / :timeout_count'; + $expected = 'switching 5 / 10'; + $result = String::insert($string, array('timeout' => 5, 'timeout_count' => 10)); + $this->assertEquals($expected, $result); + + $string = 'switching :timeout / :timeout_count'; + $expected = 'switching 5 / 10'; + $result = String::insert($string, array('timeout_count' => 10, 'timeout' => 5)); + $this->assertEquals($expected, $result); + + $string = 'switching :timeout_count by :timeout'; + $expected = 'switching 10 by 5'; + $result = String::insert($string, array('timeout' => 5, 'timeout_count' => 10)); + $this->assertEquals($expected, $result); + + $string = 'switching :timeout_count by :timeout'; + $expected = 'switching 10 by 5'; + $result = String::insert($string, array('timeout_count' => 10, 'timeout' => 5)); + $this->assertEquals($expected, $result); + } + +/** + * test Clean Insert + * + * @return void + */ + public function testCleanInsert() { + $result = String::cleanInsert(':incomplete', array( + 'clean' => true, 'before' => ':', 'after' => '' + )); + $this->assertEquals('', $result); + + $result = String::cleanInsert(':incomplete', array( + 'clean' => array('method' => 'text', 'replacement' => 'complete'), + 'before' => ':', 'after' => '') + ); + $this->assertEquals('complete', $result); + + $result = String::cleanInsert(':in.complete', array( + 'clean' => true, 'before' => ':', 'after' => '' + )); + $this->assertEquals('', $result); + + $result = String::cleanInsert(':in.complete and', array( + 'clean' => true, 'before' => ':', 'after' => '') + ); + $this->assertEquals('', $result); + + $result = String::cleanInsert(':in.complete or stuff', array( + 'clean' => true, 'before' => ':', 'after' => '' + )); + $this->assertEquals('stuff', $result); + + $result = String::cleanInsert( + '

Text here

', + array('clean' => 'html', 'before' => ':', 'after' => '') + ); + $this->assertEquals('

Text here

', $result); + } + +/** + * Tests that non-insertable variables (i.e. arrays) are skipped when used as values in + * String::insert(). + * + * @return void + */ + public function testAutoIgnoreBadInsertData() { + $data = array('foo' => 'alpha', 'bar' => 'beta', 'fale' => array()); + $result = String::insert('(:foo > :bar || :fale!)', $data, array('clean' => 'text')); + $this->assertEquals('(alpha > beta || !)', $result); + } + +/** + * testTokenize method + * + * @return void + */ + public function testTokenize() { + $result = String::tokenize('A,(short,boring test)'); + $expected = array('A', '(short,boring test)'); + $this->assertEquals($expected, $result); + + $result = String::tokenize('A,(short,more interesting( test)'); + $expected = array('A', '(short,more interesting( test)'); + $this->assertEquals($expected, $result); + + $result = String::tokenize('A,(short,very interesting( test))'); + $expected = array('A', '(short,very interesting( test))'); + $this->assertEquals($expected, $result); + + $result = String::tokenize('"single tag"', ' ', '"', '"'); + $expected = array('"single tag"'); + $this->assertEquals($expected, $result); + + $result = String::tokenize('tagA "single tag" tagB', ' ', '"', '"'); + $expected = array('tagA', '"single tag"', 'tagB'); + $this->assertEquals($expected, $result); + } + + public function testReplaceWithQuestionMarkInString() { + $string = ':a, :b and :c?'; + $expected = '2 and 3?'; + $result = String::insert($string, array('b' => 2, 'c' => 3), array('clean' => true)); + $this->assertEquals($expected, $result); + } + +/** + * test wrap method. + * + * @return void + */ + public function testWrap() { + $text = 'This is the song that never ends. This is the song that never ends. This is the song that never ends.'; + $result = String::wrap($text, 33); + $expected = <<assertTextEquals($expected, $result, 'Text not wrapped.'); + + $result = String::wrap($text, array('width' => 20, 'wordWrap' => false)); + $expected = <<assertTextEquals($expected, $result, 'Text not wrapped.'); + } + +/** + * test wrap() indenting + * + * @return void + */ + public function testWrapIndent() { + $text = 'This is the song that never ends. This is the song that never ends. This is the song that never ends.'; + $result = String::wrap($text, array('width' => 33, 'indent' => "\t", 'indentAt' => 1)); + $expected = <<assertTextEquals($expected, $result); + } + +/** + * testTruncate method + * + * @return void + */ + public function testTruncate() { + $text1 = 'The quick brown fox jumps over the lazy dog'; + $text2 = 'Heizölrückstoßabdämpfung'; + $text3 = '© 2005-2007, Cake Software Foundation, Inc.
written by Alexander Wegener'; + $text4 = ' This image tag is not XHTML conform!

But the following image tag should be conform Me, myself and I
Great, or?'; + $text5 = '01234567890'; + $text6 = '

Extra dates have been announced for this year\'s tour.

Tickets for the new shows in

'; + $text7 = 'El moño está en el lugar correcto. Eso fue lo que dijo la niña, ¿habrá dicho la verdad?'; + $text8 = 'Vive la R' . chr(195) . chr(169) . 'publique de France'; + $text9 = 'НОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыь'; + $text10 = 'http://example.com/something/foo:bar'; + + $this->assertSame($this->Text->truncate($text1, 15), 'The quick br...'); + $this->assertSame($this->Text->truncate($text1, 15, array('exact' => false)), 'The quick...'); + $this->assertSame($this->Text->truncate($text1, 100), 'The quick brown fox jumps over the lazy dog'); + $this->assertSame($this->Text->truncate($text2, 10), 'Heiz&ou...'); + $this->assertSame($this->Text->truncate($text2, 10, array('exact' => false)), '...'); + $this->assertSame($this->Text->truncate($text3, 20), '© 2005-20...'); + $this->assertSame($this->Text->truncate($text4, 15), ' This image ...'); + $this->assertSame($this->Text->truncate($text4, 45, array('html' => true)), ' This image tag is not XHTML conform!

But t...'); + $this->assertSame($this->Text->truncate($text4, 90, array('html' => true)), ' This image tag is not XHTML conform!

But the following image tag should be conform Me, myself and I
Grea...'); + $this->assertSame($this->Text->truncate($text5, 6, array('ending' => '', 'html' => true)), '012345'); + $this->assertSame($this->Text->truncate($text5, 20, array('ending' => '', 'html' => true)), $text5); + $this->assertSame($this->Text->truncate($text6, 57, array('exact' => false, 'html' => true)), "

Extra dates have been announced for this year's...

"); + $this->assertSame($this->Text->truncate($text7, 255), $text7); + $this->assertSame($this->Text->truncate($text7, 15), 'El moño está...'); + $this->assertSame($this->Text->truncate($text8, 15), 'Vive la R' . chr(195) . chr(169) . 'pu...'); + $this->assertSame($this->Text->truncate($text9, 10), 'НОПРСТУ...'); + $this->assertSame($this->Text->truncate($text10, 30), 'http://example.com/somethin...'); + + $text = '

Iamatestwithnospacesandhtml

'; + $result = $this->Text->truncate($text, 10, array( + 'ending' => '...', + 'exact' => false, + 'html' => true + )); + $expected = '

...

'; + $this->assertEquals($expected, $result); + + $text = '

El biógrafo de Steve Jobs, Walter +Isaacson, explica porqué Jobs le pidió que le hiciera su biografía en +este artículo de El País.

+

Por qué Steve era distinto.

+

http://www.elpais.com/articulo/primer/plano/ +Steve/era/distinto/elpepueconeg/20111009elpneglse_4/Tes

+

Ya se ha publicado la biografía de +Steve Jobs escrita por Walter Isaacson "Steve Jobs by Walter +Isaacson", aquí os dejamos la dirección de amazon donde +podeís adquirirla.

+

http://www.amazon.com/Steve- +Jobs-Walter-Isaacson/dp/1451648537

'; + $result = $this->Text->truncate($text, 500, array( + 'ending' => '... ', + 'exact' => false, + 'html' => true + )); + $expected = '

El biógrafo de Steve Jobs, Walter +Isaacson, explica porqué Jobs le pidió que le hiciera su biografía en +este artículo de El País.

+

Por qué Steve era distinto.

+

http://www.elpais.com/articulo/primer/plano/ +Steve/era/distinto/elpepueconeg/20111009elpneglse_4/Tes

+

Ya se ha publicado la biografía de +Steve Jobs escrita por Walter Isaacson "Steve Jobs by Walter +Isaacson", aquí os dejamos la dirección de amazon donde +podeís adquirirla.

+

...

'; + $this->assertEquals($expected, $result); + } + +/** + * testHighlight method + * + * @return void + */ + public function testHighlight() { + $text = 'This is a test text'; + $phrases = array('This', 'text'); + $result = $this->Text->highlight($text, $phrases, array('format' => '\1')); + $expected = 'This is a test text'; + $this->assertEquals($expected, $result); + + $phrases = array('is', 'text'); + $result = $this->Text->highlight($text, $phrases, array('format' => '\1', 'regex' => "|\b%s\b|iu")); + $expected = 'This is a test text'; + $this->assertEquals($expected, $result); + + $text = 'This is a test text'; + $phrases = null; + $result = $this->Text->highlight($text, $phrases, array('format' => '\1')); + $this->assertEquals($text, $result); + + $text = 'This is a (test) text'; + $phrases = '(test'; + $result = $this->Text->highlight($text, $phrases, array('format' => '\1')); + $this->assertEquals('This is a (test) text', $result); + + $text = 'Ich saß in einem Café am Übergang'; + $expected = 'Ich saß in einem Café am Übergang'; + $phrases = array('saß', 'café', 'übergang'); + $result = $this->Text->highlight($text, $phrases, array('format' => '\1')); + $this->assertEquals($expected, $result); + } + +/** + * testHighlightHtml method + * + * @return void + */ + public function testHighlightHtml() { + $text1 = '

strongbow isn’t real cider

'; + $text2 = '

strongbow isn’t real cider

'; + $text3 = 'What a strong mouse!'; + $text4 = 'What a strong mouse: What a strong mouse!'; + $options = array('format' => '\1', 'html' => true); + + $expected = '

strongbow isn’t real cider

'; + $this->assertEquals($expected, $this->Text->highlight($text1, 'strong', $options)); + + $expected = '

strongbow isn’t real cider

'; + $this->assertEquals($expected, $this->Text->highlight($text2, 'strong', $options)); + + $this->assertEquals($this->Text->highlight($text3, 'strong', $options), $text3); + + $this->assertEquals($this->Text->highlight($text3, array('strong', 'what'), $options), $text3); + + $expected = 'What a strong mouse: What a strong mouse!'; + $this->assertEquals($this->Text->highlight($text4, array('strong', 'what'), $options), $expected); + } + +/** + * testHighlightMulti method + * + * @return void + */ + public function testHighlightMulti() { + $text = 'This is a test text'; + $phrases = array('This', 'text'); + $result = $this->Text->highlight($text, $phrases, array('format' => array('\1', '\1'))); + $expected = 'This is a test text'; + $this->assertEquals($expected, $result); + } + +/** + * testStripLinks method + * + * @return void + */ + public function testStripLinks() { + $text = 'This is a test text'; + $expected = 'This is a test text'; + $result = $this->Text->stripLinks($text); + $this->assertEquals($expected, $result); + + $text = 'This is a test text'; + $expected = 'This is a test text'; + $result = $this->Text->stripLinks($text); + $this->assertEquals($expected, $result); + + $text = 'This is a test text'; + $expected = 'This is a test text'; + $result = $this->Text->stripLinks($text); + $this->assertEquals($expected, $result); + + $text = 'This is a test and some other text'; + $expected = 'This is a test and some other text'; + $result = $this->Text->stripLinks($text); + $this->assertEquals($expected, $result); + } + +/** + * testHighlightCaseInsensitivity method + * + * @return void + */ + public function testHighlightCaseInsensitivity() { + $text = 'This is a Test text'; + $expected = 'This is a Test text'; + + $result = $this->Text->highlight($text, 'test', array('format' => '\1')); + $this->assertEquals($expected, $result); + + $result = $this->Text->highlight($text, array('test'), array('format' => '\1')); + $this->assertEquals($expected, $result); + } + +/** + * testExcerpt method + * + * @return void + */ + public function testExcerpt() { + $text = 'This is a phrase with test text to play with'; + + $expected = '...ase with test text to ...'; + $result = $this->Text->excerpt($text, 'test', 9, '...'); + $this->assertEquals($expected, $result); + + $expected = 'This is a...'; + $result = $this->Text->excerpt($text, 'not_found', 9, '...'); + $this->assertEquals($expected, $result); + + $expected = 'This is a phras...'; + $result = $this->Text->excerpt($text, null, 9, '...'); + $this->assertEquals($expected, $result); + + $expected = $text; + $result = $this->Text->excerpt($text, null, 200, '...'); + $this->assertEquals($expected, $result); + + $expected = '...a phrase w...'; + $result = $this->Text->excerpt($text, 'phrase', 2, '...'); + $this->assertEquals($expected, $result); + + $phrase = 'This is a phrase with test text'; + $expected = $text; + $result = $this->Text->excerpt($text, $phrase, 13, '...'); + $this->assertEquals($expected, $result); + + $text = 'aaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbaaaaaaaaaaaaaaaaaaaaaaaa'; + $phrase = 'bbbbbbbb'; + $result = $this->Text->excerpt($text, $phrase, 10); + $expected = '...aaaaaaaaaabbbbbbbbaaaaaaaaaa...'; + $this->assertEquals($expected, $result); + } + +/** + * testExcerptCaseInsensitivity method + * + * @return void + */ + public function testExcerptCaseInsensitivity() { + $text = 'This is a phrase with test text to play with'; + + $expected = '...ase with test text to ...'; + $result = $this->Text->excerpt($text, 'TEST', 9, '...'); + $this->assertEquals($expected, $result); + + $expected = 'This is a...'; + $result = $this->Text->excerpt($text, 'NOT_FOUND', 9, '...'); + $this->assertEquals($expected, $result); + } + +/** + * testListGeneration method + * + * @return void + */ + public function testListGeneration() { + $result = $this->Text->toList(array()); + $this->assertEquals('', $result); + + $result = $this->Text->toList(array('One')); + $this->assertEquals('One', $result); + + $result = $this->Text->toList(array('Larry', 'Curly', 'Moe')); + $this->assertEquals('Larry, Curly and Moe', $result); + + $result = $this->Text->toList(array('Dusty', 'Lucky', 'Ned'), 'y'); + $this->assertEquals('Dusty, Lucky y Ned', $result); + + $result = $this->Text->toList(array(1 => 'Dusty', 2 => 'Lucky', 3 => 'Ned'), 'y'); + $this->assertEquals('Dusty, Lucky y Ned', $result); + + $result = $this->Text->toList(array(1 => 'Dusty', 2 => 'Lucky', 3 => 'Ned'), 'and', ' + '); + $this->assertEquals('Dusty + Lucky and Ned', $result); + + $result = $this->Text->toList(array('name1' => 'Dusty', 'name2' => 'Lucky')); + $this->assertEquals('Dusty and Lucky', $result); + + $result = $this->Text->toList(array('test_0' => 'banana', 'test_1' => 'apple', 'test_2' => 'lemon')); + $this->assertEquals('banana, apple and lemon', $result); + } + +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Utility/ValidationTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Utility/ValidationTest.php new file mode 100644 index 0000000..a3f98f9 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Utility/ValidationTest.php @@ -0,0 +1,2217 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The Open Group Test Suite License + * Redistributions of files must retain the above copyright notice. + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Utility + * @since CakePHP(tm) v 1.2.0.4206 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ +App::uses('Validation', 'Utility'); + +/** + * CustomValidator class + * + * @package Cake.Test.Case.Utility + */ +class CustomValidator { + +/** + * Makes sure that a given $email address is valid and unique + * + * @param string $email + * @return boolean + */ + public static function customValidate($check) { + return (bool)preg_match('/^[0-9]{3}$/', $check); + } + +} + +/** + * TestNlValidation class + * + * Used to test pass through of Validation + * + * @package Cake.Test.Case.Utility + */ +class TestNlValidation { + +/** + * postal function, for testing postal pass through. + * + * @param string $check + * @return void + */ + public static function postal($check) { + return true; + } + +/** + * ssn function for testing ssn pass through + * + * @return void + */ + public static function ssn($check) { + return true; + } + +} + +/** + * TestDeValidation class + * + * Used to test pass through of Validation + * + * @package Cake.Test.Case.Utility + */ +class TestDeValidation { + +/** + * phone function, for testing phone pass through. + * + * @param string $check + * @return void + */ + public static function phone($check) { + return true; + } + +} + +/** + * Test Case for Validation Class + * + * @package Cake.Test.Case.Utility + */ +class ValidationTest extends CakeTestCase { + +/** + * setUp method + * + * @return void + */ + public function setUp() { + parent::setUp(); + $this->_appEncoding = Configure::read('App.encoding'); + $this->_appLocale = array(); + foreach (array(LC_MONETARY, LC_NUMERIC, LC_TIME) as $category) { + $this->_appLocale[$category] = setlocale($category, 0); + setlocale($category, 'en_US'); + } + } + +/** + * tearDown method + * + * @return void + */ + public function tearDown() { + parent::tearDown(); + Configure::write('App.encoding', $this->_appEncoding); + foreach ($this->_appLocale as $category => $locale) { + setlocale($category, $locale); + } + } + +/** + * testNotEmpty method + * + * @return void + */ + public function testNotEmpty() { + $this->assertTrue(Validation::notEmpty('abcdefg')); + $this->assertTrue(Validation::notEmpty('fasdf ')); + $this->assertTrue(Validation::notEmpty('fooo' . chr(243) . 'blabla')); + $this->assertTrue(Validation::notEmpty('abçďĕʑʘπй')); + $this->assertTrue(Validation::notEmpty('José')); + $this->assertTrue(Validation::notEmpty('é')); + $this->assertTrue(Validation::notEmpty('π')); + $this->assertFalse(Validation::notEmpty("\t ")); + $this->assertFalse(Validation::notEmpty("")); + } + +/** + * testNotEmptyISO88591Encoding method + * + * @return void + */ + public function testNotEmptyISO88591AppEncoding() { + Configure::write('App.encoding', 'ISO-8859-1'); + $this->assertTrue(Validation::notEmpty('abcdefg')); + $this->assertTrue(Validation::notEmpty('fasdf ')); + $this->assertTrue(Validation::notEmpty('fooo' . chr(243) . 'blabla')); + $this->assertTrue(Validation::notEmpty('abçďĕʑʘπй')); + $this->assertTrue(Validation::notEmpty('José')); + $this->assertTrue(Validation::notEmpty(utf8_decode('José'))); + $this->assertFalse(Validation::notEmpty("\t ")); + $this->assertFalse(Validation::notEmpty("")); + } + +/** + * testAlphaNumeric method + * + * @return void + */ + public function testAlphaNumeric() { + $this->assertTrue(Validation::alphaNumeric('frferrf')); + $this->assertTrue(Validation::alphaNumeric('12234')); + $this->assertTrue(Validation::alphaNumeric('1w2e2r3t4y')); + $this->assertTrue(Validation::alphaNumeric('0')); + $this->assertTrue(Validation::alphaNumeric('abçďĕʑʘπй')); + $this->assertTrue(Validation::alphaNumeric('ˇˆๆゞ')); + $this->assertTrue(Validation::alphaNumeric('אกあアꀀ豈')); + $this->assertTrue(Validation::alphaNumeric('Džᾈᾨ')); + $this->assertTrue(Validation::alphaNumeric('ÆΔΩЖÇ')); + + $this->assertFalse(Validation::alphaNumeric('12 234')); + $this->assertFalse(Validation::alphaNumeric('dfd 234')); + $this->assertFalse(Validation::alphaNumeric("\n")); + $this->assertFalse(Validation::alphaNumeric("\t")); + $this->assertFalse(Validation::alphaNumeric("\r")); + $this->assertFalse(Validation::alphaNumeric(' ')); + $this->assertFalse(Validation::alphaNumeric('')); + } + +/** + * testAlphaNumericPassedAsArray method + * + * @return void + */ + public function testAlphaNumericPassedAsArray() { + $this->assertTrue(Validation::alphaNumeric(array('check' => 'frferrf'))); + $this->assertTrue(Validation::alphaNumeric(array('check' => '12234'))); + $this->assertTrue(Validation::alphaNumeric(array('check' => '1w2e2r3t4y'))); + $this->assertTrue(Validation::alphaNumeric(array('check' => '0'))); + $this->assertFalse(Validation::alphaNumeric(array('check' => '12 234'))); + $this->assertFalse(Validation::alphaNumeric(array('check' => 'dfd 234'))); + $this->assertFalse(Validation::alphaNumeric(array('check' => "\n"))); + $this->assertFalse(Validation::alphaNumeric(array('check' => "\t"))); + $this->assertFalse(Validation::alphaNumeric(array('check' => "\r"))); + $this->assertFalse(Validation::alphaNumeric(array('check' => ' '))); + $this->assertFalse(Validation::alphaNumeric(array('check' => ''))); + } + +/** + * testBetween method + * + * @return void + */ + public function testBetween() { + $this->assertTrue(Validation::between('abcdefg', 1, 7)); + $this->assertTrue(Validation::between('', 0, 7)); + $this->assertTrue(Validation::between('אกあアꀀ豈', 1, 7)); + + $this->assertFalse(Validation::between('abcdefg', 1, 6)); + $this->assertFalse(Validation::between('ÆΔΩЖÇ', 1, 3)); + } + +/** + * testBlank method + * + * @return void + */ + public function testBlank() { + $this->assertTrue(Validation::blank('')); + $this->assertTrue(Validation::blank(' ')); + $this->assertTrue(Validation::blank("\n")); + $this->assertTrue(Validation::blank("\t")); + $this->assertTrue(Validation::blank("\r")); + $this->assertFalse(Validation::blank(' Blank')); + $this->assertFalse(Validation::blank('Blank')); + } + +/** + * testBlankAsArray method + * + * @return void + */ + public function testBlankAsArray() { + $this->assertTrue(Validation::blank(array('check' => ''))); + $this->assertTrue(Validation::blank(array('check' => ' '))); + $this->assertTrue(Validation::blank(array('check' => "\n"))); + $this->assertTrue(Validation::blank(array('check' => "\t"))); + $this->assertTrue(Validation::blank(array('check' => "\r"))); + $this->assertFalse(Validation::blank(array('check' => ' Blank'))); + $this->assertFalse(Validation::blank(array('check' => 'Blank'))); + } + +/** + * testcc method + * + * @return void + */ + public function testCc() { + //American Express + $this->assertTrue(Validation::cc('370482756063980', array('amex'))); + $this->assertTrue(Validation::cc('349106433773483', array('amex'))); + $this->assertTrue(Validation::cc('344671486204764', array('amex'))); + $this->assertTrue(Validation::cc('344042544509943', array('amex'))); + $this->assertTrue(Validation::cc('377147515754475', array('amex'))); + $this->assertTrue(Validation::cc('375239372816422', array('amex'))); + $this->assertTrue(Validation::cc('376294341957707', array('amex'))); + $this->assertTrue(Validation::cc('341779292230411', array('amex'))); + $this->assertTrue(Validation::cc('341646919853372', array('amex'))); + $this->assertTrue(Validation::cc('348498616319346', array('amex'))); + //BankCard + $this->assertTrue(Validation::cc('5610745867413420', array('bankcard'))); + $this->assertTrue(Validation::cc('5610376649499352', array('bankcard'))); + $this->assertTrue(Validation::cc('5610091936000694', array('bankcard'))); + $this->assertTrue(Validation::cc('5602248780118788', array('bankcard'))); + $this->assertTrue(Validation::cc('5610631567676765', array('bankcard'))); + $this->assertTrue(Validation::cc('5602238211270795', array('bankcard'))); + $this->assertTrue(Validation::cc('5610173951215470', array('bankcard'))); + $this->assertTrue(Validation::cc('5610139705753702', array('bankcard'))); + $this->assertTrue(Validation::cc('5602226032150551', array('bankcard'))); + $this->assertTrue(Validation::cc('5602223993735777', array('bankcard'))); + //Diners Club 14 + $this->assertTrue(Validation::cc('30155483651028', array('diners'))); + $this->assertTrue(Validation::cc('36371312803821', array('diners'))); + $this->assertTrue(Validation::cc('38801277489875', array('diners'))); + $this->assertTrue(Validation::cc('30348560464296', array('diners'))); + $this->assertTrue(Validation::cc('30349040317708', array('diners'))); + $this->assertTrue(Validation::cc('36567413559978', array('diners'))); + $this->assertTrue(Validation::cc('36051554732702', array('diners'))); + $this->assertTrue(Validation::cc('30391842198191', array('diners'))); + $this->assertTrue(Validation::cc('30172682197745', array('diners'))); + $this->assertTrue(Validation::cc('30162056566641', array('diners'))); + $this->assertTrue(Validation::cc('30085066927745', array('diners'))); + $this->assertTrue(Validation::cc('36519025221976', array('diners'))); + $this->assertTrue(Validation::cc('30372679371044', array('diners'))); + $this->assertTrue(Validation::cc('38913939150124', array('diners'))); + $this->assertTrue(Validation::cc('36852899094637', array('diners'))); + $this->assertTrue(Validation::cc('30138041971120', array('diners'))); + $this->assertTrue(Validation::cc('36184047836838', array('diners'))); + $this->assertTrue(Validation::cc('30057460264462', array('diners'))); + $this->assertTrue(Validation::cc('38980165212050', array('diners'))); + $this->assertTrue(Validation::cc('30356516881240', array('diners'))); + $this->assertTrue(Validation::cc('38744810033182', array('diners'))); + $this->assertTrue(Validation::cc('30173638706621', array('diners'))); + $this->assertTrue(Validation::cc('30158334709185', array('diners'))); + $this->assertTrue(Validation::cc('30195413721186', array('diners'))); + $this->assertTrue(Validation::cc('38863347694793', array('diners'))); + $this->assertTrue(Validation::cc('30275627009113', array('diners'))); + $this->assertTrue(Validation::cc('30242860404971', array('diners'))); + $this->assertTrue(Validation::cc('30081877595151', array('diners'))); + $this->assertTrue(Validation::cc('38053196067461', array('diners'))); + $this->assertTrue(Validation::cc('36520379984870', array('diners'))); + //2004 MasterCard/Diners Club Alliance International 14 + $this->assertTrue(Validation::cc('36747701998969', array('diners'))); + $this->assertTrue(Validation::cc('36427861123159', array('diners'))); + $this->assertTrue(Validation::cc('36150537602386', array('diners'))); + $this->assertTrue(Validation::cc('36582388820610', array('diners'))); + $this->assertTrue(Validation::cc('36729045250216', array('diners'))); + //2004 MasterCard/Diners Club Alliance US & Canada 16 + $this->assertTrue(Validation::cc('5597511346169950', array('diners'))); + $this->assertTrue(Validation::cc('5526443162217562', array('diners'))); + $this->assertTrue(Validation::cc('5577265786122391', array('diners'))); + $this->assertTrue(Validation::cc('5534061404676989', array('diners'))); + $this->assertTrue(Validation::cc('5545313588374502', array('diners'))); + //Discover + $this->assertTrue(Validation::cc('6011802876467237', array('disc'))); + $this->assertTrue(Validation::cc('6506432777720955', array('disc'))); + $this->assertTrue(Validation::cc('6011126265283942', array('disc'))); + $this->assertTrue(Validation::cc('6502187151579252', array('disc'))); + $this->assertTrue(Validation::cc('6506600836002298', array('disc'))); + $this->assertTrue(Validation::cc('6504376463615189', array('disc'))); + $this->assertTrue(Validation::cc('6011440907005377', array('disc'))); + $this->assertTrue(Validation::cc('6509735979634270', array('disc'))); + $this->assertTrue(Validation::cc('6011422366775856', array('disc'))); + $this->assertTrue(Validation::cc('6500976374623323', array('disc'))); + //enRoute + $this->assertTrue(Validation::cc('201496944158937', array('enroute'))); + $this->assertTrue(Validation::cc('214945833739665', array('enroute'))); + $this->assertTrue(Validation::cc('214982692491187', array('enroute'))); + $this->assertTrue(Validation::cc('214901395949424', array('enroute'))); + $this->assertTrue(Validation::cc('201480676269187', array('enroute'))); + $this->assertTrue(Validation::cc('214911922887807', array('enroute'))); + $this->assertTrue(Validation::cc('201485025457250', array('enroute'))); + $this->assertTrue(Validation::cc('201402662758866', array('enroute'))); + $this->assertTrue(Validation::cc('214981579370225', array('enroute'))); + $this->assertTrue(Validation::cc('201447595859877', array('enroute'))); + //JCB 15 digit + $this->assertTrue(Validation::cc('210034762247893', array('jcb'))); + $this->assertTrue(Validation::cc('180078671678892', array('jcb'))); + $this->assertTrue(Validation::cc('180010559353736', array('jcb'))); + $this->assertTrue(Validation::cc('210095474464258', array('jcb'))); + $this->assertTrue(Validation::cc('210006675562188', array('jcb'))); + $this->assertTrue(Validation::cc('210063299662662', array('jcb'))); + $this->assertTrue(Validation::cc('180032506857825', array('jcb'))); + $this->assertTrue(Validation::cc('210057919192738', array('jcb'))); + $this->assertTrue(Validation::cc('180031358949367', array('jcb'))); + $this->assertTrue(Validation::cc('180033802147846', array('jcb'))); + //JCB 16 digit + $this->assertTrue(Validation::cc('3096806857839939', array('jcb'))); + $this->assertTrue(Validation::cc('3158699503187091', array('jcb'))); + $this->assertTrue(Validation::cc('3112549607186579', array('jcb'))); + $this->assertTrue(Validation::cc('3112332922425604', array('jcb'))); + $this->assertTrue(Validation::cc('3112001541159239', array('jcb'))); + $this->assertTrue(Validation::cc('3112162495317841', array('jcb'))); + $this->assertTrue(Validation::cc('3337562627732768', array('jcb'))); + $this->assertTrue(Validation::cc('3337107161330775', array('jcb'))); + $this->assertTrue(Validation::cc('3528053736003621', array('jcb'))); + $this->assertTrue(Validation::cc('3528915255020360', array('jcb'))); + $this->assertTrue(Validation::cc('3096786059660921', array('jcb'))); + $this->assertTrue(Validation::cc('3528264799292320', array('jcb'))); + $this->assertTrue(Validation::cc('3096469164130136', array('jcb'))); + $this->assertTrue(Validation::cc('3112127443822853', array('jcb'))); + $this->assertTrue(Validation::cc('3096849995802328', array('jcb'))); + $this->assertTrue(Validation::cc('3528090735127407', array('jcb'))); + $this->assertTrue(Validation::cc('3112101006819234', array('jcb'))); + $this->assertTrue(Validation::cc('3337444428040784', array('jcb'))); + $this->assertTrue(Validation::cc('3088043154151061', array('jcb'))); + $this->assertTrue(Validation::cc('3088295969414866', array('jcb'))); + $this->assertTrue(Validation::cc('3158748843158575', array('jcb'))); + $this->assertTrue(Validation::cc('3158709206148538', array('jcb'))); + $this->assertTrue(Validation::cc('3158365159575324', array('jcb'))); + $this->assertTrue(Validation::cc('3158671691305165', array('jcb'))); + $this->assertTrue(Validation::cc('3528523028771093', array('jcb'))); + $this->assertTrue(Validation::cc('3096057126267870', array('jcb'))); + $this->assertTrue(Validation::cc('3158514047166834', array('jcb'))); + $this->assertTrue(Validation::cc('3528274546125962', array('jcb'))); + $this->assertTrue(Validation::cc('3528890967705733', array('jcb'))); + $this->assertTrue(Validation::cc('3337198811307545', array('jcb'))); + //Maestro (debit card) + $this->assertTrue(Validation::cc('5020147409985219', array('maestro'))); + $this->assertTrue(Validation::cc('5020931809905616', array('maestro'))); + $this->assertTrue(Validation::cc('5020412965470224', array('maestro'))); + $this->assertTrue(Validation::cc('5020129740944022', array('maestro'))); + $this->assertTrue(Validation::cc('5020024696747943', array('maestro'))); + $this->assertTrue(Validation::cc('5020581514636509', array('maestro'))); + $this->assertTrue(Validation::cc('5020695008411987', array('maestro'))); + $this->assertTrue(Validation::cc('5020565359718977', array('maestro'))); + $this->assertTrue(Validation::cc('6339931536544062', array('maestro'))); + $this->assertTrue(Validation::cc('6465028615704406', array('maestro'))); + //Mastercard + $this->assertTrue(Validation::cc('5580424361774366', array('mc'))); + $this->assertTrue(Validation::cc('5589563059318282', array('mc'))); + $this->assertTrue(Validation::cc('5387558333690047', array('mc'))); + $this->assertTrue(Validation::cc('5163919215247175', array('mc'))); + $this->assertTrue(Validation::cc('5386742685055055', array('mc'))); + $this->assertTrue(Validation::cc('5102303335960674', array('mc'))); + $this->assertTrue(Validation::cc('5526543403964565', array('mc'))); + $this->assertTrue(Validation::cc('5538725892618432', array('mc'))); + $this->assertTrue(Validation::cc('5119543573129778', array('mc'))); + $this->assertTrue(Validation::cc('5391174753915767', array('mc'))); + $this->assertTrue(Validation::cc('5510994113980714', array('mc'))); + $this->assertTrue(Validation::cc('5183720260418091', array('mc'))); + $this->assertTrue(Validation::cc('5488082196086704', array('mc'))); + $this->assertTrue(Validation::cc('5484645164161834', array('mc'))); + $this->assertTrue(Validation::cc('5171254350337031', array('mc'))); + $this->assertTrue(Validation::cc('5526987528136452', array('mc'))); + $this->assertTrue(Validation::cc('5504148941409358', array('mc'))); + $this->assertTrue(Validation::cc('5240793507243615', array('mc'))); + $this->assertTrue(Validation::cc('5162114693017107', array('mc'))); + $this->assertTrue(Validation::cc('5163104807404753', array('mc'))); + $this->assertTrue(Validation::cc('5590136167248365', array('mc'))); + $this->assertTrue(Validation::cc('5565816281038948', array('mc'))); + $this->assertTrue(Validation::cc('5467639122779531', array('mc'))); + $this->assertTrue(Validation::cc('5297350261550024', array('mc'))); + $this->assertTrue(Validation::cc('5162739131368058', array('mc'))); + //Solo 16 + $this->assertTrue(Validation::cc('6767432107064987', array('solo'))); + $this->assertTrue(Validation::cc('6334667758225411', array('solo'))); + $this->assertTrue(Validation::cc('6767037421954068', array('solo'))); + $this->assertTrue(Validation::cc('6767823306394854', array('solo'))); + $this->assertTrue(Validation::cc('6334768185398134', array('solo'))); + $this->assertTrue(Validation::cc('6767286729498589', array('solo'))); + $this->assertTrue(Validation::cc('6334972104431261', array('solo'))); + $this->assertTrue(Validation::cc('6334843427400616', array('solo'))); + $this->assertTrue(Validation::cc('6767493947881311', array('solo'))); + $this->assertTrue(Validation::cc('6767194235798817', array('solo'))); + //Solo 18 + $this->assertTrue(Validation::cc('676714834398858593', array('solo'))); + $this->assertTrue(Validation::cc('676751666435130857', array('solo'))); + $this->assertTrue(Validation::cc('676781908573924236', array('solo'))); + $this->assertTrue(Validation::cc('633488724644003240', array('solo'))); + $this->assertTrue(Validation::cc('676732252338067316', array('solo'))); + $this->assertTrue(Validation::cc('676747520084495821', array('solo'))); + $this->assertTrue(Validation::cc('633465488901381957', array('solo'))); + $this->assertTrue(Validation::cc('633487484858610484', array('solo'))); + $this->assertTrue(Validation::cc('633453764680740694', array('solo'))); + $this->assertTrue(Validation::cc('676768613295414451', array('solo'))); + //Solo 19 + $this->assertTrue(Validation::cc('6767838565218340113', array('solo'))); + $this->assertTrue(Validation::cc('6767760119829705181', array('solo'))); + $this->assertTrue(Validation::cc('6767265917091593668', array('solo'))); + $this->assertTrue(Validation::cc('6767938856947440111', array('solo'))); + $this->assertTrue(Validation::cc('6767501945697390076', array('solo'))); + $this->assertTrue(Validation::cc('6334902868716257379', array('solo'))); + $this->assertTrue(Validation::cc('6334922127686425532', array('solo'))); + $this->assertTrue(Validation::cc('6334933119080706440', array('solo'))); + $this->assertTrue(Validation::cc('6334647959628261714', array('solo'))); + $this->assertTrue(Validation::cc('6334527312384101382', array('solo'))); + //Switch 16 + $this->assertTrue(Validation::cc('5641829171515733', array('switch'))); + $this->assertTrue(Validation::cc('5641824852820809', array('switch'))); + $this->assertTrue(Validation::cc('6759129648956909', array('switch'))); + $this->assertTrue(Validation::cc('6759626072268156', array('switch'))); + $this->assertTrue(Validation::cc('5641822698388957', array('switch'))); + $this->assertTrue(Validation::cc('5641827123105470', array('switch'))); + $this->assertTrue(Validation::cc('5641823755819553', array('switch'))); + $this->assertTrue(Validation::cc('5641821939587682', array('switch'))); + $this->assertTrue(Validation::cc('4936097148079186', array('switch'))); + $this->assertTrue(Validation::cc('5641829739125009', array('switch'))); + $this->assertTrue(Validation::cc('5641822860725507', array('switch'))); + $this->assertTrue(Validation::cc('4936717688865831', array('switch'))); + $this->assertTrue(Validation::cc('6759487613615441', array('switch'))); + $this->assertTrue(Validation::cc('5641821346840617', array('switch'))); + $this->assertTrue(Validation::cc('5641825793417126', array('switch'))); + $this->assertTrue(Validation::cc('5641821302759595', array('switch'))); + $this->assertTrue(Validation::cc('6759784969918837', array('switch'))); + $this->assertTrue(Validation::cc('5641824910667036', array('switch'))); + $this->assertTrue(Validation::cc('6759139909636173', array('switch'))); + $this->assertTrue(Validation::cc('6333425070638022', array('switch'))); + $this->assertTrue(Validation::cc('5641823910382067', array('switch'))); + $this->assertTrue(Validation::cc('4936295218139423', array('switch'))); + $this->assertTrue(Validation::cc('6333031811316199', array('switch'))); + $this->assertTrue(Validation::cc('4936912044763198', array('switch'))); + $this->assertTrue(Validation::cc('4936387053303824', array('switch'))); + $this->assertTrue(Validation::cc('6759535838760523', array('switch'))); + $this->assertTrue(Validation::cc('6333427174594051', array('switch'))); + $this->assertTrue(Validation::cc('5641829037102700', array('switch'))); + $this->assertTrue(Validation::cc('5641826495463046', array('switch'))); + $this->assertTrue(Validation::cc('6333480852979946', array('switch'))); + $this->assertTrue(Validation::cc('5641827761302876', array('switch'))); + $this->assertTrue(Validation::cc('5641825083505317', array('switch'))); + $this->assertTrue(Validation::cc('6759298096003991', array('switch'))); + $this->assertTrue(Validation::cc('4936119165483420', array('switch'))); + $this->assertTrue(Validation::cc('4936190990500993', array('switch'))); + $this->assertTrue(Validation::cc('4903356467384927', array('switch'))); + $this->assertTrue(Validation::cc('6333372765092554', array('switch'))); + $this->assertTrue(Validation::cc('5641821330950570', array('switch'))); + $this->assertTrue(Validation::cc('6759841558826118', array('switch'))); + $this->assertTrue(Validation::cc('4936164540922452', array('switch'))); + //Switch 18 + $this->assertTrue(Validation::cc('493622764224625174', array('switch'))); + $this->assertTrue(Validation::cc('564182823396913535', array('switch'))); + $this->assertTrue(Validation::cc('675917308304801234', array('switch'))); + $this->assertTrue(Validation::cc('675919890024220298', array('switch'))); + $this->assertTrue(Validation::cc('633308376862556751', array('switch'))); + $this->assertTrue(Validation::cc('564182377633208779', array('switch'))); + $this->assertTrue(Validation::cc('564182870014926787', array('switch'))); + $this->assertTrue(Validation::cc('675979788553829819', array('switch'))); + $this->assertTrue(Validation::cc('493668394358130935', array('switch'))); + $this->assertTrue(Validation::cc('493637431790930965', array('switch'))); + $this->assertTrue(Validation::cc('633321438601941513', array('switch'))); + $this->assertTrue(Validation::cc('675913800898840986', array('switch'))); + $this->assertTrue(Validation::cc('564182592016841547', array('switch'))); + $this->assertTrue(Validation::cc('564182428380440899', array('switch'))); + $this->assertTrue(Validation::cc('493696376827623463', array('switch'))); + $this->assertTrue(Validation::cc('675977939286485757', array('switch'))); + $this->assertTrue(Validation::cc('490302699502091579', array('switch'))); + $this->assertTrue(Validation::cc('564182085013662230', array('switch'))); + $this->assertTrue(Validation::cc('493693054263310167', array('switch'))); + $this->assertTrue(Validation::cc('633321755966697525', array('switch'))); + $this->assertTrue(Validation::cc('675996851719732811', array('switch'))); + $this->assertTrue(Validation::cc('493699211208281028', array('switch'))); + $this->assertTrue(Validation::cc('493697817378356614', array('switch'))); + $this->assertTrue(Validation::cc('675968224161768150', array('switch'))); + $this->assertTrue(Validation::cc('493669416873337627', array('switch'))); + $this->assertTrue(Validation::cc('564182439172549714', array('switch'))); + $this->assertTrue(Validation::cc('675926914467673598', array('switch'))); + $this->assertTrue(Validation::cc('564182565231977809', array('switch'))); + $this->assertTrue(Validation::cc('675966282607849002', array('switch'))); + $this->assertTrue(Validation::cc('493691609704348548', array('switch'))); + $this->assertTrue(Validation::cc('675933118546065120', array('switch'))); + $this->assertTrue(Validation::cc('493631116677238592', array('switch'))); + $this->assertTrue(Validation::cc('675921142812825938', array('switch'))); + $this->assertTrue(Validation::cc('633338311815675113', array('switch'))); + $this->assertTrue(Validation::cc('633323539867338621', array('switch'))); + $this->assertTrue(Validation::cc('675964912740845663', array('switch'))); + $this->assertTrue(Validation::cc('633334008833727504', array('switch'))); + $this->assertTrue(Validation::cc('493631941273687169', array('switch'))); + $this->assertTrue(Validation::cc('564182971729706785', array('switch'))); + $this->assertTrue(Validation::cc('633303461188963496', array('switch'))); + //Switch 19 + $this->assertTrue(Validation::cc('6759603460617628716', array('switch'))); + $this->assertTrue(Validation::cc('4936705825268647681', array('switch'))); + $this->assertTrue(Validation::cc('5641829846600479183', array('switch'))); + $this->assertTrue(Validation::cc('6759389846573792530', array('switch'))); + $this->assertTrue(Validation::cc('4936189558712637603', array('switch'))); + $this->assertTrue(Validation::cc('5641822217393868189', array('switch'))); + $this->assertTrue(Validation::cc('4903075563780057152', array('switch'))); + $this->assertTrue(Validation::cc('4936510653566569547', array('switch'))); + $this->assertTrue(Validation::cc('4936503083627303364', array('switch'))); + $this->assertTrue(Validation::cc('4936777334398116272', array('switch'))); + $this->assertTrue(Validation::cc('5641823876900554860', array('switch'))); + $this->assertTrue(Validation::cc('6759619236903407276', array('switch'))); + $this->assertTrue(Validation::cc('6759011470269978117', array('switch'))); + $this->assertTrue(Validation::cc('6333175833997062502', array('switch'))); + $this->assertTrue(Validation::cc('6759498728789080439', array('switch'))); + $this->assertTrue(Validation::cc('4903020404168157841', array('switch'))); + $this->assertTrue(Validation::cc('6759354334874804313', array('switch'))); + $this->assertTrue(Validation::cc('6759900856420875115', array('switch'))); + $this->assertTrue(Validation::cc('5641827269346868860', array('switch'))); + $this->assertTrue(Validation::cc('5641828995047453870', array('switch'))); + $this->assertTrue(Validation::cc('6333321884754806543', array('switch'))); + $this->assertTrue(Validation::cc('6333108246283715901', array('switch'))); + $this->assertTrue(Validation::cc('6759572372800700102', array('switch'))); + $this->assertTrue(Validation::cc('4903095096797974933', array('switch'))); + $this->assertTrue(Validation::cc('6333354315797920215', array('switch'))); + $this->assertTrue(Validation::cc('6759163746089433755', array('switch'))); + $this->assertTrue(Validation::cc('6759871666634807647', array('switch'))); + $this->assertTrue(Validation::cc('5641827883728575248', array('switch'))); + $this->assertTrue(Validation::cc('4936527975051407847', array('switch'))); + $this->assertTrue(Validation::cc('5641823318396882141', array('switch'))); + $this->assertTrue(Validation::cc('6759123772311123708', array('switch'))); + $this->assertTrue(Validation::cc('4903054736148271088', array('switch'))); + $this->assertTrue(Validation::cc('4936477526808883952', array('switch'))); + $this->assertTrue(Validation::cc('4936433964890967966', array('switch'))); + $this->assertTrue(Validation::cc('6333245128906049344', array('switch'))); + $this->assertTrue(Validation::cc('4936321036970553134', array('switch'))); + $this->assertTrue(Validation::cc('4936111816358702773', array('switch'))); + $this->assertTrue(Validation::cc('4936196077254804290', array('switch'))); + $this->assertTrue(Validation::cc('6759558831206830183', array('switch'))); + $this->assertTrue(Validation::cc('5641827998830403137', array('switch'))); + //VISA 13 digit + $this->assertTrue(Validation::cc('4024007174754', array('visa'))); + $this->assertTrue(Validation::cc('4104816460717', array('visa'))); + $this->assertTrue(Validation::cc('4716229700437', array('visa'))); + $this->assertTrue(Validation::cc('4539305400213', array('visa'))); + $this->assertTrue(Validation::cc('4728260558665', array('visa'))); + $this->assertTrue(Validation::cc('4929100131792', array('visa'))); + $this->assertTrue(Validation::cc('4024007117308', array('visa'))); + $this->assertTrue(Validation::cc('4539915491024', array('visa'))); + $this->assertTrue(Validation::cc('4539790901139', array('visa'))); + $this->assertTrue(Validation::cc('4485284914909', array('visa'))); + $this->assertTrue(Validation::cc('4782793022350', array('visa'))); + $this->assertTrue(Validation::cc('4556899290685', array('visa'))); + $this->assertTrue(Validation::cc('4024007134774', array('visa'))); + $this->assertTrue(Validation::cc('4333412341316', array('visa'))); + $this->assertTrue(Validation::cc('4539534204543', array('visa'))); + $this->assertTrue(Validation::cc('4485640373626', array('visa'))); + $this->assertTrue(Validation::cc('4929911445746', array('visa'))); + $this->assertTrue(Validation::cc('4539292550806', array('visa'))); + $this->assertTrue(Validation::cc('4716523014030', array('visa'))); + $this->assertTrue(Validation::cc('4024007125152', array('visa'))); + $this->assertTrue(Validation::cc('4539758883311', array('visa'))); + $this->assertTrue(Validation::cc('4024007103258', array('visa'))); + $this->assertTrue(Validation::cc('4916933155767', array('visa'))); + $this->assertTrue(Validation::cc('4024007159672', array('visa'))); + $this->assertTrue(Validation::cc('4716935544871', array('visa'))); + $this->assertTrue(Validation::cc('4929415177779', array('visa'))); + $this->assertTrue(Validation::cc('4929748547896', array('visa'))); + $this->assertTrue(Validation::cc('4929153468612', array('visa'))); + $this->assertTrue(Validation::cc('4539397132104', array('visa'))); + $this->assertTrue(Validation::cc('4485293435540', array('visa'))); + $this->assertTrue(Validation::cc('4485799412720', array('visa'))); + $this->assertTrue(Validation::cc('4916744757686', array('visa'))); + $this->assertTrue(Validation::cc('4556475655426', array('visa'))); + $this->assertTrue(Validation::cc('4539400441625', array('visa'))); + $this->assertTrue(Validation::cc('4485437129173', array('visa'))); + $this->assertTrue(Validation::cc('4716253605320', array('visa'))); + $this->assertTrue(Validation::cc('4539366156589', array('visa'))); + $this->assertTrue(Validation::cc('4916498061392', array('visa'))); + $this->assertTrue(Validation::cc('4716127163779', array('visa'))); + $this->assertTrue(Validation::cc('4024007183078', array('visa'))); + $this->assertTrue(Validation::cc('4041553279654', array('visa'))); + $this->assertTrue(Validation::cc('4532380121960', array('visa'))); + $this->assertTrue(Validation::cc('4485906062491', array('visa'))); + $this->assertTrue(Validation::cc('4539365115149', array('visa'))); + $this->assertTrue(Validation::cc('4485146516702', array('visa'))); + //VISA 16 digit + $this->assertTrue(Validation::cc('4916375389940009', array('visa'))); + $this->assertTrue(Validation::cc('4929167481032610', array('visa'))); + $this->assertTrue(Validation::cc('4485029969061519', array('visa'))); + $this->assertTrue(Validation::cc('4485573845281759', array('visa'))); + $this->assertTrue(Validation::cc('4485669810383529', array('visa'))); + $this->assertTrue(Validation::cc('4929615806560327', array('visa'))); + $this->assertTrue(Validation::cc('4556807505609535', array('visa'))); + $this->assertTrue(Validation::cc('4532611336232890', array('visa'))); + $this->assertTrue(Validation::cc('4532201952422387', array('visa'))); + $this->assertTrue(Validation::cc('4485073797976290', array('visa'))); + $this->assertTrue(Validation::cc('4024007157580969', array('visa'))); + $this->assertTrue(Validation::cc('4053740470212274', array('visa'))); + $this->assertTrue(Validation::cc('4716265831525676', array('visa'))); + $this->assertTrue(Validation::cc('4024007100222966', array('visa'))); + $this->assertTrue(Validation::cc('4539556148303244', array('visa'))); + $this->assertTrue(Validation::cc('4532449879689709', array('visa'))); + $this->assertTrue(Validation::cc('4916805467840986', array('visa'))); + $this->assertTrue(Validation::cc('4532155644440233', array('visa'))); + $this->assertTrue(Validation::cc('4467977802223781', array('visa'))); + $this->assertTrue(Validation::cc('4539224637000686', array('visa'))); + $this->assertTrue(Validation::cc('4556629187064965', array('visa'))); + $this->assertTrue(Validation::cc('4532970205932943', array('visa'))); + $this->assertTrue(Validation::cc('4821470132041850', array('visa'))); + $this->assertTrue(Validation::cc('4916214267894485', array('visa'))); + $this->assertTrue(Validation::cc('4024007169073284', array('visa'))); + $this->assertTrue(Validation::cc('4716783351296122', array('visa'))); + $this->assertTrue(Validation::cc('4556480171913795', array('visa'))); + $this->assertTrue(Validation::cc('4929678411034997', array('visa'))); + $this->assertTrue(Validation::cc('4682061913519392', array('visa'))); + $this->assertTrue(Validation::cc('4916495481746474', array('visa'))); + $this->assertTrue(Validation::cc('4929007108460499', array('visa'))); + $this->assertTrue(Validation::cc('4539951357838586', array('visa'))); + $this->assertTrue(Validation::cc('4716482691051558', array('visa'))); + $this->assertTrue(Validation::cc('4916385069917516', array('visa'))); + $this->assertTrue(Validation::cc('4929020289494641', array('visa'))); + $this->assertTrue(Validation::cc('4532176245263774', array('visa'))); + $this->assertTrue(Validation::cc('4556242273553949', array('visa'))); + $this->assertTrue(Validation::cc('4481007485188614', array('visa'))); + $this->assertTrue(Validation::cc('4716533372139623', array('visa'))); + $this->assertTrue(Validation::cc('4929152038152632', array('visa'))); + $this->assertTrue(Validation::cc('4539404037310550', array('visa'))); + $this->assertTrue(Validation::cc('4532800925229140', array('visa'))); + $this->assertTrue(Validation::cc('4916845885268360', array('visa'))); + $this->assertTrue(Validation::cc('4394514669078434', array('visa'))); + $this->assertTrue(Validation::cc('4485611378115042', array('visa'))); + //Visa Electron + $this->assertTrue(Validation::cc('4175003346287100', array('electron'))); + $this->assertTrue(Validation::cc('4913042516577228', array('electron'))); + $this->assertTrue(Validation::cc('4917592325659381', array('electron'))); + $this->assertTrue(Validation::cc('4917084924450511', array('electron'))); + $this->assertTrue(Validation::cc('4917994610643999', array('electron'))); + $this->assertTrue(Validation::cc('4175005933743585', array('electron'))); + $this->assertTrue(Validation::cc('4175008373425044', array('electron'))); + $this->assertTrue(Validation::cc('4913119763664154', array('electron'))); + $this->assertTrue(Validation::cc('4913189017481812', array('electron'))); + $this->assertTrue(Validation::cc('4913085104968622', array('electron'))); + $this->assertTrue(Validation::cc('4175008803122021', array('electron'))); + $this->assertTrue(Validation::cc('4913294453962489', array('electron'))); + $this->assertTrue(Validation::cc('4175009797419290', array('electron'))); + $this->assertTrue(Validation::cc('4175005028142917', array('electron'))); + $this->assertTrue(Validation::cc('4913940802385364', array('electron'))); + //Voyager + $this->assertTrue(Validation::cc('869940697287073', array('voyager'))); + $this->assertTrue(Validation::cc('869934523596112', array('voyager'))); + $this->assertTrue(Validation::cc('869958670174621', array('voyager'))); + $this->assertTrue(Validation::cc('869921250068209', array('voyager'))); + $this->assertTrue(Validation::cc('869972521242198', array('voyager'))); + } + +/** + * testLuhn method + * + * @return void + */ + public function testLuhn() { + //American Express + $this->assertTrue(Validation::luhn('370482756063980', true)); + //BankCard + $this->assertTrue(Validation::luhn('5610745867413420', true)); + //Diners Club 14 + $this->assertTrue(Validation::luhn('30155483651028', true)); + //2004 MasterCard/Diners Club Alliance International 14 + $this->assertTrue(Validation::luhn('36747701998969', true)); + //2004 MasterCard/Diners Club Alliance US & Canada 16 + $this->assertTrue(Validation::luhn('5597511346169950', true)); + //Discover + $this->assertTrue(Validation::luhn('6011802876467237', true)); + //enRoute + $this->assertTrue(Validation::luhn('201496944158937', true)); + //JCB 15 digit + $this->assertTrue(Validation::luhn('210034762247893', true)); + //JCB 16 digit + $this->assertTrue(Validation::luhn('3096806857839939', true)); + //Maestro (debit card) + $this->assertTrue(Validation::luhn('5020147409985219', true)); + //Mastercard + $this->assertTrue(Validation::luhn('5580424361774366', true)); + //Solo 16 + $this->assertTrue(Validation::luhn('6767432107064987', true)); + //Solo 18 + $this->assertTrue(Validation::luhn('676714834398858593', true)); + //Solo 19 + $this->assertTrue(Validation::luhn('6767838565218340113', true)); + //Switch 16 + $this->assertTrue(Validation::luhn('5641829171515733', true)); + //Switch 18 + $this->assertTrue(Validation::luhn('493622764224625174', true)); + //Switch 19 + $this->assertTrue(Validation::luhn('6759603460617628716', true)); + //VISA 13 digit + $this->assertTrue(Validation::luhn('4024007174754', true)); + //VISA 16 digit + $this->assertTrue(Validation::luhn('4916375389940009', true)); + //Visa Electron + $this->assertTrue(Validation::luhn('4175003346287100', true)); + //Voyager + $this->assertTrue(Validation::luhn('869940697287073', true)); + + $this->assertFalse(Validation::luhn('0000000000000000', true)); + + $this->assertFalse(Validation::luhn('869940697287173', true)); + } + +/** + * testCustomRegexForCc method + * + * @return void + */ + public function testCustomRegexForCc() { + $this->assertTrue(Validation::cc('12332105933743585', null, null, '/123321\\d{11}/')); + $this->assertFalse(Validation::cc('1233210593374358', null, null, '/123321\\d{11}/')); + $this->assertFalse(Validation::cc('12312305933743585', null, null, '/123321\\d{11}/')); + } + +/** + * testCustomRegexForCcWithLuhnCheck method + * + * @return void + */ + public function testCustomRegexForCcWithLuhnCheck() { + $this->assertTrue(Validation::cc('12332110426226941', null, true, '/123321\\d{11}/')); + $this->assertFalse(Validation::cc('12332105933743585', null, true, '/123321\\d{11}/')); + $this->assertFalse(Validation::cc('12332105933743587', null, true, '/123321\\d{11}/')); + $this->assertFalse(Validation::cc('12312305933743585', null, true, '/123321\\d{11}/')); + } + +/** + * testFastCc method + * + * @return void + */ + public function testFastCc() { + // too short + $this->assertFalse(Validation::cc('123456789012')); + //American Express + $this->assertTrue(Validation::cc('370482756063980')); + //Diners Club 14 + $this->assertTrue(Validation::cc('30155483651028')); + //2004 MasterCard/Diners Club Alliance International 14 + $this->assertTrue(Validation::cc('36747701998969')); + //2004 MasterCard/Diners Club Alliance US & Canada 16 + $this->assertTrue(Validation::cc('5597511346169950')); + //Discover + $this->assertTrue(Validation::cc('6011802876467237')); + //Mastercard + $this->assertTrue(Validation::cc('5580424361774366')); + //VISA 13 digit + $this->assertTrue(Validation::cc('4024007174754')); + //VISA 16 digit + $this->assertTrue(Validation::cc('4916375389940009')); + //Visa Electron + $this->assertTrue(Validation::cc('4175003346287100')); + } + +/** + * testAllCc method + * + * @return void + */ + public function testAllCc() { + //American Express + $this->assertTrue(Validation::cc('370482756063980', 'all')); + //BankCard + $this->assertTrue(Validation::cc('5610745867413420', 'all')); + //Diners Club 14 + $this->assertTrue(Validation::cc('30155483651028', 'all')); + //2004 MasterCard/Diners Club Alliance International 14 + $this->assertTrue(Validation::cc('36747701998969', 'all')); + //2004 MasterCard/Diners Club Alliance US & Canada 16 + $this->assertTrue(Validation::cc('5597511346169950', 'all')); + //Discover + $this->assertTrue(Validation::cc('6011802876467237', 'all')); + //enRoute + $this->assertTrue(Validation::cc('201496944158937', 'all')); + //JCB 15 digit + $this->assertTrue(Validation::cc('210034762247893', 'all')); + //JCB 16 digit + $this->assertTrue(Validation::cc('3096806857839939', 'all')); + //Maestro (debit card) + $this->assertTrue(Validation::cc('5020147409985219', 'all')); + //Mastercard + $this->assertTrue(Validation::cc('5580424361774366', 'all')); + //Solo 16 + $this->assertTrue(Validation::cc('6767432107064987', 'all')); + //Solo 18 + $this->assertTrue(Validation::cc('676714834398858593', 'all')); + //Solo 19 + $this->assertTrue(Validation::cc('6767838565218340113', 'all')); + //Switch 16 + $this->assertTrue(Validation::cc('5641829171515733', 'all')); + //Switch 18 + $this->assertTrue(Validation::cc('493622764224625174', 'all')); + //Switch 19 + $this->assertTrue(Validation::cc('6759603460617628716', 'all')); + //VISA 13 digit + $this->assertTrue(Validation::cc('4024007174754', 'all')); + //VISA 16 digit + $this->assertTrue(Validation::cc('4916375389940009', 'all')); + //Visa Electron + $this->assertTrue(Validation::cc('4175003346287100', 'all')); + //Voyager + $this->assertTrue(Validation::cc('869940697287073', 'all')); + } + +/** + * testAllCcDeep method + * + * @return void + */ + public function testAllCcDeep() { + //American Express + $this->assertTrue(Validation::cc('370482756063980', 'all', true)); + //BankCard + $this->assertTrue(Validation::cc('5610745867413420', 'all', true)); + //Diners Club 14 + $this->assertTrue(Validation::cc('30155483651028', 'all', true)); + //2004 MasterCard/Diners Club Alliance International 14 + $this->assertTrue(Validation::cc('36747701998969', 'all', true)); + //2004 MasterCard/Diners Club Alliance US & Canada 16 + $this->assertTrue(Validation::cc('5597511346169950', 'all', true)); + //Discover + $this->assertTrue(Validation::cc('6011802876467237', 'all', true)); + //enRoute + $this->assertTrue(Validation::cc('201496944158937', 'all', true)); + //JCB 15 digit + $this->assertTrue(Validation::cc('210034762247893', 'all', true)); + //JCB 16 digit + $this->assertTrue(Validation::cc('3096806857839939', 'all', true)); + //Maestro (debit card) + $this->assertTrue(Validation::cc('5020147409985219', 'all', true)); + //Mastercard + $this->assertTrue(Validation::cc('5580424361774366', 'all', true)); + //Solo 16 + $this->assertTrue(Validation::cc('6767432107064987', 'all', true)); + //Solo 18 + $this->assertTrue(Validation::cc('676714834398858593', 'all', true)); + //Solo 19 + $this->assertTrue(Validation::cc('6767838565218340113', 'all', true)); + //Switch 16 + $this->assertTrue(Validation::cc('5641829171515733', 'all', true)); + //Switch 18 + $this->assertTrue(Validation::cc('493622764224625174', 'all', true)); + //Switch 19 + $this->assertTrue(Validation::cc('6759603460617628716', 'all', true)); + //VISA 13 digit + $this->assertTrue(Validation::cc('4024007174754', 'all', true)); + //VISA 16 digit + $this->assertTrue(Validation::cc('4916375389940009', 'all', true)); + //Visa Electron + $this->assertTrue(Validation::cc('4175003346287100', 'all', true)); + //Voyager + $this->assertTrue(Validation::cc('869940697287073', 'all', true)); + } + +/** + * testComparison method + * + * @return void + */ + public function testComparison() { + $this->assertFalse(Validation::comparison(7, null, 6)); + $this->assertTrue(Validation::comparison(7, 'is greater', 6)); + $this->assertTrue(Validation::comparison(7, '>', 6)); + $this->assertTrue(Validation::comparison(6, 'is less', 7)); + $this->assertTrue(Validation::comparison(6, '<', 7)); + $this->assertTrue(Validation::comparison(7, 'greater or equal', 7)); + $this->assertTrue(Validation::comparison(7, '>=', 7)); + $this->assertTrue(Validation::comparison(7, 'greater or equal', 6)); + $this->assertTrue(Validation::comparison(7, '>=', 6)); + $this->assertTrue(Validation::comparison(6, 'less or equal', 7)); + $this->assertTrue(Validation::comparison(6, '<=', 7)); + $this->assertTrue(Validation::comparison(7, 'equal to', 7)); + $this->assertTrue(Validation::comparison(7, '==', 7)); + $this->assertTrue(Validation::comparison(7, 'not equal', 6)); + $this->assertTrue(Validation::comparison(7, '!=', 6)); + $this->assertFalse(Validation::comparison(6, 'is greater', 7)); + $this->assertFalse(Validation::comparison(6, '>', 7)); + $this->assertFalse(Validation::comparison(7, 'is less', 6)); + $this->assertFalse(Validation::comparison(7, '<', 6)); + $this->assertFalse(Validation::comparison(6, 'greater or equal', 7)); + $this->assertFalse(Validation::comparison(6, '>=', 7)); + $this->assertFalse(Validation::comparison(6, 'greater or equal', 7)); + $this->assertFalse(Validation::comparison(6, '>=', 7)); + $this->assertFalse(Validation::comparison(7, 'less or equal', 6)); + $this->assertFalse(Validation::comparison(7, '<=', 6)); + $this->assertFalse(Validation::comparison(7, 'equal to', 6)); + $this->assertFalse(Validation::comparison(7, '==', 6)); + $this->assertFalse(Validation::comparison(7, 'not equal', 7)); + $this->assertFalse(Validation::comparison(7, '!=', 7)); + } + +/** + * testComparisonAsArray method + * + * @return void + */ + public function testComparisonAsArray() { + $this->assertTrue(Validation::comparison(array('check1' => 7, 'operator' => 'is greater', 'check2' => 6))); + $this->assertTrue(Validation::comparison(array('check1' => 7, 'operator' => '>', 'check2' => 6))); + $this->assertTrue(Validation::comparison(array('check1' => 6, 'operator' => 'is less', 'check2' => 7))); + $this->assertTrue(Validation::comparison(array('check1' => 6, 'operator' => '<', 'check2' => 7))); + $this->assertTrue(Validation::comparison(array('check1' => 7, 'operator' => 'greater or equal', 'check2' => 7))); + $this->assertTrue(Validation::comparison(array('check1' => 7, 'operator' => '>=', 'check2' => 7))); + $this->assertTrue(Validation::comparison(array('check1' => 7, 'operator' => 'greater or equal','check2' => 6))); + $this->assertTrue(Validation::comparison(array('check1' => 7, 'operator' => '>=', 'check2' => 6))); + $this->assertTrue(Validation::comparison(array('check1' => 6, 'operator' => 'less or equal', 'check2' => 7))); + $this->assertTrue(Validation::comparison(array('check1' => 6, 'operator' => '<=', 'check2' => 7))); + $this->assertTrue(Validation::comparison(array('check1' => 7, 'operator' => 'equal to', 'check2' => 7))); + $this->assertTrue(Validation::comparison(array('check1' => 7, 'operator' => '==', 'check2' => 7))); + $this->assertTrue(Validation::comparison(array('check1' => 7, 'operator' => 'not equal', 'check2' => 6))); + $this->assertTrue(Validation::comparison(array('check1' => 7, 'operator' => '!=', 'check2' => 6))); + $this->assertFalse(Validation::comparison(array('check1' => 6, 'operator' => 'is greater', 'check2' => 7))); + $this->assertFalse(Validation::comparison(array('check1' => 6, 'operator' => '>', 'check2' => 7))); + $this->assertFalse(Validation::comparison(array('check1' => 7, 'operator' => 'is less', 'check2' => 6))); + $this->assertFalse(Validation::comparison(array('check1' => 7, 'operator' => '<', 'check2' => 6))); + $this->assertFalse(Validation::comparison(array('check1' => 6, 'operator' => 'greater or equal', 'check2' => 7))); + $this->assertFalse(Validation::comparison(array('check1' => 6, 'operator' => '>=', 'check2' => 7))); + $this->assertFalse(Validation::comparison(array('check1' => 6, 'operator' => 'greater or equal', 'check2' => 7))); + $this->assertFalse(Validation::comparison(array('check1' => 6, 'operator' => '>=', 'check2' => 7))); + $this->assertFalse(Validation::comparison(array('check1' => 7, 'operator' => 'less or equal', 'check2' => 6))); + $this->assertFalse(Validation::comparison(array('check1' => 7, 'operator' => '<=', 'check2' => 6))); + $this->assertFalse(Validation::comparison(array('check1' => 7, 'operator' => 'equal to', 'check2' => 6))); + $this->assertFalse(Validation::comparison(array('check1' => 7, 'operator' => '==','check2' => 6))); + $this->assertFalse(Validation::comparison(array('check1' => 7, 'operator' => 'not equal', 'check2' => 7))); + $this->assertFalse(Validation::comparison(array('check1' => 7, 'operator' => '!=', 'check2' => 7))); + } + +/** + * testCustom method + * + * @return void + */ + public function testCustom() { + $this->assertTrue(Validation::custom('12345', '/(?assertFalse(Validation::custom('Text', '/(?assertFalse(Validation::custom('123.45', '/(?assertFalse(Validation::custom('missing regex')); + } + +/** + * testCustomAsArray method + * + * @return void + */ + public function testCustomAsArray() { + $this->assertTrue(Validation::custom(array('check' => '12345', 'regex' => '/(?assertFalse(Validation::custom(array('check' => 'Text', 'regex' => '/(?assertFalse(Validation::custom(array('check' => '123.45', 'regex' => '/(?assertTrue(Validation::date('27-12-2006', array('dmy'))); + $this->assertTrue(Validation::date('27.12.2006', array('dmy'))); + $this->assertTrue(Validation::date('27/12/2006', array('dmy'))); + $this->assertTrue(Validation::date('27 12 2006', array('dmy'))); + $this->assertFalse(Validation::date('00-00-0000', array('dmy'))); + $this->assertFalse(Validation::date('00.00.0000', array('dmy'))); + $this->assertFalse(Validation::date('00/00/0000', array('dmy'))); + $this->assertFalse(Validation::date('00 00 0000', array('dmy'))); + $this->assertFalse(Validation::date('31-11-2006', array('dmy'))); + $this->assertFalse(Validation::date('31.11.2006', array('dmy'))); + $this->assertFalse(Validation::date('31/11/2006', array('dmy'))); + $this->assertFalse(Validation::date('31 11 2006', array('dmy'))); + } + +/** + * testDateDdmmyyyyLeapYear method + * + * @return void + */ + public function testDateDdmmyyyyLeapYear() { + $this->assertTrue(Validation::date('29-02-2004', array('dmy'))); + $this->assertTrue(Validation::date('29.02.2004', array('dmy'))); + $this->assertTrue(Validation::date('29/02/2004', array('dmy'))); + $this->assertTrue(Validation::date('29 02 2004', array('dmy'))); + $this->assertFalse(Validation::date('29-02-2006', array('dmy'))); + $this->assertFalse(Validation::date('29.02.2006', array('dmy'))); + $this->assertFalse(Validation::date('29/02/2006', array('dmy'))); + $this->assertFalse(Validation::date('29 02 2006', array('dmy'))); + } + +/** + * testDateDdmmyy method + * + * @return void + */ + public function testDateDdmmyy() { + $this->assertTrue(Validation::date('27-12-06', array('dmy'))); + $this->assertTrue(Validation::date('27.12.06', array('dmy'))); + $this->assertTrue(Validation::date('27/12/06', array('dmy'))); + $this->assertTrue(Validation::date('27 12 06', array('dmy'))); + $this->assertFalse(Validation::date('00-00-00', array('dmy'))); + $this->assertFalse(Validation::date('00.00.00', array('dmy'))); + $this->assertFalse(Validation::date('00/00/00', array('dmy'))); + $this->assertFalse(Validation::date('00 00 00', array('dmy'))); + $this->assertFalse(Validation::date('31-11-06', array('dmy'))); + $this->assertFalse(Validation::date('31.11.06', array('dmy'))); + $this->assertFalse(Validation::date('31/11/06', array('dmy'))); + $this->assertFalse(Validation::date('31 11 06', array('dmy'))); + } + +/** + * testDateDdmmyyLeapYear method + * + * @return void + */ + public function testDateDdmmyyLeapYear() { + $this->assertTrue(Validation::date('29-02-04', array('dmy'))); + $this->assertTrue(Validation::date('29.02.04', array('dmy'))); + $this->assertTrue(Validation::date('29/02/04', array('dmy'))); + $this->assertTrue(Validation::date('29 02 04', array('dmy'))); + $this->assertFalse(Validation::date('29-02-06', array('dmy'))); + $this->assertFalse(Validation::date('29.02.06', array('dmy'))); + $this->assertFalse(Validation::date('29/02/06', array('dmy'))); + $this->assertFalse(Validation::date('29 02 06', array('dmy'))); + } + +/** + * testDateDmyy method + * + * @return void + */ + public function testDateDmyy() { + $this->assertTrue(Validation::date('7-2-06', array('dmy'))); + $this->assertTrue(Validation::date('7.2.06', array('dmy'))); + $this->assertTrue(Validation::date('7/2/06', array('dmy'))); + $this->assertTrue(Validation::date('7 2 06', array('dmy'))); + $this->assertFalse(Validation::date('0-0-00', array('dmy'))); + $this->assertFalse(Validation::date('0.0.00', array('dmy'))); + $this->assertFalse(Validation::date('0/0/00', array('dmy'))); + $this->assertFalse(Validation::date('0 0 00', array('dmy'))); + $this->assertFalse(Validation::date('32-2-06', array('dmy'))); + $this->assertFalse(Validation::date('32.2.06', array('dmy'))); + $this->assertFalse(Validation::date('32/2/06', array('dmy'))); + $this->assertFalse(Validation::date('32 2 06', array('dmy'))); + } + +/** + * testDateDmyyLeapYear method + * + * @return void + */ + public function testDateDmyyLeapYear() { + $this->assertTrue(Validation::date('29-2-04', array('dmy'))); + $this->assertTrue(Validation::date('29.2.04', array('dmy'))); + $this->assertTrue(Validation::date('29/2/04', array('dmy'))); + $this->assertTrue(Validation::date('29 2 04', array('dmy'))); + $this->assertFalse(Validation::date('29-2-06', array('dmy'))); + $this->assertFalse(Validation::date('29.2.06', array('dmy'))); + $this->assertFalse(Validation::date('29/2/06', array('dmy'))); + $this->assertFalse(Validation::date('29 2 06', array('dmy'))); + } + +/** + * testDateDmyyyy method + * + * @return void + */ + public function testDateDmyyyy() { + $this->assertTrue(Validation::date('7-2-2006', array('dmy'))); + $this->assertTrue(Validation::date('7.2.2006', array('dmy'))); + $this->assertTrue(Validation::date('7/2/2006', array('dmy'))); + $this->assertTrue(Validation::date('7 2 2006', array('dmy'))); + $this->assertFalse(Validation::date('0-0-0000', array('dmy'))); + $this->assertFalse(Validation::date('0.0.0000', array('dmy'))); + $this->assertFalse(Validation::date('0/0/0000', array('dmy'))); + $this->assertFalse(Validation::date('0 0 0000', array('dmy'))); + $this->assertFalse(Validation::date('32-2-2006', array('dmy'))); + $this->assertFalse(Validation::date('32.2.2006', array('dmy'))); + $this->assertFalse(Validation::date('32/2/2006', array('dmy'))); + $this->assertFalse(Validation::date('32 2 2006', array('dmy'))); + } + +/** + * testDateDmyyyyLeapYear method + * + * @return void + */ + public function testDateDmyyyyLeapYear() { + $this->assertTrue(Validation::date('29-2-2004', array('dmy'))); + $this->assertTrue(Validation::date('29.2.2004', array('dmy'))); + $this->assertTrue(Validation::date('29/2/2004', array('dmy'))); + $this->assertTrue(Validation::date('29 2 2004', array('dmy'))); + $this->assertFalse(Validation::date('29-2-2006', array('dmy'))); + $this->assertFalse(Validation::date('29.2.2006', array('dmy'))); + $this->assertFalse(Validation::date('29/2/2006', array('dmy'))); + $this->assertFalse(Validation::date('29 2 2006', array('dmy'))); + } + +/** + * testDateMmddyyyy method + * + * @return void + */ + public function testDateMmddyyyy() { + $this->assertTrue(Validation::date('12-27-2006', array('mdy'))); + $this->assertTrue(Validation::date('12.27.2006', array('mdy'))); + $this->assertTrue(Validation::date('12/27/2006', array('mdy'))); + $this->assertTrue(Validation::date('12 27 2006', array('mdy'))); + $this->assertFalse(Validation::date('00-00-0000', array('mdy'))); + $this->assertFalse(Validation::date('00.00.0000', array('mdy'))); + $this->assertFalse(Validation::date('00/00/0000', array('mdy'))); + $this->assertFalse(Validation::date('00 00 0000', array('mdy'))); + $this->assertFalse(Validation::date('11-31-2006', array('mdy'))); + $this->assertFalse(Validation::date('11.31.2006', array('mdy'))); + $this->assertFalse(Validation::date('11/31/2006', array('mdy'))); + $this->assertFalse(Validation::date('11 31 2006', array('mdy'))); + } + +/** + * testDateMmddyyyyLeapYear method + * + * @return void + */ + public function testDateMmddyyyyLeapYear() { + $this->assertTrue(Validation::date('02-29-2004', array('mdy'))); + $this->assertTrue(Validation::date('02.29.2004', array('mdy'))); + $this->assertTrue(Validation::date('02/29/2004', array('mdy'))); + $this->assertTrue(Validation::date('02 29 2004', array('mdy'))); + $this->assertFalse(Validation::date('02-29-2006', array('mdy'))); + $this->assertFalse(Validation::date('02.29.2006', array('mdy'))); + $this->assertFalse(Validation::date('02/29/2006', array('mdy'))); + $this->assertFalse(Validation::date('02 29 2006', array('mdy'))); + } + +/** + * testDateMmddyy method + * + * @return void + */ + public function testDateMmddyy() { + $this->assertTrue(Validation::date('12-27-06', array('mdy'))); + $this->assertTrue(Validation::date('12.27.06', array('mdy'))); + $this->assertTrue(Validation::date('12/27/06', array('mdy'))); + $this->assertTrue(Validation::date('12 27 06', array('mdy'))); + $this->assertFalse(Validation::date('00-00-00', array('mdy'))); + $this->assertFalse(Validation::date('00.00.00', array('mdy'))); + $this->assertFalse(Validation::date('00/00/00', array('mdy'))); + $this->assertFalse(Validation::date('00 00 00', array('mdy'))); + $this->assertFalse(Validation::date('11-31-06', array('mdy'))); + $this->assertFalse(Validation::date('11.31.06', array('mdy'))); + $this->assertFalse(Validation::date('11/31/06', array('mdy'))); + $this->assertFalse(Validation::date('11 31 06', array('mdy'))); + } + +/** + * testDateMmddyyLeapYear method + * + * @return void + */ + public function testDateMmddyyLeapYear() { + $this->assertTrue(Validation::date('02-29-04', array('mdy'))); + $this->assertTrue(Validation::date('02.29.04', array('mdy'))); + $this->assertTrue(Validation::date('02/29/04', array('mdy'))); + $this->assertTrue(Validation::date('02 29 04', array('mdy'))); + $this->assertFalse(Validation::date('02-29-06', array('mdy'))); + $this->assertFalse(Validation::date('02.29.06', array('mdy'))); + $this->assertFalse(Validation::date('02/29/06', array('mdy'))); + $this->assertFalse(Validation::date('02 29 06', array('mdy'))); + } + +/** + * testDateMdyy method + * + * @return void + */ + public function testDateMdyy() { + $this->assertTrue(Validation::date('2-7-06', array('mdy'))); + $this->assertTrue(Validation::date('2.7.06', array('mdy'))); + $this->assertTrue(Validation::date('2/7/06', array('mdy'))); + $this->assertTrue(Validation::date('2 7 06', array('mdy'))); + $this->assertFalse(Validation::date('0-0-00', array('mdy'))); + $this->assertFalse(Validation::date('0.0.00', array('mdy'))); + $this->assertFalse(Validation::date('0/0/00', array('mdy'))); + $this->assertFalse(Validation::date('0 0 00', array('mdy'))); + $this->assertFalse(Validation::date('2-32-06', array('mdy'))); + $this->assertFalse(Validation::date('2.32.06', array('mdy'))); + $this->assertFalse(Validation::date('2/32/06', array('mdy'))); + $this->assertFalse(Validation::date('2 32 06', array('mdy'))); + } + +/** + * testDateMdyyLeapYear method + * + * @return void + */ + public function testDateMdyyLeapYear() { + $this->assertTrue(Validation::date('2-29-04', array('mdy'))); + $this->assertTrue(Validation::date('2.29.04', array('mdy'))); + $this->assertTrue(Validation::date('2/29/04', array('mdy'))); + $this->assertTrue(Validation::date('2 29 04', array('mdy'))); + $this->assertFalse(Validation::date('2-29-06', array('mdy'))); + $this->assertFalse(Validation::date('2.29.06', array('mdy'))); + $this->assertFalse(Validation::date('2/29/06', array('mdy'))); + $this->assertFalse(Validation::date('2 29 06', array('mdy'))); + } + +/** + * testDateMdyyyy method + * + * @return void + */ + public function testDateMdyyyy() { + $this->assertTrue(Validation::date('2-7-2006', array('mdy'))); + $this->assertTrue(Validation::date('2.7.2006', array('mdy'))); + $this->assertTrue(Validation::date('2/7/2006', array('mdy'))); + $this->assertTrue(Validation::date('2 7 2006', array('mdy'))); + $this->assertFalse(Validation::date('0-0-0000', array('mdy'))); + $this->assertFalse(Validation::date('0.0.0000', array('mdy'))); + $this->assertFalse(Validation::date('0/0/0000', array('mdy'))); + $this->assertFalse(Validation::date('0 0 0000', array('mdy'))); + $this->assertFalse(Validation::date('2-32-2006', array('mdy'))); + $this->assertFalse(Validation::date('2.32.2006', array('mdy'))); + $this->assertFalse(Validation::date('2/32/2006', array('mdy'))); + $this->assertFalse(Validation::date('2 32 2006', array('mdy'))); + } + +/** + * testDateMdyyyyLeapYear method + * + * @return void + */ + public function testDateMdyyyyLeapYear() { + $this->assertTrue(Validation::date('2-29-2004', array('mdy'))); + $this->assertTrue(Validation::date('2.29.2004', array('mdy'))); + $this->assertTrue(Validation::date('2/29/2004', array('mdy'))); + $this->assertTrue(Validation::date('2 29 2004', array('mdy'))); + $this->assertFalse(Validation::date('2-29-2006', array('mdy'))); + $this->assertFalse(Validation::date('2.29.2006', array('mdy'))); + $this->assertFalse(Validation::date('2/29/2006', array('mdy'))); + $this->assertFalse(Validation::date('2 29 2006', array('mdy'))); + } + +/** + * testDateYyyymmdd method + * + * @return void + */ + public function testDateYyyymmdd() { + $this->assertTrue(Validation::date('2006-12-27', array('ymd'))); + $this->assertTrue(Validation::date('2006.12.27', array('ymd'))); + $this->assertTrue(Validation::date('2006/12/27', array('ymd'))); + $this->assertTrue(Validation::date('2006 12 27', array('ymd'))); + $this->assertFalse(Validation::date('2006-11-31', array('ymd'))); + $this->assertFalse(Validation::date('2006.11.31', array('ymd'))); + $this->assertFalse(Validation::date('2006/11/31', array('ymd'))); + $this->assertFalse(Validation::date('2006 11 31', array('ymd'))); + } + +/** + * testDateYyyymmddLeapYear method + * + * @return void + */ + public function testDateYyyymmddLeapYear() { + $this->assertTrue(Validation::date('2004-02-29', array('ymd'))); + $this->assertTrue(Validation::date('2004.02.29', array('ymd'))); + $this->assertTrue(Validation::date('2004/02/29', array('ymd'))); + $this->assertTrue(Validation::date('2004 02 29', array('ymd'))); + $this->assertFalse(Validation::date('2006-02-29', array('ymd'))); + $this->assertFalse(Validation::date('2006.02.29', array('ymd'))); + $this->assertFalse(Validation::date('2006/02/29', array('ymd'))); + $this->assertFalse(Validation::date('2006 02 29', array('ymd'))); + } + +/** + * testDateYymmdd method + * + * @return void + */ + public function testDateYymmdd() { + $this->assertTrue(Validation::date('06-12-27', array('ymd'))); + $this->assertTrue(Validation::date('06.12.27', array('ymd'))); + $this->assertTrue(Validation::date('06/12/27', array('ymd'))); + $this->assertTrue(Validation::date('06 12 27', array('ymd'))); + $this->assertFalse(Validation::date('12/27/2600', array('ymd'))); + $this->assertFalse(Validation::date('12.27.2600', array('ymd'))); + $this->assertFalse(Validation::date('12/27/2600', array('ymd'))); + $this->assertFalse(Validation::date('12 27 2600', array('ymd'))); + $this->assertFalse(Validation::date('06-11-31', array('ymd'))); + $this->assertFalse(Validation::date('06.11.31', array('ymd'))); + $this->assertFalse(Validation::date('06/11/31', array('ymd'))); + $this->assertFalse(Validation::date('06 11 31', array('ymd'))); + } + +/** + * testDateYymmddLeapYear method + * + * @return void + */ + public function testDateYymmddLeapYear() { + $this->assertTrue(Validation::date('2004-02-29', array('ymd'))); + $this->assertTrue(Validation::date('2004.02.29', array('ymd'))); + $this->assertTrue(Validation::date('2004/02/29', array('ymd'))); + $this->assertTrue(Validation::date('2004 02 29', array('ymd'))); + $this->assertFalse(Validation::date('2006-02-29', array('ymd'))); + $this->assertFalse(Validation::date('2006.02.29', array('ymd'))); + $this->assertFalse(Validation::date('2006/02/29', array('ymd'))); + $this->assertFalse(Validation::date('2006 02 29', array('ymd'))); + } + +/** + * testDateDdMMMMyyyy method + * + * @return void + */ + public function testDateDdMMMMyyyy() { + $this->assertTrue(Validation::date('27 December 2006', array('dMy'))); + $this->assertTrue(Validation::date('27 Dec 2006', array('dMy'))); + $this->assertFalse(Validation::date('2006 Dec 27', array('dMy'))); + $this->assertFalse(Validation::date('2006 December 27', array('dMy'))); + } + +/** + * testDateDdMMMMyyyyLeapYear method + * + * @return void + */ + public function testDateDdMMMMyyyyLeapYear() { + $this->assertTrue(Validation::date('29 February 2004', array('dMy'))); + $this->assertFalse(Validation::date('29 February 2006', array('dMy'))); + } + +/** + * testDateMmmmDdyyyy method + * + * @return void + */ + public function testDateMmmmDdyyyy() { + $this->assertTrue(Validation::date('December 27, 2006', array('Mdy'))); + $this->assertTrue(Validation::date('Dec 27, 2006', array('Mdy'))); + $this->assertTrue(Validation::date('December 27 2006', array('Mdy'))); + $this->assertTrue(Validation::date('Dec 27 2006', array('Mdy'))); + $this->assertFalse(Validation::date('27 Dec 2006', array('Mdy'))); + $this->assertFalse(Validation::date('2006 December 27', array('Mdy'))); + $this->assertTrue(Validation::date('Sep 12, 2011', array('Mdy'))); + } + +/** + * testDateMmmmDdyyyyLeapYear method + * + * @return void + */ + public function testDateMmmmDdyyyyLeapYear() { + $this->assertTrue(Validation::date('February 29, 2004', array('Mdy'))); + $this->assertTrue(Validation::date('Feb 29, 2004', array('Mdy'))); + $this->assertTrue(Validation::date('February 29 2004', array('Mdy'))); + $this->assertTrue(Validation::date('Feb 29 2004', array('Mdy'))); + $this->assertFalse(Validation::date('February 29, 2006', array('Mdy'))); + } + +/** + * testDateMy method + * + * @return void + */ + public function testDateMy() { + $this->assertTrue(Validation::date('December 2006', array('My'))); + $this->assertTrue(Validation::date('Dec 2006', array('My'))); + $this->assertTrue(Validation::date('December/2006', array('My'))); + $this->assertTrue(Validation::date('Dec/2006', array('My'))); + } + +/** + * testDateMyNumeric method + * + * @return void + */ + public function testDateMyNumeric() { + $this->assertTrue(Validation::date('12/2006', array('my'))); + $this->assertTrue(Validation::date('12-2006', array('my'))); + $this->assertTrue(Validation::date('12.2006', array('my'))); + $this->assertTrue(Validation::date('12 2006', array('my'))); + $this->assertFalse(Validation::date('12/06', array('my'))); + $this->assertFalse(Validation::date('12-06', array('my'))); + $this->assertFalse(Validation::date('12.06', array('my'))); + $this->assertFalse(Validation::date('12 06', array('my'))); + } + +/** + * Test validating dates with multiple formats + * + * @return void + */ + public function testDateMultiple() { + $this->assertTrue(Validation::date('2011-12-31', array('ymd', 'dmy'))); + $this->assertTrue(Validation::date('31-12-2011', array('ymd', 'dmy'))); + } + +/** + * testTime method + * + * @return void + */ + public function testTime() { + $this->assertTrue(Validation::time('00:00')); + $this->assertTrue(Validation::time('23:59')); + $this->assertFalse(Validation::time('24:00')); + $this->assertTrue(Validation::time('12:00')); + $this->assertTrue(Validation::time('12:01')); + $this->assertTrue(Validation::time('12:01am')); + $this->assertTrue(Validation::time('12:01pm')); + $this->assertTrue(Validation::time('1pm')); + $this->assertTrue(Validation::time('1 pm')); + $this->assertTrue(Validation::time('1 PM')); + $this->assertTrue(Validation::time('01:00')); + $this->assertFalse(Validation::time('1:00')); + $this->assertTrue(Validation::time('1:00pm')); + $this->assertFalse(Validation::time('13:00pm')); + $this->assertFalse(Validation::time('9:00')); + } + +/** + * testBoolean method + * + * @return void + */ + public function testBoolean() { + $this->assertTrue(Validation::boolean('0')); + $this->assertTrue(Validation::boolean('1')); + $this->assertTrue(Validation::boolean(0)); + $this->assertTrue(Validation::boolean(1)); + $this->assertTrue(Validation::boolean(true)); + $this->assertTrue(Validation::boolean(false)); + $this->assertFalse(Validation::boolean('true')); + $this->assertFalse(Validation::boolean('false')); + $this->assertFalse(Validation::boolean('-1')); + $this->assertFalse(Validation::boolean('2')); + $this->assertFalse(Validation::boolean('Boo!')); + } + +/** + * testDateCustomRegx method + * + * @return void + */ + public function testDateCustomRegx() { + $this->assertTrue(Validation::date('2006-12-27', null, '%^(19|20)[0-9]{2}[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$%')); + $this->assertFalse(Validation::date('12-27-2006', null, '%^(19|20)[0-9]{2}[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$%')); + } + +/** + * testDecimal method + * + * @return void + */ + public function testDecimal() { + $this->assertTrue(Validation::decimal('+1234.54321')); + $this->assertTrue(Validation::decimal('-1234.54321')); + $this->assertTrue(Validation::decimal('1234.54321')); + $this->assertTrue(Validation::decimal('+0123.45e6')); + $this->assertTrue(Validation::decimal('-0123.45e6')); + $this->assertTrue(Validation::decimal('0123.45e6')); + $this->assertTrue(Validation::decimal('1234')); + $this->assertTrue(Validation::decimal('-1234')); + $this->assertTrue(Validation::decimal('+1234')); + $this->assertTrue(Validation::decimal(1234.56)); + $this->assertTrue(Validation::decimal(1234.00)); + $this->assertTrue(Validation::decimal(.0)); + $this->assertTrue(Validation::decimal(.00)); + $this->assertTrue(Validation::decimal(.01)); + + $this->assertFalse(Validation::decimal('string')); + } + +/** + * testDecimalWithPlaces method + * + * @return void + */ + public function testDecimalWithPlaces() { + $this->assertTrue(Validation::decimal('.27', '2')); + $this->assertTrue(Validation::decimal(0.27, 2)); + $this->assertTrue(Validation::decimal(-0.27, 2)); + $this->assertTrue(Validation::decimal(0.27, 2)); + $this->assertTrue(Validation::decimal('0.277', '3')); + $this->assertTrue(Validation::decimal(0.277, 3)); + $this->assertTrue(Validation::decimal(-0.277, 3)); + $this->assertTrue(Validation::decimal(0.277, 3)); + $this->assertTrue(Validation::decimal('1234.5678', '4')); + $this->assertTrue(Validation::decimal(1234.5678, 4)); + $this->assertTrue(Validation::decimal(-1234.5678, 4)); + $this->assertTrue(Validation::decimal(1234.5678, 4)); + $this->assertFalse(Validation::decimal('1234.5678', '3')); + $this->assertFalse(Validation::decimal(1234.5678, 3)); + $this->assertFalse(Validation::decimal(-1234.5678, 3)); + $this->assertFalse(Validation::decimal(1234.5678, 3)); + } + +/** + * testDecimalCustomRegex method + * + * @return void + */ + public function testDecimalCustomRegex() { + $this->assertTrue(Validation::decimal('1.54321', null, '/^[-+]?[0-9]+(\\.[0-9]+)?$/s')); + $this->assertFalse(Validation::decimal('.54321', null, '/^[-+]?[0-9]+(\\.[0-9]+)?$/s')); + } + +/** + * testEmail method + * + * @return void + */ + public function testEmail() { + $this->assertTrue(Validation::email('abc.efg@domain.com')); + $this->assertTrue(Validation::email('efg@domain.com')); + $this->assertTrue(Validation::email('abc-efg@domain.com')); + $this->assertTrue(Validation::email('abc_efg@domain.com')); + $this->assertTrue(Validation::email('raw@test.ra.ru')); + $this->assertTrue(Validation::email('abc-efg@domain-hyphened.com')); + $this->assertTrue(Validation::email("p.o'malley@domain.com")); + $this->assertTrue(Validation::email('abc+efg@domain.com')); + $this->assertTrue(Validation::email('abc&efg@domain.com')); + $this->assertTrue(Validation::email('abc.efg@12345.com')); + $this->assertTrue(Validation::email('abc.efg@12345.co.jp')); + $this->assertTrue(Validation::email('abc@g.cn')); + $this->assertTrue(Validation::email('abc@x.com')); + $this->assertTrue(Validation::email('henrik@sbcglobal.net')); + $this->assertTrue(Validation::email('sani@sbcglobal.net')); + + // all ICANN TLDs + $this->assertTrue(Validation::email('abc@example.aero')); + $this->assertTrue(Validation::email('abc@example.asia')); + $this->assertTrue(Validation::email('abc@example.biz')); + $this->assertTrue(Validation::email('abc@example.cat')); + $this->assertTrue(Validation::email('abc@example.com')); + $this->assertTrue(Validation::email('abc@example.coop')); + $this->assertTrue(Validation::email('abc@example.edu')); + $this->assertTrue(Validation::email('abc@example.gov')); + $this->assertTrue(Validation::email('abc@example.info')); + $this->assertTrue(Validation::email('abc@example.int')); + $this->assertTrue(Validation::email('abc@example.jobs')); + $this->assertTrue(Validation::email('abc@example.mil')); + $this->assertTrue(Validation::email('abc@example.mobi')); + $this->assertTrue(Validation::email('abc@example.museum')); + $this->assertTrue(Validation::email('abc@example.name')); + $this->assertTrue(Validation::email('abc@example.net')); + $this->assertTrue(Validation::email('abc@example.org')); + $this->assertTrue(Validation::email('abc@example.pro')); + $this->assertTrue(Validation::email('abc@example.tel')); + $this->assertTrue(Validation::email('abc@example.travel')); + $this->assertTrue(Validation::email('someone@st.t-com.hr')); + + // strange, but technically valid email addresses + $this->assertTrue(Validation::email('S=postmaster/OU=rz/P=uni-frankfurt/A=d400/C=de@gateway.d400.de')); + $this->assertTrue(Validation::email('customer/department=shipping@example.com')); + $this->assertTrue(Validation::email('$A12345@example.com')); + $this->assertTrue(Validation::email('!def!xyz%abc@example.com')); + $this->assertTrue(Validation::email('_somename@example.com')); + + // invalid addresses + $this->assertFalse(Validation::email('abc@example')); + $this->assertFalse(Validation::email('abc@example.c')); + $this->assertFalse(Validation::email('abc@example.com.')); + $this->assertFalse(Validation::email('abc.@example.com')); + $this->assertFalse(Validation::email('abc@example..com')); + $this->assertFalse(Validation::email('abc@example.com.a')); + $this->assertFalse(Validation::email('abc@example.toolong')); + $this->assertFalse(Validation::email('abc;@example.com')); + $this->assertFalse(Validation::email('abc@example.com;')); + $this->assertFalse(Validation::email('abc@efg@example.com')); + $this->assertFalse(Validation::email('abc@@example.com')); + $this->assertFalse(Validation::email('abc efg@example.com')); + $this->assertFalse(Validation::email('abc,efg@example.com')); + $this->assertFalse(Validation::email('abc@sub,example.com')); + $this->assertFalse(Validation::email("abc@sub'example.com")); + $this->assertFalse(Validation::email('abc@sub/example.com')); + $this->assertFalse(Validation::email('abc@yahoo!.com')); + $this->assertFalse(Validation::email("Nyrée.surname@example.com")); + $this->assertFalse(Validation::email('abc@example_underscored.com')); + $this->assertFalse(Validation::email('raw@test.ra.ru....com')); + } + +/** + * testEmailDeep method + * + * @return void + */ + public function testEmailDeep() { + $this->skipIf(gethostbynamel('example.abcd'), 'Your DNS service responds for non-existant domains, skipping deep email checks.'); + + $this->assertTrue(Validation::email('abc.efg@cakephp.org', true)); + $this->assertFalse(Validation::email('abc.efg@caphpkeinvalid.com', true)); + $this->assertFalse(Validation::email('abc@example.abcd', true)); + } + +/** + * testEmailCustomRegex method + * + * @return void + */ + public function testEmailCustomRegex() { + $this->assertTrue(Validation::email('abc.efg@cakephp.org', null, '/^[A-Z0-9._%-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}$/i')); + $this->assertFalse(Validation::email('abc.efg@com.caphpkeinvalid', null, '/^[A-Z0-9._%-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}$/i')); + } + +/** + * testEqualTo method + * + * @return void + */ + public function testEqualTo() { + $this->assertTrue(Validation::equalTo("1", "1")); + $this->assertFalse(Validation::equalTo(1, "1")); + $this->assertFalse(Validation::equalTo("", null)); + $this->assertFalse(Validation::equalTo("", false)); + $this->assertFalse(Validation::equalTo(0, false)); + $this->assertFalse(Validation::equalTo(null, false)); + } + +/** + * testIpV4 method + * + * @return void + */ + public function testIpV4() { + $this->assertTrue(Validation::ip('0.0.0.0', 'ipv4')); + $this->assertTrue(Validation::ip('192.168.1.156')); + $this->assertTrue(Validation::ip('255.255.255.255')); + $this->assertFalse(Validation::ip('127.0.0')); + $this->assertFalse(Validation::ip('127.0.0.a')); + $this->assertFalse(Validation::ip('127.0.0.256')); + $this->assertFalse(Validation::ip('2001:0db8:85a3:0000:0000:8a2e:0370:7334', 'ipv4'), 'IPv6 is not valid IPv4'); + } + +/** + * testIp v6 + * + * @return void + */ + public function testIpv6() { + $this->assertTrue(Validation::ip('2001:0db8:85a3:0000:0000:8a2e:0370:7334', 'IPv6')); + $this->assertTrue(Validation::ip('2001:db8:85a3:0:0:8a2e:370:7334', 'IPv6')); + $this->assertTrue(Validation::ip('2001:db8:85a3::8a2e:370:7334', 'IPv6')); + $this->assertTrue(Validation::ip('2001:0db8:0000:0000:0000:0000:1428:57ab', 'IPv6')); + $this->assertTrue(Validation::ip('2001:0db8:0000:0000:0000::1428:57ab', 'IPv6')); + $this->assertTrue(Validation::ip('2001:0db8:0:0:0:0:1428:57ab', 'IPv6')); + $this->assertTrue(Validation::ip('2001:0db8:0:0::1428:57ab', 'IPv6')); + $this->assertTrue(Validation::ip('2001:0db8::1428:57ab', 'IPv6')); + $this->assertTrue(Validation::ip('2001:db8::1428:57ab', 'IPv6')); + $this->assertTrue(Validation::ip('0000:0000:0000:0000:0000:0000:0000:0001', 'IPv6')); + $this->assertTrue(Validation::ip('::1', 'IPv6')); + $this->assertTrue(Validation::ip('::ffff:12.34.56.78', 'IPv6')); + $this->assertTrue(Validation::ip('::ffff:0c22:384e', 'IPv6')); + $this->assertTrue(Validation::ip('2001:0db8:1234:0000:0000:0000:0000:0000', 'IPv6')); + $this->assertTrue(Validation::ip('2001:0db8:1234:ffff:ffff:ffff:ffff:ffff', 'IPv6')); + $this->assertTrue(Validation::ip('2001:db8:a::123', 'IPv6')); + $this->assertTrue(Validation::ip('fe80::', 'IPv6')); + $this->assertTrue(Validation::ip('::ffff:192.0.2.128', 'IPv6')); + $this->assertTrue(Validation::ip('::ffff:c000:280', 'IPv6')); + + $this->assertFalse(Validation::ip('123', 'IPv6')); + $this->assertFalse(Validation::ip('ldkfj', 'IPv6')); + $this->assertFalse(Validation::ip('2001::FFD3::57ab', 'IPv6')); + $this->assertFalse(Validation::ip('2001:db8:85a3::8a2e:37023:7334', 'IPv6')); + $this->assertFalse(Validation::ip('2001:db8:85a3::8a2e:370k:7334', 'IPv6')); + $this->assertFalse(Validation::ip('1:2:3:4:5:6:7:8:9', 'IPv6')); + $this->assertFalse(Validation::ip('1::2::3', 'IPv6')); + $this->assertFalse(Validation::ip('1:::3:4:5', 'IPv6')); + $this->assertFalse(Validation::ip('1:2:3::4:5:6:7:8:9', 'IPv6')); + $this->assertFalse(Validation::ip('::ffff:2.3.4', 'IPv6')); + $this->assertFalse(Validation::ip('::ffff:257.1.2.3', 'IPv6')); + $this->assertFalse(Validation::ip('255.255.255.255', 'ipv6'), 'IPv4 is not valid IPv6'); + } + +/** + * testMaxLength method + * + * @return void + */ + public function testMaxLength() { + $this->assertTrue(Validation::maxLength('ab', 3)); + $this->assertTrue(Validation::maxLength('abc', 3)); + $this->assertTrue(Validation::maxLength('ÆΔΩЖÇ', 10)); + + $this->assertFalse(Validation::maxLength('abcd', 3)); + $this->assertFalse(Validation::maxLength('ÆΔΩЖÇ', 3)); + } + +/** + * testMinLength method + * + * @return void + */ + public function testMinLength() { + $this->assertFalse(Validation::minLength('ab', 3)); + $this->assertFalse(Validation::minLength('ÆΔΩЖÇ', 10)); + + $this->assertTrue(Validation::minLength('abc', 3)); + $this->assertTrue(Validation::minLength('abcd', 3)); + $this->assertTrue(Validation::minLength('ÆΔΩЖÇ', 2)); + } + +/** + * testUrl method + * + * @return void + */ + public function testUrl() { + $this->assertTrue(Validation::url('http://www.cakephp.org')); + $this->assertTrue(Validation::url('http://cakephp.org')); + $this->assertTrue(Validation::url('http://www.cakephp.org/somewhere#anchor')); + $this->assertTrue(Validation::url('http://192.168.0.1')); + $this->assertTrue(Validation::url('https://www.cakephp.org')); + $this->assertTrue(Validation::url('https://cakephp.org')); + $this->assertTrue(Validation::url('https://www.cakephp.org/somewhere#anchor')); + $this->assertTrue(Validation::url('https://192.168.0.1')); + $this->assertTrue(Validation::url('ftps://www.cakephp.org/pub/cake')); + $this->assertTrue(Validation::url('ftps://cakephp.org/pub/cake')); + $this->assertTrue(Validation::url('ftps://192.168.0.1/pub/cake')); + $this->assertTrue(Validation::url('ftp://www.cakephp.org/pub/cake')); + $this->assertTrue(Validation::url('ftp://cakephp.org/pub/cake')); + $this->assertTrue(Validation::url('ftp://192.168.0.1/pub/cake')); + $this->assertTrue(Validation::url('sftp://192.168.0.1/pub/cake')); + $this->assertFalse(Validation::url('ftps://256.168.0.1/pub/cake')); + $this->assertFalse(Validation::url('ftp://256.168.0.1/pub/cake')); + $this->assertTrue(Validation::url('https://my.domain.com/gizmo/app?class=MySip;proc=start')); + $this->assertTrue(Validation::url('www.domain.tld')); + $this->assertFalse(Validation::url('http://w_w.domain.co_m')); + $this->assertFalse(Validation::url('http://www.domain.12com')); + $this->assertFalse(Validation::url('http://www.domain.longttldnotallowed')); + $this->assertFalse(Validation::url('http://www.-invaliddomain.tld')); + $this->assertFalse(Validation::url('http://www.domain.-invalidtld')); + $this->assertTrue(Validation::url('http://123456789112345678921234567893123456789412345678951234567896123.com')); + $this->assertFalse(Validation::url('http://this-domain-is-too-loooooong-by-icann-rules-maximum-length-is-63.com')); + $this->assertTrue(Validation::url('http://www.domain.com/blogs/index.php?blog=6&tempskin=_rss2')); + $this->assertTrue(Validation::url('http://www.domain.com/blogs/parenth()eses.php')); + $this->assertTrue(Validation::url('http://www.domain.com/index.php?get=params&get2=params')); + $this->assertTrue(Validation::url('http://www.domain.com/ndex.php?get=params&get2=params#anchor')); + $this->assertFalse(Validation::url('http://www.domain.com/fakeenco%ode')); + $this->assertTrue(Validation::url('http://www.domain.com/real%20url%20encodeing')); + $this->assertTrue(Validation::url('http://en.wikipedia.org/wiki/Architectural_pattern_(computer_science)')); + $this->assertFalse(Validation::url('http://en.(wikipedia).org/')); + $this->assertFalse(Validation::url('www.cakephp.org', true)); + $this->assertTrue(Validation::url('http://www.cakephp.org', true)); + $this->assertTrue(Validation::url('http://example.com/~userdir/')); + + $this->assertTrue(Validation::url('http://example.com/~userdir/subdir/index.html')); + $this->assertTrue(Validation::url('http://www.zwischenraume.de')); + $this->assertTrue(Validation::url('http://www.zwischenraume.cz')); + $this->assertTrue(Validation::url('http://www.last.fm/music/浜崎あゆみ'), 'utf8 path failed'); + $this->assertTrue(Validation::url('http://www.electrohome.ro/images/239537750-284232-215_300[1].jpg')); + + $this->assertTrue(Validation::url('http://cakephp.org:80')); + $this->assertTrue(Validation::url('http://cakephp.org:443')); + $this->assertTrue(Validation::url('http://cakephp.org:2000')); + $this->assertTrue(Validation::url('http://cakephp.org:27000')); + $this->assertTrue(Validation::url('http://cakephp.org:65000')); + + $this->assertTrue(Validation::url('[2001:0db8::1428:57ab]')); + $this->assertTrue(Validation::url('[::1]')); + $this->assertTrue(Validation::url('[2001:0db8::1428:57ab]:80')); + $this->assertTrue(Validation::url('[::1]:80')); + $this->assertTrue(Validation::url('http://[2001:0db8::1428:57ab]')); + $this->assertTrue(Validation::url('http://[::1]')); + $this->assertTrue(Validation::url('http://[2001:0db8::1428:57ab]:80')); + $this->assertTrue(Validation::url('http://[::1]:80')); + + $this->assertFalse(Validation::url('[1::2::3]')); + } + + public function testUuid() { + $this->assertTrue(Validation::uuid('550e8400-e29b-11d4-a716-446655440000')); + $this->assertFalse(Validation::uuid('BRAP-e29b-11d4-a716-446655440000')); + $this->assertTrue(Validation::uuid('550E8400-e29b-11D4-A716-446655440000')); + $this->assertFalse(Validation::uuid('550e8400-e29b11d4-a716-446655440000')); + $this->assertFalse(Validation::uuid('550e8400-e29b-11d4-a716-4466440000')); + $this->assertFalse(Validation::uuid('550e8400-e29b-11d4-a71-446655440000')); + $this->assertFalse(Validation::uuid('550e8400-e29b-11d-a716-446655440000')); + $this->assertFalse(Validation::uuid('550e8400-e29-11d4-a716-446655440000')); + } + +/** + * testInList method + * + * @return void + */ + public function testInList() { + $this->assertTrue(Validation::inList('one', array('one', 'two'))); + $this->assertTrue(Validation::inList('two', array('one', 'two'))); + $this->assertFalse(Validation::inList('three', array('one', 'two'))); + $this->assertFalse(Validation::inList('1one', array(0, 1, 2, 3))); + $this->assertFalse(Validation::inList('one', array(0, 1, 2, 3))); + $this->assertFalse(Validation::inList('2', array(1, 2, 3))); + $this->assertTrue(Validation::inList('2', array(1, 2, 3), false)); + } + +/** + * testRange method + * + * @return void + */ + public function testRange() { + $this->assertFalse(Validation::range(20, 100, 1)); + $this->assertTrue(Validation::range(20, 1, 100)); + $this->assertFalse(Validation::range(.5, 1, 100)); + $this->assertTrue(Validation::range(.5, 0, 100)); + $this->assertTrue(Validation::range(5)); + $this->assertTrue(Validation::range(-5, -10, 1)); + $this->assertFalse(Validation::range('word')); + } + +/** + * testExtension method + * + * @return void + */ + public function testExtension() { + $this->assertTrue(Validation::extension('extension.jpeg')); + $this->assertTrue(Validation::extension('extension.JPEG')); + $this->assertTrue(Validation::extension('extension.gif')); + $this->assertTrue(Validation::extension('extension.GIF')); + $this->assertTrue(Validation::extension('extension.png')); + $this->assertTrue(Validation::extension('extension.jpg')); + $this->assertTrue(Validation::extension('extension.JPG')); + $this->assertFalse(Validation::extension('noextension')); + $this->assertTrue(Validation::extension('extension.pdf', array('PDF'))); + $this->assertFalse(Validation::extension('extension.jpg', array('GIF'))); + $this->assertTrue(Validation::extension(array('extension.JPG', 'extension.gif', 'extension.png'))); + $this->assertTrue(Validation::extension(array('file' => array('name' => 'file.jpg')))); + $this->assertTrue(Validation::extension(array('file1' => array('name' => 'file.jpg'), + 'file2' => array('name' => 'file.jpg'), + 'file3' => array('name' => 'file.jpg')))); + $this->assertFalse(Validation::extension(array('file1' => array('name' => 'file.jpg'), + 'file2' => array('name' => 'file.jpg'), + 'file3' => array('name' => 'file.jpg')), array('gif'))); + + $this->assertFalse(Validation::extension(array('noextension', 'extension.JPG', 'extension.gif', 'extension.png'))); + $this->assertFalse(Validation::extension(array('extension.pdf', 'extension.JPG', 'extension.gif', 'extension.png'))); + } + +/** + * testMoney method + * + * @return void + */ + public function testMoney() { + $this->assertTrue(Validation::money('$100')); + $this->assertTrue(Validation::money('$100.11')); + $this->assertTrue(Validation::money('$100.112')); + $this->assertFalse(Validation::money('$100.1')); + $this->assertFalse(Validation::money('$100.1111')); + $this->assertFalse(Validation::money('text')); + + $this->assertTrue(Validation::money('100', 'right')); + $this->assertTrue(Validation::money('100.11$', 'right')); + $this->assertTrue(Validation::money('100.112$', 'right')); + $this->assertFalse(Validation::money('100.1$', 'right')); + $this->assertFalse(Validation::money('100.1111$', 'right')); + + $this->assertTrue(Validation::money('€100')); + $this->assertTrue(Validation::money('€100.11')); + $this->assertTrue(Validation::money('€100.112')); + $this->assertFalse(Validation::money('€100.1')); + $this->assertFalse(Validation::money('€100.1111')); + + $this->assertTrue(Validation::money('100', 'right')); + $this->assertTrue(Validation::money('100.11€', 'right')); + $this->assertTrue(Validation::money('100.112€', 'right')); + $this->assertFalse(Validation::money('100.1€', 'right')); + $this->assertFalse(Validation::money('100.1111€', 'right')); + } + +/** + * Test Multiple Select Validation + * + * @return void + */ + public function testMultiple() { + $this->assertTrue(Validation::multiple(array(0, 1, 2, 3))); + $this->assertTrue(Validation::multiple(array(50, 32, 22, 0))); + $this->assertTrue(Validation::multiple(array('str', 'var', 'enum', 0))); + $this->assertFalse(Validation::multiple('')); + $this->assertFalse(Validation::multiple(null)); + $this->assertFalse(Validation::multiple(array())); + $this->assertFalse(Validation::multiple(array(0))); + $this->assertFalse(Validation::multiple(array('0'))); + + $this->assertTrue(Validation::multiple(array(0, 3, 4, 5), array('in' => range(0, 10)))); + $this->assertFalse(Validation::multiple(array(0, 15, 20, 5), array('in' => range(0, 10)))); + $this->assertFalse(Validation::multiple(array(0, 5, 10, 11), array('in' => range(0, 10)))); + $this->assertFalse(Validation::multiple(array('boo', 'foo', 'bar'), array('in' => array('foo', 'bar', 'baz')))); + $this->assertFalse(Validation::multiple(array('foo', '1bar'), array('in' => range(0, 10)))); + + $this->assertTrue(Validation::multiple(array(0, 5, 10, 11), array('max' => 3))); + $this->assertFalse(Validation::multiple(array(0, 5, 10, 11, 55), array('max' => 3))); + $this->assertTrue(Validation::multiple(array('foo', 'bar', 'baz'), array('max' => 3))); + $this->assertFalse(Validation::multiple(array('foo', 'bar', 'baz', 'squirrel'), array('max' => 3))); + + $this->assertTrue(Validation::multiple(array(0, 5, 10, 11), array('min' => 3))); + $this->assertTrue(Validation::multiple(array(0, 5, 10, 11, 55), array('min' => 3))); + $this->assertFalse(Validation::multiple(array('foo', 'bar', 'baz'), array('min' => 5))); + $this->assertFalse(Validation::multiple(array('foo', 'bar', 'baz', 'squirrel'), array('min' => 10))); + + $this->assertTrue(Validation::multiple(array(0, 5, 9), array('in' => range(0, 10), 'max' => 5))); + $this->assertFalse(Validation::multiple(array('0', '5', '9'), array('in' => range(0, 10), 'max' => 5))); + $this->assertTrue(Validation::multiple(array('0', '5', '9'), array('in' => range(0, 10), 'max' => 5), false)); + $this->assertFalse(Validation::multiple(array(0, 5, 9, 8, 6, 2, 1), array('in' => range(0, 10), 'max' => 5))); + $this->assertFalse(Validation::multiple(array(0, 5, 9, 8, 11), array('in' => range(0, 10), 'max' => 5))); + + $this->assertFalse(Validation::multiple(array(0, 5, 9), array('in' => range(0, 10), 'max' => 5, 'min' => 3))); + $this->assertFalse(Validation::multiple(array(0, 5, 9, 8, 6, 2, 1), array('in' => range(0, 10), 'max' => 5, 'min' => 2))); + $this->assertFalse(Validation::multiple(array(0, 5, 9, 8, 11), array('in' => range(0, 10), 'max' => 5, 'min' => 2))); + } + +/** + * testNumeric method + * + * @return void + */ + public function testNumeric() { + $this->assertFalse(Validation::numeric('teststring')); + $this->assertFalse(Validation::numeric('1.1test')); + $this->assertFalse(Validation::numeric('2test')); + + $this->assertTrue(Validation::numeric('2')); + $this->assertTrue(Validation::numeric(2)); + $this->assertTrue(Validation::numeric(2.2)); + $this->assertTrue(Validation::numeric('2.2')); + } + +/** + * testNaturalNumber method + * + * @return void + */ + public function testNaturalNumber() { + $this->assertFalse(Validation::naturalNumber('teststring')); + $this->assertFalse(Validation::naturalNumber('5.4')); + $this->assertFalse(Validation::naturalNumber(99.004)); + $this->assertFalse(Validation::naturalNumber('0,05')); + $this->assertFalse(Validation::naturalNumber('-2')); + $this->assertFalse(Validation::naturalNumber(-2)); + $this->assertFalse(Validation::naturalNumber('0')); + $this->assertFalse(Validation::naturalNumber('050')); + + $this->assertTrue(Validation::naturalNumber('2')); + $this->assertTrue(Validation::naturalNumber(49)); + $this->assertTrue(Validation::naturalNumber('0', true)); + $this->assertTrue(Validation::naturalNumber(0, true)); + } + +/** + * testPhone method + * + * @return void + */ + public function testPhone() { + $this->assertFalse(Validation::phone('teststring')); + $this->assertFalse(Validation::phone('1-(33)-(333)-(4444)')); + $this->assertFalse(Validation::phone('1-(33)-3333-4444')); + $this->assertFalse(Validation::phone('1-(33)-33-4444')); + $this->assertFalse(Validation::phone('1-(33)-3-44444')); + $this->assertFalse(Validation::phone('1-(33)-3-444')); + $this->assertFalse(Validation::phone('1-(33)-3-44')); + + $this->assertFalse(Validation::phone('(055) 999-9999')); + $this->assertFalse(Validation::phone('(155) 999-9999')); + $this->assertFalse(Validation::phone('(595) 999-9999')); + $this->assertFalse(Validation::phone('(555) 099-9999')); + $this->assertFalse(Validation::phone('(555) 199-9999')); + + $this->assertTrue(Validation::phone('1 (222) 333 4444')); + $this->assertTrue(Validation::phone('+1 (222) 333 4444')); + $this->assertTrue(Validation::phone('(222) 333 4444')); + + $this->assertTrue(Validation::phone('1-(333)-333-4444')); + $this->assertTrue(Validation::phone('1.(333)-333-4444')); + $this->assertTrue(Validation::phone('1.(333).333-4444')); + $this->assertTrue(Validation::phone('1.(333).333.4444')); + $this->assertTrue(Validation::phone('1-333-333-4444')); + } + +/** + * testPostal method + * + * @return void + */ + public function testPostal() { + $this->assertFalse(Validation::postal('111', null, 'de')); + $this->assertFalse(Validation::postal('1111', null, 'de')); + $this->assertTrue(Validation::postal('13089', null, 'de')); + + $this->assertFalse(Validation::postal('111', null, 'be')); + $this->assertFalse(Validation::postal('0123', null, 'be')); + $this->assertTrue(Validation::postal('1204', null, 'be')); + + $this->assertFalse(Validation::postal('111', null, 'it')); + $this->assertFalse(Validation::postal('1111', null, 'it')); + $this->assertTrue(Validation::postal('13089', null, 'it')); + + $this->assertFalse(Validation::postal('111', null, 'uk')); + $this->assertFalse(Validation::postal('1111', null, 'uk')); + $this->assertFalse(Validation::postal('AZA 0AB', null, 'uk')); + $this->assertFalse(Validation::postal('X0A 0ABC', null, 'uk')); + $this->assertTrue(Validation::postal('X0A 0AB', null, 'uk')); + $this->assertTrue(Validation::postal('AZ0A 0AA', null, 'uk')); + $this->assertTrue(Validation::postal('A89 2DD', null, 'uk')); + + $this->assertFalse(Validation::postal('111', null, 'ca')); + $this->assertFalse(Validation::postal('1111', null, 'ca')); + $this->assertFalse(Validation::postal('D2A 0A0', null, 'ca')); + $this->assertFalse(Validation::postal('BAA 0ABC', null, 'ca')); + $this->assertFalse(Validation::postal('B2A AABC', null, 'ca')); + $this->assertFalse(Validation::postal('B2A 2AB', null, 'ca')); + $this->assertTrue(Validation::postal('X0A 0A2', null, 'ca')); + $this->assertTrue(Validation::postal('G4V 4C3', null, 'ca')); + + $this->assertFalse(Validation::postal('111', null, 'us')); + $this->assertFalse(Validation::postal('1111', null, 'us')); + $this->assertFalse(Validation::postal('130896', null, 'us')); + $this->assertFalse(Validation::postal('13089-33333', null, 'us')); + $this->assertFalse(Validation::postal('13089-333', null, 'us')); + $this->assertFalse(Validation::postal('13A89-4333', null, 'us')); + $this->assertTrue(Validation::postal('13089-3333', null, 'us')); + + $this->assertFalse(Validation::postal('111')); + $this->assertFalse(Validation::postal('1111')); + $this->assertFalse(Validation::postal('130896')); + $this->assertFalse(Validation::postal('13089-33333')); + $this->assertFalse(Validation::postal('13089-333')); + $this->assertFalse(Validation::postal('13A89-4333')); + $this->assertTrue(Validation::postal('13089-3333')); + } + +/** + * test that phone and postal pass to other classes. + * + * @return void + */ + public function testPhonePostalSsnPass() { + $this->assertTrue(Validation::postal('text', null, 'testNl')); + $this->assertTrue(Validation::phone('text', null, 'testDe')); + $this->assertTrue(Validation::ssn('text', null, 'testNl')); + } + +/** + * test pass through failure on postal + * + * @expectedException PHPUnit_Framework_Error + * @return void + */ + public function testPassThroughMethodFailure() { + Validation::phone('text', null, 'testNl'); + } + +/** + * test the pass through calling of an alternate locale with postal() + * + * @expectedException PHPUnit_Framework_Error + * @return void + **/ + public function testPassThroughClassFailure() { + Validation::postal('text', null, 'AUTOFAIL'); + } + +/** + * test pass through method + * + * @return void + */ + public function testPassThroughMethod() { + $this->assertTrue(Validation::postal('text', null, 'testNl')); + } + +/** + * testSsn method + * + * @return void + */ + public function testSsn() { + $this->assertFalse(Validation::ssn('111-333', null, 'dk')); + $this->assertFalse(Validation::ssn('111111-333', null, 'dk')); + $this->assertTrue(Validation::ssn('111111-3334', null, 'dk')); + + $this->assertFalse(Validation::ssn('1118333', null, 'nl')); + $this->assertFalse(Validation::ssn('1234567890', null, 'nl')); + $this->assertFalse(Validation::ssn('12345A789', null, 'nl')); + $this->assertTrue(Validation::ssn('123456789', null, 'nl')); + + $this->assertFalse(Validation::ssn('11-33-4333', null, 'us')); + $this->assertFalse(Validation::ssn('113-3-4333', null, 'us')); + $this->assertFalse(Validation::ssn('111-33-333', null, 'us')); + $this->assertTrue(Validation::ssn('111-33-4333', null, 'us')); + } + +/** + * testUserDefined method + * + * @return void + */ + public function testUserDefined() { + $validator = new CustomValidator; + $this->assertFalse(Validation::userDefined('33', $validator, 'customValidate')); + $this->assertFalse(Validation::userDefined('3333', $validator, 'customValidate')); + $this->assertTrue(Validation::userDefined('333', $validator, 'customValidate')); + } + +/** + * testDatetime method + * + * @return void + */ + public function testDatetime() { + $this->assertTrue(Validation::datetime('27-12-2006 01:00', 'dmy')); + $this->assertTrue(Validation::datetime('27-12-2006 01:00', array('dmy'))); + $this->assertFalse(Validation::datetime('27-12-2006 1:00', 'dmy')); + + $this->assertTrue(Validation::datetime('27.12.2006 1:00pm', 'dmy')); + $this->assertFalse(Validation::datetime('27.12.2006 13:00pm', 'dmy')); + + $this->assertTrue(Validation::datetime('27/12/2006 1:00pm', 'dmy')); + $this->assertFalse(Validation::datetime('27/12/2006 9:00', 'dmy')); + + $this->assertTrue(Validation::datetime('27 12 2006 1:00pm', 'dmy')); + $this->assertFalse(Validation::datetime('27 12 2006 24:00', 'dmy')); + + $this->assertFalse(Validation::datetime('00-00-0000 1:00pm', 'dmy')); + $this->assertFalse(Validation::datetime('00.00.0000 1:00pm', 'dmy')); + $this->assertFalse(Validation::datetime('00/00/0000 1:00pm', 'dmy')); + $this->assertFalse(Validation::datetime('00 00 0000 1:00pm', 'dmy')); + $this->assertFalse(Validation::datetime('31-11-2006 1:00pm', 'dmy')); + $this->assertFalse(Validation::datetime('31.11.2006 1:00pm', 'dmy')); + $this->assertFalse(Validation::datetime('31/11/2006 1:00pm', 'dmy')); + $this->assertFalse(Validation::datetime('31 11 2006 1:00pm', 'dmy')); + } + +/** + * testMimeType method + * + * @return void + */ + public function testMimeType() { + $image = CORE_PATH . 'Cake' . DS . 'Test' . DS . 'test_app' . DS . 'webroot' . DS . 'img' . DS . 'cake.power.gif'; + $File = new File($image, false); + $this->skipIf(!$File->mime(), 'Cannot determine mimeType'); + $this->assertTrue(Validation::mimeType($image, array('image/gif'))); + $this->assertTrue(Validation::mimeType(array('tmp_name' => $image), array('image/gif'))); + + $this->assertFalse(Validation::mimeType($image, array('image/png'))); + $this->assertFalse(Validation::mimeType(array('tmp_name' => $image), array('image/png'))); + } + +/** + * testMimeTypeFalse method + * + * @expectedException CakeException + * @return void + */ + public function testMimeTypeFalse() { + $image = CORE_PATH . 'Cake' . DS . 'Test' . DS . 'test_app' . DS . 'webroot' . DS . 'img' . DS . 'cake.power.gif'; + $File = new File($image, false); + $this->skipIf($File->mime(), 'mimeType can be determined, no Exception will be thrown'); + Validation::mimeType($image, array('image/gif')); + } + +/** + * testMimeType method + * + * @return void + */ + public function testUploadError() { + $this->assertTrue(Validation::uploadError(0)); + $this->assertTrue(Validation::uploadError(array('error' => 0))); + + $this->assertFalse(Validation::uploadError(2)); + $this->assertFalse(Validation::uploadError(array('error' => 2))); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Utility/XmlTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Utility/XmlTest.php new file mode 100644 index 0000000..7108d75 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/Utility/XmlTest.php @@ -0,0 +1,1064 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.Utility + * @since CakePHP(tm) v 1.2.0.5432 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ +App::uses('Xml', 'Utility'); +App::uses('CakeTestModel', 'TestSuite/Fixture'); + +/** + * Article class + * + * @package Cake.Test.Case.Utility + */ +class XmlArticle extends CakeTestModel { + +/** + * name property + * + * @var string 'Article' + */ + public $name = 'Article'; + +/** + * belongsTo property + * + * @var array + */ + public $belongsTo = array( + 'User' => array( + 'className' => 'XmlUser', + 'foreignKey' => 'user_id' + ) + ); +} + +/** + * User class + * + * @package Cake.Test.Case.Utility + */ +class XmlUser extends CakeTestModel { + +/** + * name property + * + * @var string 'User' + */ + public $name = 'User'; + +/** + * hasMany property + * + * @var array + */ + public $hasMany = array( + 'Article' => array( + 'className' => 'XmlArticle' + ) + ); +} + +/** + * XmlTest class + * + * @package Cake.Test.Case.Utility + */ +class XmlTest extends CakeTestCase { + +/** + * autoFixtures property + * + * @var bool false + */ + public $autoFixtures = false; + +/** + * fixtures property + * @var array + */ + public $fixtures = array( + 'core.article', 'core.user' + ); + +/** + * setUp method + * + * @return void + */ + public function setUp() { + parent::setUp(); + $this->_appEncoding = Configure::read('App.encoding'); + Configure::write('App.encoding', 'UTF-8'); + } + +/** + * tearDown method + * + * @return void + */ + public function tearDown() { + parent::tearDown(); + Configure::write('App.encoding', $this->_appEncoding); + } + +/** + * testBuild method + * + * @return void + */ + public function testBuild() { + $xml = 'value'; + $obj = Xml::build($xml); + $this->assertTrue($obj instanceof SimpleXMLElement); + $this->assertEquals('tag', (string)$obj->getName()); + $this->assertEquals('value', (string)$obj); + + $xml = 'value'; + $this->assertEquals($obj, Xml::build($xml)); + + $obj = Xml::build($xml, array('return' => 'domdocument')); + $this->assertTrue($obj instanceof DOMDocument); + $this->assertEquals('tag', $obj->firstChild->nodeName); + $this->assertEquals('value', $obj->firstChild->nodeValue); + + $xml = CAKE . 'Test' . DS . 'Fixture' . DS . 'sample.xml'; + $obj = Xml::build($xml); + $this->assertEquals('tags', $obj->getName()); + $this->assertEquals(2, count($obj)); + + $this->assertEquals(Xml::build($xml), Xml::build(file_get_contents($xml))); + + $obj = Xml::build($xml, array('return' => 'domdocument')); + $this->assertEquals('tags', $obj->firstChild->nodeName); + + $this->assertEquals( + Xml::build($xml, array('return' => 'domdocument')), + Xml::build(file_get_contents($xml), array('return' => 'domdocument')) + ); + $this->assertEquals( + Xml::build($xml, array('return' => 'simplexml')), + Xml::build($xml, 'simplexml') + ); + + $xml = array('tag' => 'value'); + $obj = Xml::build($xml); + $this->assertEquals('tag', $obj->getName()); + $this->assertEquals('value', (string)$obj); + + $obj = Xml::build($xml, array('return' => 'domdocument')); + $this->assertEquals('tag', $obj->firstChild->nodeName); + $this->assertEquals('value', $obj->firstChild->nodeValue); + + $obj = Xml::build($xml, array('return' => 'domdocument', 'encoding' => null)); + $this->assertNotRegExp('/encoding/', $obj->saveXML()); + } + +/** + * data provider function for testBuildInvalidData + * + * @return array + */ + public static function invalidDataProvider() { + return array( + array(null), + array(false), + array(''), + ); + } + +/** + * testBuildInvalidData + * + * @dataProvider invalidDataProvider + * @expectedException XmlException + * return void + */ + public function testBuildInvalidData($value) { + Xml::build($value); + } + +/** + * test build with a single empty tag + * + * return void + */ + public function testBuildEmptyTag() { + try { + Xml::build(''); + $this->fail('No exception'); + } catch (Exception $e) { + $this->assertTrue(true, 'An exception was raised'); + } + } + +/** + * testFromArray method + * + * @return void + */ + public function testFromArray() { + $xml = array('tag' => 'value'); + $obj = Xml::fromArray($xml); + $this->assertEquals('tag', $obj->getName()); + $this->assertEquals('value', (string)$obj); + + $xml = array('tag' => null); + $obj = Xml::fromArray($xml); + $this->assertEquals('tag', $obj->getName()); + $this->assertEquals('', (string)$obj); + + $xml = array('tag' => array('@' => 'value')); + $obj = Xml::fromArray($xml); + $this->assertEquals('tag', $obj->getName()); + $this->assertEquals('value', (string)$obj); + + $xml = array( + 'tags' => array( + 'tag' => array( + array( + 'id' => '1', + 'name' => 'defect' + ), + array( + 'id' => '2', + 'name' => 'enhancement' + ) + ) + ) + ); + $obj = Xml::fromArray($xml, 'attributes'); + $this->assertTrue($obj instanceof SimpleXMLElement); + $this->assertEquals('tags', $obj->getName()); + $this->assertEquals(2, count($obj)); + $xmlText = << + + + + +XML; + $this->assertXmlStringEqualsXmlString($xmlText, $obj->asXML()); + + $obj = Xml::fromArray($xml); + $this->assertTrue($obj instanceof SimpleXMLElement); + $this->assertEquals('tags', $obj->getName()); + $this->assertEquals(2, count($obj)); + $xmlText = << + + + 1 + defect + + + 2 + enhancement + + +XML; + $this->assertXmlStringEqualsXmlString($xmlText, $obj->asXML()); + + $xml = array( + 'tags' => array( + ) + ); + $obj = Xml::fromArray($xml); + $this->assertEquals('tags', $obj->getName()); + $this->assertEquals('', (string)$obj); + + $xml = array( + 'tags' => array( + 'bool' => true, + 'int' => 1, + 'float' => 10.2, + 'string' => 'ok', + 'null' => null, + 'array' => array() + ) + ); + $obj = Xml::fromArray($xml, 'tags'); + $this->assertEquals(6, count($obj)); + $this->assertSame((string)$obj->bool, '1'); + $this->assertSame((string)$obj->int, '1'); + $this->assertSame((string)$obj->float, '10.2'); + $this->assertSame((string)$obj->string, 'ok'); + $this->assertSame((string)$obj->null, ''); + $this->assertSame((string)$obj->array, ''); + + $xml = array( + 'tags' => array( + 'tag' => array( + array( + '@id' => '1', + 'name' => 'defect' + ), + array( + '@id' => '2', + 'name' => 'enhancement' + ) + ) + ) + ); + $obj = Xml::fromArray($xml, 'tags'); + $xmlText = << + + + defect + + + enhancement + + +XML; + $this->assertXmlStringEqualsXmlString($xmlText, $obj->asXML()); + + $xml = array( + 'tags' => array( + 'tag' => array( + array( + '@id' => '1', + 'name' => 'defect', + '@' => 'Tag 1' + ), + array( + '@id' => '2', + 'name' => 'enhancement' + ), + ), + '@' => 'All tags' + ) + ); + $obj = Xml::fromArray($xml, 'tags'); + $xmlText = << +All tagsTag 1defectenhancement +XML; + $this->assertXmlStringEqualsXmlString($xmlText, $obj->asXML()); + + $xml = array( + 'tags' => array( + 'tag' => array( + 'id' => 1, + '@' => 'defect' + ) + ) + ); + $obj = Xml::fromArray($xml, 'attributes'); + $xmlText = '<' . '?xml version="1.0" encoding="UTF-8"?>defect'; + $this->assertXmlStringEqualsXmlString($xmlText, $obj->asXML()); + } + +/** + * Test non-sequential keys in list types. + * + * @return void + */ + public function testFromArrayNonSequentialKeys() { + $xmlArray = array( + 'Event' => array( + array( + 'id' => '235', + 'Attribute' => array( + 0 => array( + 'id' => '9646', + ), + 2 => array( + 'id' => '9647', + ) + ) + ) + ) + ); + $obj = Xml::fromArray($xmlArray); + $expected = << + + 235 + + 9646 + + + 9647 + + +XML; + $this->assertXmlStringEqualsXmlString($expected, $obj->asXML()); + } + +/** + * data provider for fromArray() failures + * + * @return array + */ + public static function invalidArrayDataProvider() { + return array( + array(''), + array(null), + array(false), + array(array()), + array(array('numeric key as root')), + array(array('item1' => '', 'item2' => '')), + array(array('items' => array('item1', 'item2'))), + array(array( + 'tags' => array( + 'tag' => array( + array( + array( + 'string' + ) + ) + ) + ) + )), + array(array( + 'tags' => array( + '@tag' => array( + array( + '@id' => '1', + 'name' => 'defect' + ), + array( + '@id' => '2', + 'name' => 'enhancement' + ) + ) + ) + )), + array(new DateTime()) + ); + } + +/** + * testFromArrayFail method + * + * @dataProvider invalidArrayDataProvider + */ + public function testFromArrayFail($value) { + try { + Xml::fromArray($value); + $this->fail('No exception.'); + } catch (Exception $e) { + $this->assertTrue(true, 'Caught exception.'); + } + } + +/** + * testToArray method + * + * @return void + */ + public function testToArray() { + $xml = 'name'; + $obj = Xml::build($xml); + $this->assertEquals(array('tag' => 'name'), Xml::toArray($obj)); + + $xml = CAKE . 'Test' . DS . 'Fixture' . DS . 'sample.xml'; + $obj = Xml::build($xml); + $expected = array( + 'tags' => array( + 'tag' => array( + array( + '@id' => '1', + 'name' => 'defect' + ), + array( + '@id' => '2', + 'name' => 'enhancement' + ) + ) + ) + ); + $this->assertEquals($expected, Xml::toArray($obj)); + + $array = array( + 'tags' => array( + 'tag' => array( + array( + 'id' => '1', + 'name' => 'defect' + ), + array( + 'id' => '2', + 'name' => 'enhancement' + ) + ) + ) + ); + $this->assertEquals(Xml::toArray(Xml::fromArray($array, 'tags')), $array); + + $expected = array( + 'tags' => array( + 'tag' => array( + array( + '@id' => '1', + '@name' => 'defect' + ), + array( + '@id' => '2', + '@name' => 'enhancement' + ) + ) + ) + ); + $this->assertEquals($expected, Xml::toArray(Xml::fromArray($array, 'attributes'))); + $this->assertEquals($expected, Xml::toArray(Xml::fromArray($array, array('return' => 'domdocument', 'format' => 'attributes')))); + $this->assertEquals(Xml::toArray(Xml::fromArray($array)), $array); + $this->assertEquals(Xml::toArray(Xml::fromArray($array, array('return' => 'domdocument'))), $array); + + $array = array( + 'tags' => array( + 'tag' => array( + 'id' => '1', + 'posts' => array( + array('id' => '1'), + array('id' => '2') + ) + ), + 'tagOther' => array( + 'subtag' => array( + 'id' => '1' + ) + ) + ) + ); + $expected = array( + 'tags' => array( + 'tag' => array( + '@id' => '1', + 'posts' => array( + array('@id' => '1'), + array('@id' => '2') + ) + ), + 'tagOther' => array( + 'subtag' => array( + '@id' => '1' + ) + ) + ) + ); + $this->assertEquals($expected, Xml::toArray(Xml::fromArray($array, 'attributes'))); + $this->assertEquals($expected, Xml::toArray(Xml::fromArray($array, array('format' => 'attributes', 'return' => 'domdocument')))); + + $xml = << +defect + +XML; + $obj = Xml::build($xml); + + $expected = array( + 'root' => array( + 'tag' => array( + '@id' => 1, + '@' => 'defect' + ) + ) + ); + $this->assertEquals($expected, Xml::toArray($obj)); + + $xml = << +
ApplesBananas
+ CakePHPMIT
+ The book is on the table.
+ +XML; + $obj = Xml::build($xml); + + $expected = array( + 'root' => array( + 'table' => array( + array('tr' => array('td' => array('Apples', 'Bananas'))), + array('name' => 'CakePHP', 'license' => 'MIT'), + 'The book is on the table.' + ) + ) + ); + $this->assertEquals($expected, Xml::toArray($obj)); + + $xml = << +defect +1 + +XML; + $obj = Xml::build($xml); + + $expected = array( + 'root' => array( + 'tag' => 'defect', + 'cake:bug' => 1 + ) + ); + $this->assertEquals($expected, Xml::toArray($obj)); + } + +/** + * testRss + * + * @return void + */ + public function testRss() { + $rss = file_get_contents(CAKE . 'Test' . DS . 'Fixture' . DS . 'rss.xml'); + $rssAsArray = Xml::toArray(Xml::build($rss)); + $this->assertEquals('2.0', $rssAsArray['rss']['@version']); + $this->assertEquals(2, count($rssAsArray['rss']['channel']['item'])); + + $atomLink = array('@href' => 'http://bakery.cakephp.org/articles/rss', '@rel' => 'self', '@type' => 'application/rss+xml'); + $this->assertEquals($rssAsArray['rss']['channel']['atom:link'], $atomLink); + $this->assertEquals('http://bakery.cakephp.org/', $rssAsArray['rss']['channel']['link']); + + $expected = array( + 'title' => 'Alertpay automated sales via IPN', + 'link' => 'http://bakery.cakephp.org/articles/view/alertpay-automated-sales-via-ipn', + 'description' => 'I\'m going to show you how I implemented a payment module via the Alertpay payment processor.', + 'pubDate' => 'Tue, 31 Aug 2010 01:42:00 -0500', + 'guid' => 'http://bakery.cakephp.org/articles/view/alertpay-automated-sales-via-ipn' + ); + $this->assertSame($rssAsArray['rss']['channel']['item'][1], $expected); + + $rss = array( + 'rss' => array( + 'xmlns:atom' => 'http://www.w3.org/2005/Atom', + '@version' => '2.0', + 'channel' => array( + 'atom:link' => array( + '@href' => 'http://bakery.cakephp.org/articles/rss', + '@rel' => 'self', + '@type' => 'application/rss+xml' + ), + 'title' => 'The Bakery: ', + 'link' => 'http://bakery.cakephp.org/', + 'description' => 'Recent Articles at The Bakery.', + 'pubDate' => 'Sun, 12 Sep 2010 04:18:26 -0500', + 'item' => array( + array( + 'title' => 'CakePHP 1.3.4 released', + 'link' => 'http://bakery.cakephp.org/articles/view/cakephp-1-3-4-released' + ), + array( + 'title' => 'Wizard Component 1.2 Tutorial', + 'link' => 'http://bakery.cakephp.org/articles/view/wizard-component-1-2-tutorial' + ) + ) + ) + ) + ); + $rssAsSimpleXML = Xml::fromArray($rss); + $xmlText = << + + + + The Bakery: + http://bakery.cakephp.org/ + Recent Articles at The Bakery. + Sun, 12 Sep 2010 04:18:26 -0500 + + CakePHP 1.3.4 released + http://bakery.cakephp.org/articles/view/cakephp-1-3-4-released + + + Wizard Component 1.2 Tutorial + http://bakery.cakephp.org/articles/view/wizard-component-1-2-tutorial + + + +XML; + $this->assertXmlStringEqualsXmlString($xmlText, $rssAsSimpleXML->asXML()); + } + +/** + * testXmlRpc + * + * @return void + */ + public function testXmlRpc() { + $xml = Xml::build('test'); + $expected = array( + 'methodCall' => array( + 'methodName' => 'test', + 'params' => '' + ) + ); + $this->assertSame(Xml::toArray($xml), $expected); + + $xml = Xml::build('test12Egypt0-31'); + $expected = array( + 'methodCall' => array( + 'methodName' => 'test', + 'params' => array( + 'param' => array( + 'value' => array( + 'array' => array( + 'data' => array( + 'value' => array( + array('int' => '12'), + array('string' => 'Egypt'), + array('boolean' => '0'), + array('int' => '-31') + ) + ) + ) + ) + ) + ) + ) + ); + $this->assertSame(Xml::toArray($xml), $expected); + + $xmlText = << + + + + + + + + 1 + + + testing + + + + + + + +XML; + $xml = Xml::build($xmlText); + $expected = array( + 'methodResponse' => array( + 'params' => array( + 'param' => array( + 'value' => array( + 'array' => array( + 'data' => array( + 'value' => array( + array('int' => '1'), + array('string' => 'testing') + ) + ) + ) + ) + ) + ) + ) + ); + $this->assertSame(Xml::toArray($xml), $expected); + + $xml = Xml::fromArray($expected, 'tags'); + $this->assertXmlStringEqualsXmlString($xmlText, $xml->asXML()); + } + +/** + * testSoap + * + * @return void + */ + public function testSoap() { + $xmlRequest = Xml::build(CAKE . 'Test' . DS . 'Fixture' . DS . 'soap_request.xml'); + $expected = array( + 'Envelope' => array( + '@soap:encodingStyle' => 'http://www.w3.org/2001/12/soap-encoding', + 'soap:Body' => array( + 'm:GetStockPrice' => array( + 'm:StockName' => 'IBM' + ) + ) + ) + ); + $this->assertEquals($expected, Xml::toArray($xmlRequest)); + + $xmlResponse = Xml::build(CAKE . 'Test' . DS . 'Fixture' . DS . 'soap_response.xml'); + $expected = array( + 'Envelope' => array( + '@soap:encodingStyle' => 'http://www.w3.org/2001/12/soap-encoding', + 'soap:Body' => array( + 'm:GetStockPriceResponse' => array( + 'm:Price' => '34.5' + ) + ) + ) + ); + $this->assertEquals($expected, Xml::toArray($xmlResponse)); + + $xml = array( + 'soap:Envelope' => array( + 'xmlns:soap' => 'http://www.w3.org/2001/12/soap-envelope', + '@soap:encodingStyle' => 'http://www.w3.org/2001/12/soap-encoding', + 'soap:Body' => array( + 'xmlns:m' => 'http://www.example.org/stock', + 'm:GetStockPrice' => array( + 'm:StockName' => 'IBM' + ) + ) + ) + ); + $xmlRequest = Xml::fromArray($xml, array('encoding' => null)); + $xmlText = << + + + IBM + + +XML; + $this->assertXmlStringEqualsXmlString($xmlText, $xmlRequest->asXML()); + } + +/** + * testNamespace + * + * @return void + */ + public function testNamespace() { + $xml = << + + good + bad + + Tag without ns + +XML; + $xmlResponse = Xml::build($xml); + $expected = array( + 'root' => array( + 'ns:tag' => array( + '@id' => '1', + 'child' => 'good', + 'otherchild' => 'bad' + ), + 'tag' => 'Tag without ns' + ) + ); + $this->assertEquals($expected, Xml::toArray($xmlResponse)); + + $xmlResponse = Xml::build('1'); + $expected = array( + 'root' => array( + 'ns:tag' => array( + '@id' => '1' + ), + 'tag' => array( + 'id' => '1' + ) + ) + ); + $this->assertEquals($expected, Xml::toArray($xmlResponse)); + + $xmlResponse = Xml::build('1'); + $expected = array( + 'root' => array( + 'ns:attr' => '1' + ) + ); + $this->assertEquals($expected, Xml::toArray($xmlResponse)); + + $xmlResponse = Xml::build('1'); + $this->assertEquals($expected, Xml::toArray($xmlResponse)); + + $xml = array( + 'root' => array( + 'ns:attr' => array( + 'xmlns:ns' => 'http://cakephp.org', + '@' => 1 + ) + ) + ); + $expected = '<' . '?xml version="1.0" encoding="UTF-8"?>1'; + $xmlResponse = Xml::fromArray($xml); + $this->assertEquals(str_replace(array("\r", "\n"), '', $xmlResponse->asXML()), $expected); + + $xml = array( + 'root' => array( + 'tag' => array( + 'xmlns:pref' => 'http://cakephp.org', + 'pref:item' => array( + 'item 1', + 'item 2' + ) + ) + ) + ); + $expected = << + + + item 1 + item 2 + + +XML; + $xmlResponse = Xml::fromArray($xml); + $this->assertXmlStringEqualsXmlString($expected, $xmlResponse->asXML()); + + $xml = array( + 'root' => array( + 'tag' => array( + 'xmlns:' => 'http://cakephp.org' + ) + ) + ); + $expected = '<' . '?xml version="1.0" encoding="UTF-8"?>'; + $xmlResponse = Xml::fromArray($xml); + $this->assertXmlStringEqualsXmlString($expected, $xmlResponse->asXML()); + + $xml = array( + 'root' => array( + 'xmlns:' => 'http://cakephp.org' + ) + ); + $expected = '<' . '?xml version="1.0" encoding="UTF-8"?>'; + $xmlResponse = Xml::fromArray($xml); + $this->assertXmlStringEqualsXmlString($expected, $xmlResponse->asXML()); + + $xml = array( + 'root' => array( + 'xmlns:ns' => 'http://cakephp.org' + ) + ); + $expected = '<' . '?xml version="1.0" encoding="UTF-8"?>'; + $xmlResponse = Xml::fromArray($xml); + $this->assertXmlStringEqualsXmlString($expected, $xmlResponse->asXML()); + } + +/** + * test that CDATA blocks don't get screwed up by SimpleXml + * + * @return void + */ + public function testCdata() { + $xml = '<' . '?xml version="1.0" encoding="UTF-8"?>' . + ''; + + $result = Xml::build($xml); + $this->assertEquals(' Mark ', (string)$result->name); + } + +/** + * data provider for toArray() failures + * + * @return array + */ + public static function invalidToArrayDataProvider() { + return array( + array(new DateTime()), + array(array()) + ); + } + +/** + * testToArrayFail method + * + * @dataProvider invalidToArrayDataProvider + * @expectedException XmlException + */ + public function testToArrayFail($value) { + Xml::toArray($value); + } + +/** + * testWithModel method + * + * @return void + */ + public function testWithModel() { + $this->loadFixtures('User', 'Article'); + + $user = new XmlUser(); + $data = $user->read(null, 1); + + $obj = Xml::build(compact('data')); + $expected = << +1mariano5f4dcc3b5aa765d61d8327deb882cf99 +2007-03-17 01:16:232007-03-17 01:18:31 +
11First ArticleFirst Article Body +Y2007-03-18 10:39:232007-03-18 10:41:31
+
31Third ArticleThird Article Body +Y2007-03-18 10:43:232007-03-18 10:45:31
+
+XML; + $this->assertXmlStringEqualsXmlString($expected, $obj->asXML()); + + //multiple model results - without a records key it would fatal error + $data = $user->find('all', array('limit' => 2)); + $data = array('records' => $data); + $obj = Xml::build(compact('data')); + $expected = << + +1mariano5f4dcc3b5aa765d61d8327deb882cf99 +2007-03-17 01:16:232007-03-17 01:18:31 +
11First ArticleFirst Article Body +Y2007-03-18 10:39:232007-03-18 10:41:31
+
31Third ArticleThird Article Body +Y2007-03-18 10:43:232007-03-18 10:45:31
+
2nate5f4dcc3b5aa765d61d8327deb882cf99 +2007-03-17 01:18:232007-03-17 01:20:31
+ + +XML; + $result = $obj->asXML(); + $this->assertXmlStringEqualsXmlString($expected, $obj->asXML()); + } + +/** + * Test ampersand in text elements. + * + * @return void + */ + public function testAmpInText() { + $data = array( + 'outer' => array( + 'inner' => array('name' => 'mark & mark') + ) + ); + $obj = Xml::build($data); + $result = $obj->asXml(); + $this->assertContains('mark & mark', $result); + } + +/** + * Test that entity loading is disabled by default. + * + * @return void + */ + public function testNoEntityLoading() { + $file = CAKE . 'VERSION.txt'; + $xml = <<]> + + &payload; + +XML; + try { + $result = Xml::build($xml); + $this->assertEquals('', (string)$result->xxe); + } catch (Exception $e) { + $this->assertTrue(true, 'A warning was raised meaning external entities were not loaded'); + } + } + +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/View/Helper/CacheHelperTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/View/Helper/CacheHelperTest.php new file mode 100644 index 0000000..f6e04b6 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/View/Helper/CacheHelperTest.php @@ -0,0 +1,650 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.View.Helper + * @since CakePHP(tm) v 1.2.0.4206 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ + +App::uses('Controller', 'Controller'); +App::uses('Model', 'Model'); +App::uses('View', 'View'); +App::uses('CacheHelper', 'View/Helper'); + +/** + * CacheTestController class + * + * @package Cake.Test.Case.View.Helper + */ +class CacheTestController extends Controller { + +/** + * helpers property + * + * @var array + */ + public $helpers = array('Html', 'Cache'); + +/** + * cache_parsing method + * + * @return void + */ + public function cache_parsing() { + $this->viewPath = 'Posts'; + $this->layout = 'cache_layout'; + $this->set('variable', 'variableValue'); + $this->set('superman', 'clark kent'); + $this->set('batman', 'bruce wayne'); + $this->set('spiderman', 'peter parker'); + } + +} + +/** + * CacheHelperTest class + * + * @package Cake.Test.Case.View.Helper + */ +class CacheHelperTest extends CakeTestCase { + +/** + * Checks if TMP/views is writable, and skips the case if it is not. + * + * @return void + */ + public function skip() { + if (!is_writable(TMP . 'cache' . DS . 'views' . DS)) { + $this->markTestSkipped('TMP/views is not writable %s'); + } + } + +/** + * setUp method + * + * @return void + */ + public function setUp() { + parent::setUp(); + $_GET = array(); + $request = new CakeRequest(); + $this->Controller = new CacheTestController($request); + $View = new View($this->Controller); + $this->Cache = new CacheHelper($View); + Configure::write('Cache.check', true); + Configure::write('Cache.disable', false); + App::build(array( + 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS) + ), App::RESET); + } + +/** + * tearDown method + * + * @return void + */ + public function tearDown() { + clearCache(); + unset($this->Cache); + parent::tearDown(); + } + +/** + * test cache parsing with no cake:nocache tags in view file. + * + * @return void + */ + public function testLayoutCacheParsingNoTagsInView() { + $this->Controller->cache_parsing(); + $this->Controller->request->addParams(array( + 'controller' => 'cache_test', + 'action' => 'cache_parsing', + 'pass' => array(), + 'named' => array() + )); + $this->Controller->cacheAction = 21600; + $this->Controller->request->here = '/cacheTest/cache_parsing'; + $this->Controller->request->action = 'cache_parsing'; + + $View = new View($this->Controller); + $result = $View->render('index'); + $this->assertNotRegExp('/cake:nocache/', $result); + $this->assertNotRegExp('/php echo/', $result); + + $filename = CACHE . 'views' . DS . 'cachetest_cache_parsing.php'; + $this->assertTrue(file_exists($filename)); + + $contents = file_get_contents($filename); + $this->assertRegExp('/php echo \$variable/', $contents); + $this->assertRegExp('/php echo microtime()/', $contents); + $this->assertRegExp('/clark kent/', $result); + + @unlink($filename); + } + +/** + * test cache parsing with non-latin characters in current route + * + * @return void + */ + public function testCacheNonLatinCharactersInRoute() { + $this->Controller->cache_parsing(); + $this->Controller->request->addParams(array( + 'controller' => 'cache_test', + 'action' => 'cache_parsing', + 'pass' => array('風街ろまん'), + 'named' => array() + )); + $this->Controller->cacheAction = 21600; + $this->Controller->request->here = '/posts/view/風街ろまん'; + $this->Controller->action = 'view'; + + $View = new View($this->Controller); + $result = $View->render('index'); + + $filename = CACHE . 'views' . DS . 'posts_view_風街ろまん.php'; + $this->assertTrue(file_exists($filename)); + + @unlink($filename); + } + +/** + * Test cache parsing with cake:nocache tags in view file. + * + * @return void + */ + public function testLayoutCacheParsingWithTagsInView() { + $this->Controller->cache_parsing(); + $this->Controller->request->addParams(array( + 'controller' => 'cache_test', + 'action' => 'cache_parsing', + 'pass' => array(), + 'named' => array() + )); + $this->Controller->cacheAction = 21600; + $this->Controller->request->here = '/cacheTest/cache_parsing'; + $this->Controller->action = 'cache_parsing'; + + $View = new View($this->Controller); + $result = $View->render('test_nocache_tags'); + $this->assertNotRegExp('/cake:nocache/', $result); + $this->assertNotRegExp('/php echo/', $result); + + $filename = CACHE . 'views' . DS . 'cachetest_cache_parsing.php'; + $this->assertTrue(file_exists($filename)); + + $contents = file_get_contents($filename); + $this->assertRegExp('/if \(is_writable\(TMP\)\)\:/', $contents); + $this->assertRegExp('/php echo \$variable/', $contents); + $this->assertRegExp('/php echo microtime()/', $contents); + $this->assertNotRegExp('/cake:nocache/', $contents); + + @unlink($filename); + } + +/** + * test that multiple tags function with multiple nocache tags in the layout. + * + * @return void + */ + public function testMultipleNoCacheTagsInViewfile() { + $this->Controller->cache_parsing(); + $this->Controller->request->addParams(array( + 'controller' => 'cache_test', + 'action' => 'cache_parsing', + 'pass' => array(), + 'named' => array() + )); + $this->Controller->cacheAction = 21600; + $this->Controller->request->here = '/cacheTest/cache_parsing'; + $this->Controller->action = 'cache_parsing'; + + $View = new View($this->Controller); + $result = $View->render('multiple_nocache'); + + $this->assertNotRegExp('/cake:nocache/', $result); + $this->assertNotRegExp('/php echo/', $result); + + $filename = CACHE . 'views' . DS . 'cachetest_cache_parsing.php'; + $this->assertTrue(file_exists($filename)); + + $contents = file_get_contents($filename); + $this->assertNotRegExp('/cake:nocache/', $contents); + @unlink($filename); + } + +/** + * testComplexNoCache method + * + * @return void + */ + public function testComplexNoCache() { + $this->Controller->cache_parsing(); + $this->Controller->request->addParams(array( + 'controller' => 'cache_test', + 'action' => 'cache_complex', + 'pass' => array(), + 'named' => array() + )); + $this->Controller->cacheAction = array('cache_complex' => 21600); + $this->Controller->request->here = '/cacheTest/cache_complex'; + $this->Controller->action = 'cache_complex'; + $this->Controller->layout = 'multi_cache'; + $this->Controller->viewPath = 'Posts'; + + $View = new View($this->Controller); + $result = $View->render('sequencial_nocache'); + + $this->assertNotRegExp('/cake:nocache/', $result); + $this->assertNotRegExp('/php echo/', $result); + $this->assertRegExp('/A\. Layout Before Content/', $result); + $this->assertRegExp('/B\. In Plain Element/', $result); + $this->assertRegExp('/C\. Layout After Test Element/', $result); + $this->assertRegExp('/D\. In View File/', $result); + $this->assertRegExp('/E\. Layout After Content/', $result); + $this->assertRegExp('/F\. In Element With No Cache Tags/', $result); + $this->assertRegExp('/G\. Layout After Content And After Element With No Cache Tags/', $result); + $this->assertNotRegExp('/1\. layout before content/', $result); + $this->assertNotRegExp('/2\. in plain element/', $result); + $this->assertNotRegExp('/3\. layout after test element/', $result); + $this->assertNotRegExp('/4\. in view file/', $result); + $this->assertNotRegExp('/5\. layout after content/', $result); + $this->assertNotRegExp('/6\. in element with no cache tags/', $result); + $this->assertNotRegExp('/7\. layout after content and after element with no cache tags/', $result); + + $filename = CACHE . 'views' . DS . 'cachetest_cache_complex.php'; + $this->assertTrue(file_exists($filename)); + $contents = file_get_contents($filename); + @unlink($filename); + + $this->assertRegExp('/A\. Layout Before Content/', $contents); + $this->assertNotRegExp('/B\. In Plain Element/', $contents); + $this->assertRegExp('/C\. Layout After Test Element/', $contents); + $this->assertRegExp('/D\. In View File/', $contents); + $this->assertRegExp('/E\. Layout After Content/', $contents); + $this->assertRegExp('/F\. In Element With No Cache Tags/', $contents); + $this->assertRegExp('/G\. Layout After Content And After Element With No Cache Tags/', $contents); + $this->assertRegExp('/1\. layout before content/', $contents); + $this->assertNotRegExp('/2\. in plain element/', $contents); + $this->assertRegExp('/3\. layout after test element/', $contents); + $this->assertRegExp('/4\. in view file/', $contents); + $this->assertRegExp('/5\. layout after content/', $contents); + $this->assertRegExp('/6\. in element with no cache tags/', $contents); + $this->assertRegExp('/7\. layout after content and after element with no cache tags/', $contents); + } + +/** + * test cache of view vars + * + * @return void + */ + public function testCacheViewVars() { + $this->Controller->cache_parsing(); + $this->Controller->request->addParams(array( + 'controller' => 'cache_test', + 'action' => 'cache_parsing', + 'pass' => array(), + 'named' => array() + )); + $this->Controller->request->here = '/cacheTest/cache_parsing'; + $this->Controller->cacheAction = 21600; + + $View = new View($this->Controller); + $result = $View->render('index'); + $this->assertNotRegExp('/cake:nocache/', $result); + $this->assertNotRegExp('/php echo/', $result); + + $filename = CACHE . 'views' . DS . 'cachetest_cache_parsing.php'; + $this->assertTrue(file_exists($filename)); + + $contents = file_get_contents($filename); + $this->assertRegExp('/\$this\-\>viewVars/', $contents); + $this->assertRegExp('/extract\(\$this\-\>viewVars, EXTR_SKIP\);/', $contents); + $this->assertRegExp('/php echo \$variable/', $contents); + + @unlink($filename); + } + +/** + * Test that callback code is generated correctly. + * + * @return void + */ + public function testCacheCallbacks() { + $this->Controller->request->addParams(array( + 'controller' => 'cache_test', + 'action' => 'cache_parsing', + 'pass' => array(), + 'named' => array() + )); + $this->Controller->cacheAction = array( + 'cache_parsing' => array( + 'duration' => 21600, + 'callbacks' => true + ) + ); + $this->Controller->request->here = '/cacheTest/cache_parsing'; + $this->Controller->cache_parsing(); + + $View = new View($this->Controller); + $result = $View->render('index'); + + $filename = CACHE . 'views' . DS . 'cachetest_cache_parsing.php'; + $this->assertTrue(file_exists($filename)); + + $contents = file_get_contents($filename); + + $this->assertRegExp('/\$controller->startupProcess\(\);/', $contents); + + @unlink($filename); + } + +/** + * test cacheAction set to a boolean + * + * @return void + */ + public function testCacheActionArray() { + $this->Controller->request->addParams(array( + 'controller' => 'cache_test', + 'action' => 'cache_parsing', + 'pass' => array(), + 'named' => array() + )); + $this->Controller->request->here = '/cache_test/cache_parsing'; + $this->Controller->cacheAction = array( + 'cache_parsing' => 21600 + ); + + $this->Controller->cache_parsing(); + + $View = new View($this->Controller); + $result = $View->render('index'); + + $this->assertNotRegExp('/cake:nocache/', $result); + $this->assertNotRegExp('/php echo/', $result); + + $filename = CACHE . 'views' . DS . 'cache_test_cache_parsing.php'; + $this->assertTrue(file_exists($filename)); + @unlink($filename); + } + +/** + * Test that cacheAction works with camelcased controller names. + * + * @return void + */ + public function testCacheActionArrayCamelCase() { + $this->Controller->request->addParams(array( + 'controller' => 'cache_test', + 'action' => 'cache_parsing', + 'pass' => array(), + 'named' => array() + )); + $this->Controller->cacheAction = array( + 'cache_parsing' => 21600 + ); + $this->Controller->request->here = '/cacheTest/cache_parsing'; + $this->Controller->cache_parsing(); + + $View = new View($this->Controller); + $result = $View->render('index'); + + $this->assertNotRegExp('/cake:nocache/', $result); + $this->assertNotRegExp('/php echo/', $result); + + $filename = CACHE . 'views' . DS . 'cachetest_cache_parsing.php'; + $this->assertTrue(file_exists($filename)); + @unlink($filename); + } + +/** + * test with named and pass args. + * + * @return void + */ + public function testCacheWithNamedAndPassedArgs() { + Router::reload(); + + $this->Controller->cache_parsing(); + $this->Controller->request->addParams(array( + 'controller' => 'cache_test', + 'action' => 'cache_parsing', + 'pass' => array(1, 2), + 'named' => array( + 'name' => 'mark', + 'ice' => 'cream' + ) + )); + $this->Controller->cacheAction = array( + 'cache_parsing' => 21600 + ); + $this->Controller->request->here = '/cache_test/cache_parsing/1/2/name:mark/ice:cream'; + + $View = new View($this->Controller); + $result = $View->render('index'); + + $this->assertNotRegExp('/cake:nocache/', $result); + $this->assertNotRegExp('/php echo/', $result); + + $filename = CACHE . 'views' . DS . 'cache_test_cache_parsing_1_2_name_mark_ice_cream.php'; + $this->assertTrue(file_exists($filename)); + @unlink($filename); + } + +/** + * Test that query string parameters are included in the cache filename. + * + * @return void + */ + public function testCacheWithQueryStringParams() { + Router::reload(); + + $this->Controller->cache_parsing(); + $this->Controller->request->addParams(array( + 'controller' => 'cache_test', + 'action' => 'cache_parsing', + 'pass' => array(), + 'named' => array() + )); + $this->Controller->request->query = array('q' => 'cakephp'); + $this->Controller->cacheAction = array( + 'cache_parsing' => 21600 + ); + $this->Controller->request->here = '/cache_test/cache_parsing'; + + $View = new View($this->Controller); + $result = $View->render('index'); + + $this->assertNotRegExp('/cake:nocache/', $result); + $this->assertNotRegExp('/php echo/', $result); + + $filename = CACHE . 'views' . DS . 'cache_test_cache_parsing_q_cakephp.php'; + $this->assertTrue(file_exists($filename), 'Missing cache file ' . $filename); + @unlink($filename); + } + +/** + * test that custom routes are respected when generating cache files. + * + * @return void + */ + public function testCacheWithCustomRoutes() { + Router::reload(); + Router::connect('/:lang/:controller/:action/*', array(), array('lang' => '[a-z]{3}')); + + $this->Controller->cache_parsing(); + $this->Controller->request->addParams(array( + 'lang' => 'en', + 'controller' => 'cache_test', + 'action' => 'cache_parsing', + 'pass' => array(), + 'named' => array() + )); + $this->Controller->cacheAction = array( + 'cache_parsing' => 21600 + ); + $this->Controller->request->here = '/en/cache_test/cache_parsing'; + $this->Controller->action = 'cache_parsing'; + + $View = new View($this->Controller); + $result = $View->render('index'); + + $this->assertNotRegExp('/cake:nocache/', $result); + $this->assertNotRegExp('/php echo/', $result); + + $filename = CACHE . 'views' . DS . 'en_cache_test_cache_parsing.php'; + $this->assertTrue(file_exists($filename)); + @unlink($filename); + } + +/** + * test ControllerName contains AppName + * + * This test verifies view cache is created correctly when the app name is contained in part of the controller name. + * (webapp Name) base name is 'cache' controller is 'cacheTest' action is 'cache_name' + * apps url would look something like http://localhost/cache/cacheTest/cache_name + * + * @return void + **/ + public function testCacheBaseNameControllerName() { + $this->Controller->cache_parsing(); + $this->Controller->cacheAction = array( + 'cache_name' => 21600 + ); + $this->Controller->params = array( + 'controller' => 'cacheTest', + 'action' => 'cache_name', + 'pass' => array(), + 'named' => array() + ); + $this->Controller->here = '/cache/cacheTest/cache_name'; + $this->Controller->action = 'cache_name'; + $this->Controller->base = '/cache'; + + $View = new View($this->Controller); + $result = $View->render('index'); + + $this->assertNotRegExp('/cake:nocache/', $result); + $this->assertNotRegExp('/php echo/', $result); + + $filename = CACHE . 'views' . DS . 'cache_cachetest_cache_name.php'; + $this->assertTrue(file_exists($filename)); + @unlink($filename); + } + +/** + * test that afterRender checks the conditions correctly. + * + * @return void + */ + public function testAfterRenderConditions() { + Configure::write('Cache.check', true); + $View = new View($this->Controller); + $View->cacheAction = '+1 day'; + $View->output = 'test'; + + $Cache = $this->getMock('CacheHelper', array('_parseContent'), array($View)); + $Cache->expects($this->once()) + ->method('_parseContent') + ->with('posts/index', 'content') + ->will($this->returnValue('')); + + $Cache->afterRenderFile('posts/index', 'content'); + + Configure::write('Cache.check', false); + $Cache->afterRender('posts/index'); + + Configure::write('Cache.check', true); + $View->cacheAction = false; + $Cache->afterRender('posts/index'); + } + +/** + * test that afterRender checks the conditions correctly. + * + * @return void + */ + public function testAfterLayoutConditions() { + Configure::write('Cache.check', true); + $View = new View($this->Controller); + $View->cacheAction = '+1 day'; + $View->output = 'test'; + + $Cache = $this->getMock('CacheHelper', array('cache'), array($View)); + $Cache->expects($this->once()) + ->method('cache') + ->with('posts/index', $View->output) + ->will($this->returnValue('')); + + $Cache->afterLayout('posts/index'); + + Configure::write('Cache.check', false); + $Cache->afterLayout('posts/index'); + + Configure::write('Cache.check', true); + $View->cacheAction = false; + $Cache->afterLayout('posts/index'); + } + +/** + * testCacheEmptySections method + * + * This test must be uncommented/fixed in next release (1.2+) + * + * @return void + */ + public function testCacheEmptySections() { + $this->Controller->cache_parsing(); + $this->Controller->params = array( + 'controller' => 'cacheTest', + 'action' => 'cache_empty_sections', + 'pass' => array(), + 'named' => array() + ); + $this->Controller->cacheAction = array('cache_empty_sections' => 21600); + $this->Controller->here = '/cacheTest/cache_empty_sections'; + $this->Controller->action = 'cache_empty_sections'; + $this->Controller->layout = 'cache_empty_sections'; + $this->Controller->viewPath = 'Posts'; + + $View = new View($this->Controller); + $result = $View->render('cache_empty_sections'); + $this->assertNotRegExp('/nocache/', $result); + $this->assertNotRegExp('/php echo/', $result); + $this->assertRegExp( + '@\s*\s*' . + '\s*' . + 'View Content\s*' . + 'cached count is: 3\s*' . + '@', $result); + + $filename = CACHE . 'views' . DS . 'cachetest_cache_empty_sections.php'; + $this->assertTrue(file_exists($filename)); + $contents = file_get_contents($filename); + $this->assertNotRegExp('/nocache/', $contents); + $this->assertRegExp( + '@\s*Posts\s*' . + '<\?php \$x \= 1; \?>\s*' . + '\s*' . + '\s*' . + '<\?php \$x\+\+; \?>\s*' . + '<\?php \$x\+\+; \?>\s*' . + 'View Content\s*' . + '<\?php \$y = 1; \?>\s*' . + '<\?php echo \'cached count is: \' . \$x; \?>\s*' . + '@', $contents); + @unlink($filename); + } +} diff --git a/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/View/Helper/FormHelperTest.php b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/View/Helper/FormHelperTest.php new file mode 100644 index 0000000..e523024 --- /dev/null +++ b/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Test/Case/View/Helper/FormHelperTest.php @@ -0,0 +1,8004 @@ + + * Copyright 2005-2012, Cake Software Foundation, Inc. + * + * Licensed under The MIT License + * Redistributions of files must retain the above copyright notice + * + * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. + * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests + * @package Cake.Test.Case.View.Helper + * @since CakePHP(tm) v 1.2.0.4206 + * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + */ +App::uses('ClassRegistry', 'Utility'); +App::uses('Controller', 'Controller'); +App::uses('View', 'View'); +App::uses('Model', 'Model'); +App::uses('Security', 'Utility'); +App::uses('CakeRequest', 'Network'); +App::uses('HtmlHelper', 'View/Helper'); +App::uses('FormHelper', 'View/Helper'); +App::uses('Router', 'Routing'); + +/** + * ContactTestController class + * + * @package cake + * @package Cake.Test.Case.View.Helper + */ +class ContactTestController extends Controller { + +/** + * name property + * + * @var string 'ContactTest' + */ + public $name = 'ContactTest'; + +/** + * uses property + * + * @var mixed null + */ + public $uses = null; +} + +/** + * Contact class + * + * @package cake + * @package Cake.Test.Case.View.Helper + */ +class Contact extends CakeTestModel { + +/** + * primaryKey property + * + * @var string 'id' + */ + public $primaryKey = 'id'; + +/** + * useTable property + * + * @var bool false + */ + public $useTable = false; + +/** + * name property + * + * @var string 'Contact' + */ + public $name = 'Contact'; + +/** + * Default schema + * + * @var array + */ + protected $_schema = array( + 'id' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => '8'), + 'name' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'), + 'email' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'), + 'phone' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'), + 'password' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'), + 'published' => array('type' => 'date', 'null' => true, 'default' => null, 'length' => null), + 'created' => array('type' => 'date', 'null' => '1', 'default' => '', 'length' => ''), + 'updated' => array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => null), + 'age' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => null) + ); + +/** + * validate property + * + * @var array + */ + public $validate = array( + 'non_existing' => array(), + 'idontexist' => array(), + 'imrequired' => array('rule' => array('between', 5, 30), 'allowEmpty' => false), + 'imrequiredonupdate' => array('notEmpty' => array('rule' => 'alphaNumeric', 'on' => 'update')), + 'imrequiredoncreate' => array('required' => array('rule' => 'alphaNumeric', 'on' => 'create')), + 'imrequiredonboth' => array( + 'required' => array('rule' => 'alphaNumeric', 'allowEmpty' => true), + 'check' => array('rule' => 'alphaNumeric') + ), + 'string_required' => 'notEmpty', + 'imalsorequired' => array('rule' => 'alphaNumeric', 'allowEmpty' => false), + 'imrequiredtoo' => array('rule' => 'notEmpty'), + 'required_one' => array('required' => array('rule' => array('notEmpty'))), + 'imnotrequired' => array('required' => false, 'rule' => 'alphaNumeric', 'allowEmpty' => true), + 'imalsonotrequired' => array( + 'alpha' => array('rule' => 'alphaNumeric', 'allowEmpty' => true), + 'between' => array('rule' => array('between', 5, 30), 'allowEmpty' => true), + ), + 'imnotrequiredeither' => array('required' => true, 'rule' => array('between', 5, 30), 'allowEmpty' => true), + ); + +/** + * schema method + * + * @return void + */ + public function setSchema($schema) { + $this->_schema = $schema; + } + +/** + * hasAndBelongsToMany property + * + * @var array + */ + public $hasAndBelongsToMany = array('ContactTag' => array('with' => 'ContactTagsContact')); + +/** + * hasAndBelongsToMany property + * + * @var array + */ + public $belongsTo = array('User' => array('className' => 'UserForm')); +} + +/** + * ContactTagsContact class + * + * @package cake + * @package Cake.Test.Case.View.Helper + */ +class ContactTagsContact extends CakeTestModel { + +/** + * useTable property + * + * @var bool false + */ + public $useTable = false; + +/** + * name property + * + * @var string 'Contact' + */ + public $name = 'ContactTagsContact'; + +/** + * Default schema + * + * @var array + */ + protected $_schema = array( + 'contact_id' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => '8'), + 'contact_tag_id' => array( + 'type' => 'integer', 'null' => '', 'default' => '', 'length' => '8' + ) + ); + +/** + * schema method + * + * @return void + */ + public function setSchema($schema) { + $this->_schema = $schema; + } + +} + +/** + * ContactNonStandardPk class + * + * @package cake + * @package Cake.Test.Case.View.Helper + */ +class ContactNonStandardPk extends Contact { + +/** + * primaryKey property + * + * @var string 'pk' + */ + public $primaryKey = 'pk'; + +/** + * name property + * + * @var string 'ContactNonStandardPk' + */ + public $name = 'ContactNonStandardPk'; + +/** + * schema method + * + * @return void + */ + public function schema($field = false) { + $this->_schema = parent::schema(); + $this->_schema['pk'] = $this->_schema['id']; + unset($this->_schema['id']); + return $this->_schema; + } + +} + +/** + * ContactTag class + * + * @package cake + * @package Cake.Test.Case.View.Helper + */ +class ContactTag extends Model { + +/** + * useTable property + * + * @var bool false + */ + public $useTable = false; + +/** + * schema definition + * + * @var array + */ + protected $_schema = array( + 'id' => array('type' => 'integer', 'null' => false, 'default' => '', 'length' => '8'), + 'name' => array('type' => 'string', 'null' => false, 'default' => '', 'length' => '255'), + 'created' => array('type' => 'date', 'null' => true, 'default' => '', 'length' => ''), + 'modified' => array('type' => 'datetime', 'null' => true, 'default' => '', 'length' => null) + ); +} + +/** + * UserForm class + * + * @package cake + * @package Cake.Test.Case.View.Helper + */ +class UserForm extends CakeTestModel { + +/** + * useTable property + * + * @var bool false + */ + public $useTable = false; + +/** + * primaryKey property + * + * @var string 'id' + */ + public $primaryKey = 'id'; + +/** + * name property + * + * @var string 'UserForm' + */ + public $name = 'UserForm'; + +/** + * hasMany property + * + * @var array + */ + public $hasMany = array( + 'OpenidUrl' => array('className' => 'OpenidUrl', 'foreignKey' => 'user_form_id' + )); + +/** + * schema definition + * + * @var array + */ + protected $_schema = array( + 'id' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => '8'), + 'published' => array('type' => 'date', 'null' => true, 'default' => null, 'length' => null), + 'other' => array('type' => 'text', 'null' => true, 'default' => null, 'length' => null), + 'stuff' => array('type' => 'string', 'null' => true, 'default' => null, 'length' => 10), + 'something' => array('type' => 'string', 'null' => true, 'default' => null, 'length' => 255), + 'active' => array('type' => 'boolean', 'null' => false, 'default' => false), + 'created' => array('type' => 'date', 'null' => '1', 'default' => '', 'length' => ''), + 'updated' => array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => null) + ); +} + +/** + * OpenidUrl class + * + * @package cake + * @package Cake.Test.Case.View.Helper + */ +class OpenidUrl extends CakeTestModel { + +/** + * useTable property + * + * @var bool false + */ + public $useTable = false; + +/** + * primaryKey property + * + * @var string 'id' + */ + public $primaryKey = 'id'; + +/** + * name property + * + * @var string 'OpenidUrl' + */ + public $name = 'OpenidUrl'; + +/** + * belongsTo property + * + * @var array + */ + public $belongsTo = array('UserForm' => array( + 'className' => 'UserForm', 'foreignKey' => 'user_form_id' + )); + +/** + * validate property + * + * @var array + */ + public $validate = array('openid_not_registered' => array()); + +/** + * schema method + * + * @var array + */ + protected $_schema = array( + 'id' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => '8'), + 'user_form_id' => array( + 'type' => 'user_form_id', 'null' => '', 'default' => '', 'length' => '8' + ), + 'url' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'), + ); + +/** + * beforeValidate method + * + * @return void + */ + public function beforeValidate($options = array()) { + $this->invalidate('openid_not_registered'); + return true; + } + +} + +/** + * ValidateUser class + * + * @package cake + * @package Cake.Test.Case.View.Helper + */ +class ValidateUser extends CakeTestModel { + +/** + * primaryKey property + * + * @var string 'id' + */ + public $primaryKey = 'id'; + +/** + * useTable property + * + * @var bool false + */ + public $useTable = false; + +/** + * name property + * + * @var string 'ValidateUser' + */ + public $name = 'ValidateUser'; + +/** + * hasOne property + * + * @var array + */ + public $hasOne = array('ValidateProfile' => array( + 'className' => 'ValidateProfile', 'foreignKey' => 'user_id' + )); + +/** + * schema method + * + * @var array + */ + protected $_schema = array( + 'id' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => '8'), + 'name' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'), + 'email' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'), + 'balance' => array('type' => 'float', 'null' => false, 'length' => '5,2'), + 'created' => array('type' => 'date', 'null' => '1', 'default' => '', 'length' => ''), + 'updated' => array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => null) + ); + +/** + * beforeValidate method + * + * @return void + */ + public function beforeValidate($options = array()) { + $this->invalidate('email'); + return false; + } + +} + +/** + * ValidateProfile class + * + * @package cake + * @package Cake.Test.Case.View.Helper + */ +class ValidateProfile extends CakeTestModel { + +/** + * primaryKey property + * + * @var string 'id' + */ + public $primaryKey = 'id'; + +/** + * useTable property + * + * @var bool false + */ + public $useTable = false; + +/** + * schema property + * + * @var array + */ + protected $_schema = array( + 'id' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => '8'), + 'user_id' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => '8'), + 'full_name' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'), + 'city' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'), + 'created' => array('type' => 'date', 'null' => '1', 'default' => '', 'length' => ''), + 'updated' => array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => null) + ); + +/** + * name property + * + * @var string 'ValidateProfile' + */ + public $name = 'ValidateProfile'; + +/** + * hasOne property + * + * @var array + */ + public $hasOne = array('ValidateItem' => array( + 'className' => 'ValidateItem', 'foreignKey' => 'profile_id' + )); + +/** + * belongsTo property + * + * @var array + */ + public $belongsTo = array('ValidateUser' => array( + 'className' => 'ValidateUser', 'foreignKey' => 'user_id' + )); + +/** + * beforeValidate method + * + * @return void + */ + public function beforeValidate($options = array()) { + $this->invalidate('full_name'); + $this->invalidate('city'); + return false; + } + +} + +/** + * ValidateItem class + * + * @package cake + * @package Cake.Test.Case.View.Helper + */ +class ValidateItem extends CakeTestModel { + +/** + * primaryKey property + * + * @var string 'id' + */ + public $primaryKey = 'id'; + +/** + * useTable property + * + * @var bool false + */ + public $useTable = false; + +/** + * name property + * + * @var string 'ValidateItem' + */ + public $name = 'ValidateItem'; + +/** + * schema property + * + * @var array + */ + protected $_schema = array( + 'id' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => '8'), + 'profile_id' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => '8'), + 'name' => array('type' => 'text', 'null' => '', 'default' => '', 'length' => '255'), + 'description' => array( + 'type' => 'string', 'null' => '', 'default' => '', 'length' => '255' + ), + 'created' => array('type' => 'date', 'null' => '1', 'default' => '', 'length' => ''), + 'updated' => array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => null) + ); + +/** + * belongsTo property + * + * @var array + */ + public $belongsTo = array('ValidateProfile' => array('foreignKey' => 'profile_id')); + +/** + * beforeValidate method + * + * @return void + */ + public function beforeValidate($options = array()) { + $this->invalidate('description'); + return false; + } + +} + +/** + * TestMail class + * + * @package cake + * @package Cake.Test.Case.View.Helper + */ +class TestMail extends CakeTestModel { + +/** + * primaryKey property + * + * @var string 'id' + */ + public $primaryKey = 'id'; + +/** + * useTable property + * + * @var bool false + */ + public $useTable = false; + +/** + * name property + * + * @var string 'TestMail' + */ + public $name = 'TestMail'; +} + +/** + * FormHelperTest class + * + * @package cake + * @subpackage Cake.Test.Case.View.Helper + * @property FormHelper $Form + */ +class FormHelperTest extends CakeTestCase { + +/** + * Fixtures to be used + * + * @var array + */ + public $fixtures = array('core.post'); + +/** + * Do not load the fixtures by default + * + * @var boolean + */ + public $autoFixtures = false; + +/** + * setUp method + * + * @return void + */ + public function setUp() { + parent::setUp(); + + Configure::write('App.base', ''); + $this->Controller = new ContactTestController(); + $this->View = new View($this->Controller); + + $this->Form = new FormHelper($this->View); + $this->Form->Html = new HtmlHelper($this->View); + $this->Form->request = new CakeRequest('contacts/add', false); + $this->Form->request->here = '/contacts/add'; + $this->Form->request['action'] = 'add'; + $this->Form->request->webroot = ''; + $this->Form->request->base = ''; + + ClassRegistry::addObject('Contact', new Contact()); + ClassRegistry::addObject('ContactNonStandardPk', new ContactNonStandardPk()); + ClassRegistry::addObject('OpenidUrl', new OpenidUrl()); + ClassRegistry::addObject('User', new UserForm()); + ClassRegistry::addObject('ValidateItem', new ValidateItem()); + ClassRegistry::addObject('ValidateUser', new ValidateUser()); + ClassRegistry::addObject('ValidateProfile', new ValidateProfile()); + + $this->oldSalt = Configure::read('Security.salt'); + + $this->dateRegex = array( + 'daysRegex' => 'preg:/(?: