From 8aaa1aba44e541ca260de505a3e98996b98c9f37 Mon Sep 17 00:00:00 2001 From: Thomas Steur Date: Mon, 6 Oct 2014 04:41:13 +0200 Subject: refs #5940 splitting plugin tests folder into unit, integration and system for now --- plugins/API/tests/ConsoleRendererTest.php | 121 --- plugins/API/tests/CsvRendererTest.php | 283 ------ plugins/API/tests/HtmlRendererTest.php | 459 --------- plugins/API/tests/Integration/RowEvolutionTest.php | 45 + plugins/API/tests/Integration/RssRendererTest.php | 192 ++++ plugins/API/tests/JsonRendererTest.php | 385 -------- plugins/API/tests/OriginalRendererTest.php | Bin 4028 -> 0 bytes plugins/API/tests/PhpRendererTest.php | 218 ---- plugins/API/tests/RowEvolutionTest.php | 44 - plugins/API/tests/RssRendererTest.php | 192 ---- plugins/API/tests/Unit/ConsoleRendererTest.php | 121 +++ plugins/API/tests/Unit/CsvRendererTest.php | 283 ++++++ plugins/API/tests/Unit/HtmlRendererTest.php | 459 +++++++++ plugins/API/tests/Unit/JsonRendererTest.php | 385 ++++++++ plugins/API/tests/Unit/OriginalRendererTest.php | Bin 0 -> 4033 bytes plugins/API/tests/Unit/PhpRendererTest.php | 218 ++++ plugins/API/tests/Unit/XmlRendererTest.php | 346 +++++++ plugins/API/tests/XmlRendererTest.php | 346 ------- plugins/Actions/tests/ArchiverTest.php | 130 --- plugins/Actions/tests/Unit/ArchiverTest.php | 130 +++ plugins/Contents/.gitignore | 2 +- plugins/Contents/tests/ContentsTest.php | 135 --- plugins/Contents/tests/System/ContentsTest.php | 135 +++ ...tentNames_lastN__API.getProcessedReport_day.xml | 83 ++ ...entPieces_lastN__API.getProcessedReport_day.xml | 123 +++ .../test_Contents__Actions.getPageUrls_day.xml | 25 + .../test_Contents__Actions.getPageUrls_month.xml | 25 + .../expected/test_Contents__Actions.get_day.xml | 12 + .../expected/test_Contents__Actions.get_month.xml | 12 + ...test_Contents__Contents.getContentNames_day.xml | 30 + ...st_Contents__Contents.getContentNames_month.xml | 30 + ...est_Contents__Contents.getContentPieces_day.xml | 66 ++ ...t_Contents__Contents.getContentPieces_month.xml | 66 ++ ...est_Contents__Live.getLastVisitsDetails_day.xml | 199 ++++ ...t_Contents__Live.getLastVisitsDetails_month.xml | 199 ++++ ...ntInteractionMatch__Actions.getPageUrls_day.xml | 2 + ...eractionMatch__Contents.getContentNames_day.xml | 2 + ...ractionMatch__Contents.getContentPieces_day.xml | 2 + ...ractionMatch__Live.getLastVisitsDetails_day.xml | 199 ++++ ...contentTargetMatch__Actions.getPageUrls_day.xml | 2 + ...ntTargetMatch__Contents.getContentNames_day.xml | 12 + ...tTargetMatch__Contents.getContentPieces_day.xml | 21 + ...tTargetMatch__Live.getLastVisitsDetails_day.xml | 199 ++++ ...ntNameOrPieceMatch__Actions.getPageUrls_day.xml | 2 + ...eOrPieceMatch__Contents.getContentNames_day.xml | 21 + ...OrPieceMatch__Contents.getContentPieces_day.xml | 48 + ...OrPieceMatch__Live.getLastVisitsDetails_day.xml | 199 ++++ plugins/Contents/tests/System/processed/.gitkeep | 0 ...tentNames_lastN__API.getProcessedReport_day.xml | 83 ++ ...entPieces_lastN__API.getProcessedReport_day.xml | 123 +++ .../test_Contents__Actions.getPageUrls_day.xml | 25 + .../test_Contents__Actions.getPageUrls_month.xml | 25 + .../processed/test_Contents__Actions.get_day.xml | 12 + .../processed/test_Contents__Actions.get_month.xml | 12 + ...test_Contents__Contents.getContentNames_day.xml | 30 + ...st_Contents__Contents.getContentNames_month.xml | 30 + ...est_Contents__Contents.getContentPieces_day.xml | 66 ++ ...t_Contents__Contents.getContentPieces_month.xml | 66 ++ ...est_Contents__Live.getLastVisitsDetails_day.xml | 199 ++++ ...t_Contents__Live.getLastVisitsDetails_month.xml | 199 ++++ ...ntInteractionMatch__Actions.getPageUrls_day.xml | 2 + ...eractionMatch__Contents.getContentNames_day.xml | 2 + ...ractionMatch__Contents.getContentPieces_day.xml | 2 + ...ractionMatch__Live.getLastVisitsDetails_day.xml | 199 ++++ ...contentTargetMatch__Actions.getPageUrls_day.xml | 2 + ...ntTargetMatch__Contents.getContentNames_day.xml | 12 + ...tTargetMatch__Contents.getContentPieces_day.xml | 21 + ...tTargetMatch__Live.getLastVisitsDetails_day.xml | 199 ++++ ...ntNameOrPieceMatch__Actions.getPageUrls_day.xml | 2 + ...eOrPieceMatch__Contents.getContentNames_day.xml | 21 + ...OrPieceMatch__Contents.getContentPieces_day.xml | 48 + ...OrPieceMatch__Live.getLastVisitsDetails_day.xml | 199 ++++ ...tentNames_lastN__API.getProcessedReport_day.xml | 83 -- ...entPieces_lastN__API.getProcessedReport_day.xml | 123 --- .../test_Contents__Actions.getPageUrls_day.xml | 25 - .../test_Contents__Actions.getPageUrls_month.xml | 25 - .../expected/test_Contents__Actions.get_day.xml | 12 - .../expected/test_Contents__Actions.get_month.xml | 12 - ...test_Contents__Contents.getContentNames_day.xml | 30 - ...st_Contents__Contents.getContentNames_month.xml | 30 - ...est_Contents__Contents.getContentPieces_day.xml | 66 -- ...t_Contents__Contents.getContentPieces_month.xml | 66 -- ...est_Contents__Live.getLastVisitsDetails_day.xml | 199 ---- ...t_Contents__Live.getLastVisitsDetails_month.xml | 199 ---- ...ntInteractionMatch__Actions.getPageUrls_day.xml | 2 - ...eractionMatch__Contents.getContentNames_day.xml | 2 - ...ractionMatch__Contents.getContentPieces_day.xml | 2 - ...ractionMatch__Live.getLastVisitsDetails_day.xml | 199 ---- ...contentTargetMatch__Actions.getPageUrls_day.xml | 2 - ...ntTargetMatch__Contents.getContentNames_day.xml | 12 - ...tTargetMatch__Contents.getContentPieces_day.xml | 21 - ...tTargetMatch__Live.getLastVisitsDetails_day.xml | 199 ---- ...ntNameOrPieceMatch__Actions.getPageUrls_day.xml | 2 - ...eOrPieceMatch__Contents.getContentNames_day.xml | 21 - ...OrPieceMatch__Contents.getContentPieces_day.xml | 48 - ...OrPieceMatch__Live.getLastVisitsDetails_day.xml | 199 ---- plugins/Contents/tests/processed/.gitkeep | 0 plugins/CoreConsole/Commands/GenerateTest.php | 54 +- plugins/CoreConsole/TravisYmlView.php | 8 +- .../tests/Integration/TravisYmlViewTest.php | 165 ++++ .../tests/Integration/resources/test.travis.yml | 55 ++ .../CoreConsole/tests/Unit/TravisYmlViewTest.php | 165 ---- .../CoreConsole/tests/resources/test.travis.yml | 55 -- .../tests/Integration/UpdateCommunicationTest.php | 185 ++++ .../tests/UpdateCommunicationTest.php | 185 ---- .../tests/Integration/UpdateCommunicationTest.php | 121 +++ plugins/CoreUpdater/tests/ModelTest.php | 60 -- plugins/CoreUpdater/tests/Unit/ModelTest.php | 60 ++ .../CoreUpdater/tests/UpdateCommunicationTest.php | 121 --- plugins/CustomVariables/.gitignore | 1 + .../tests/CustomVariablesSystemTest.php | 60 -- .../CustomVariables/tests/CustomVariablesTest.php | 43 - .../tests/Integration/CustomVariablesTest.php | 43 + .../tests/Integration/ModelTest.php | 198 ++++ plugins/CustomVariables/tests/ModelTest.php | 200 ---- .../tests/System/CustomVariablesSystemTest.php | 60 ++ ...est__CustomVariables.getCustomVariables_day.xml | 395 ++++++++ ...esSystemTest__Live.getLastVisitsDetails_day.xml | 176 ++++ ...est__CustomVariables.getCustomVariables_day.xml | 395 ++++++++ ...egrationTest__Live.getLastVisitsDetails_day.xml | 176 ++++ ...est__CustomVariables.getCustomVariables_day.xml | 395 ++++++++ ...esSystemTest__Live.getLastVisitsDetails_day.xml | 176 ++++ ...est__CustomVariables.getCustomVariables_day.xml | 395 -------- ...esSystemTest__Live.getLastVisitsDetails_day.xml | 176 ---- ...est__CustomVariables.getCustomVariables_day.xml | 395 -------- ...egrationTest__Live.getLastVisitsDetails_day.xml | 176 ---- ...est__CustomVariables.getCustomVariables_day.xml | 395 -------- ...esSystemTest__Live.getLastVisitsDetails_day.xml | 176 ---- plugins/ExamplePlugin/.gitignore | 2 +- .../tests/Fixtures/SimpleFixtureTrackFewVisits.php | 77 ++ .../ExamplePlugin/tests/Integration/SimpleTest.php | 24 + plugins/ExamplePlugin/tests/SimpleSystemTest.php | 66 -- plugins/ExamplePlugin/tests/SimpleTest.php | 24 - .../tests/System/SimpleSystemTest.php | 66 ++ .../tests/System/expected/test___API.get_day.xml | 30 + .../expected/test___Goals.getItemsSku_day.xml | 12 + .../ExamplePlugin/tests/System/processed/.gitkeep | 0 .../tests/System/processed/test___API.get_day.xml | 30 + .../processed/test___Goals.getItemsSku_day.xml | 12 + plugins/ExamplePlugin/tests/Unit/SimpleTest.php | 24 + .../tests/expected/test___API.get_day.xml | 30 - .../expected/test___Goals.getItemsSku_day.xml | 12 - .../tests/fixtures/SimpleFixtureTrackFewVisits.php | 77 -- plugins/ExamplePlugin/tests/processed/.gitkeep | 0 plugins/Goals/tests/APITest.php | 232 ----- plugins/Goals/tests/Integration/APITest.php | 232 +++++ plugins/Insights/tests/ApiTest.php | 269 ----- plugins/Insights/tests/BaseUnitTest.php | 50 - .../Insights/tests/FilterExcludeLowValueTest.php | 85 -- plugins/Insights/tests/FilterInsightTest.php | 226 ----- plugins/Insights/tests/FilterLimitTest.php | 81 -- plugins/Insights/tests/FilterMinGrowthTest.php | 91 -- plugins/Insights/tests/FilterOrderByTest.php | 95 -- plugins/Insights/tests/InsightReportTest.php | 471 --------- plugins/Insights/tests/Integration/ApiTest.php | 269 +++++ plugins/Insights/tests/Integration/ModelTest.php | 189 ++++ plugins/Insights/tests/ModelTest.php | 189 ---- plugins/Insights/tests/Unit/BaseUnitTest.php | 50 + .../tests/Unit/FilterExcludeLowValueTest.php | 85 ++ plugins/Insights/tests/Unit/FilterInsightTest.php | 226 +++++ plugins/Insights/tests/Unit/FilterLimitTest.php | 81 ++ .../Insights/tests/Unit/FilterMinGrowthTest.php | 91 ++ plugins/Insights/tests/Unit/FilterOrderByTest.php | 95 ++ plugins/Insights/tests/Unit/InsightReportTest.php | 471 +++++++++ .../tests/Integration/LanguagesManagerTest.php | 182 ++++ .../tests/LanguagesManagerTest.php | 182 ---- plugins/LeftMenu/tests/APITest.php | 144 --- plugins/LeftMenu/tests/Integration/APITest.php | 144 +++ plugins/Live/tests/APITest.php | 152 --- plugins/Live/tests/Integration/APITest.php | 152 +++ plugins/Login/tests/Integration/LoginTest.php | 404 ++++++++ plugins/Login/tests/LoginTest.php | 404 -------- .../tests/Integration/MobileMessagingTest.php | 262 +++++ .../MobileMessaging/tests/MobileMessagingTest.php | 262 ----- .../tests/Integration/MultiSitesTest.php | 52 + plugins/MultiSites/tests/MultiSitesTest.php | 52 - plugins/PrivacyManager/tests/AnonymizeIPTest.php | 92 -- .../tests/Integration/PrivacyManagerConfigTest.php | 102 ++ .../tests/Integration/PrivacyManagerTest.php | 86 ++ .../tests/PrivacyManagerConfigTest.php | 102 -- .../PrivacyManager/tests/PrivacyManagerTest.php | 86 -- .../PrivacyManager/tests/Unit/AnonymizeIPTest.php | 92 ++ plugins/Proxy/tests/ProxyTest.php | 48 - plugins/Proxy/tests/Unit/ProxyTest.php | 48 + plugins/Referrers/tests/ReferrersTest.php | 246 ----- plugins/Referrers/tests/Unit/ReferrersTest.php | 246 +++++ plugins/SEO/tests/SEOTest.php | 68 -- plugins/SEO/tests/Unit/SEOTest.php | 68 ++ plugins/ScheduledReports/tests/ApiTest.php | 513 ---------- .../ScheduledReports/tests/Integration/ApiTest.php | 513 ++++++++++ .../tests/Integration/ScheduledReportsTest.php | 163 +++ .../tests/ScheduledReportsTest.php | 163 --- .../tests/Integration/SegmentEditorTest.php | 210 ++++ plugins/SegmentEditor/tests/SegmentEditorTest.php | 210 ---- .../tests/Integration/SiteUrlsTest.php | 145 +++ .../tests/Integration/SitesManagerTest.php | 1000 +++++++++++++++++++ plugins/SitesManager/tests/SiteUrlsTest.php | 145 --- plugins/SitesManager/tests/SitesManagerTest.php | 1000 ------------------- plugins/UserCountry/tests/Unit/UserCountryTest.php | 185 ++++ plugins/UserCountry/tests/UserCountryTest.php | 185 ---- plugins/UserSettings/.gitignore | 1 + .../UserSettings/tests/GetLanguageSystemTest.php | 74 -- .../tests/System/GetLanguageSystemTest.php | 74 ++ .../test___UserSettings.getLanguageCode_day.xml | 157 +++ .../test___UserSettings.getLanguage_day.xml | 135 +++ .../UserSettings/tests/System/processed/.gitkeep | 0 .../test___UserSettings.getLanguageCode_day.xml | 157 +++ .../test___UserSettings.getLanguage_day.xml | 135 +++ .../UserSettings/tests/Unit/UserSettingsTest.php | 1036 ++++++++++++++++++++ plugins/UserSettings/tests/UserSettingsTest.php | 1036 -------------------- .../test___UserSettings.getLanguageCode_day.xml | 157 --- .../test___UserSettings.getLanguage_day.xml | 135 --- plugins/UserSettings/tests/processed/.gitkeep | 0 .../test___UserSettings.getLanguageCode_day.xml | 157 --- .../test___UserSettings.getLanguage_day.xml | 135 --- plugins/UsersManager/tests/APITest.php | 71 -- plugins/UsersManager/tests/Integration/APITest.php | 71 ++ .../tests/Integration/UserPreferencesTest.php | 117 +++ .../tests/Integration/UsersManagerTest.php | 919 +++++++++++++++++ plugins/UsersManager/tests/UserPreferencesTest.php | 117 --- plugins/UsersManager/tests/UsersManagerTest.php | 917 ----------------- 221 files changed, 17020 insertions(+), 15384 deletions(-) delete mode 100644 plugins/API/tests/ConsoleRendererTest.php delete mode 100644 plugins/API/tests/CsvRendererTest.php delete mode 100644 plugins/API/tests/HtmlRendererTest.php create mode 100644 plugins/API/tests/Integration/RowEvolutionTest.php create mode 100644 plugins/API/tests/Integration/RssRendererTest.php delete mode 100644 plugins/API/tests/JsonRendererTest.php delete mode 100644 plugins/API/tests/OriginalRendererTest.php delete mode 100644 plugins/API/tests/PhpRendererTest.php delete mode 100644 plugins/API/tests/RowEvolutionTest.php delete mode 100644 plugins/API/tests/RssRendererTest.php create mode 100644 plugins/API/tests/Unit/ConsoleRendererTest.php create mode 100644 plugins/API/tests/Unit/CsvRendererTest.php create mode 100644 plugins/API/tests/Unit/HtmlRendererTest.php create mode 100644 plugins/API/tests/Unit/JsonRendererTest.php create mode 100644 plugins/API/tests/Unit/OriginalRendererTest.php create mode 100644 plugins/API/tests/Unit/PhpRendererTest.php create mode 100644 plugins/API/tests/Unit/XmlRendererTest.php delete mode 100644 plugins/API/tests/XmlRendererTest.php delete mode 100644 plugins/Actions/tests/ArchiverTest.php create mode 100644 plugins/Actions/tests/Unit/ArchiverTest.php delete mode 100644 plugins/Contents/tests/ContentsTest.php create mode 100644 plugins/Contents/tests/System/ContentsTest.php create mode 100644 plugins/Contents/tests/System/expected/test_Contents_Contents.getContentNames_lastN__API.getProcessedReport_day.xml create mode 100644 plugins/Contents/tests/System/expected/test_Contents_Contents.getContentPieces_lastN__API.getProcessedReport_day.xml create mode 100644 plugins/Contents/tests/System/expected/test_Contents__Actions.getPageUrls_day.xml create mode 100644 plugins/Contents/tests/System/expected/test_Contents__Actions.getPageUrls_month.xml create mode 100644 plugins/Contents/tests/System/expected/test_Contents__Actions.get_day.xml create mode 100644 plugins/Contents/tests/System/expected/test_Contents__Actions.get_month.xml create mode 100644 plugins/Contents/tests/System/expected/test_Contents__Contents.getContentNames_day.xml create mode 100644 plugins/Contents/tests/System/expected/test_Contents__Contents.getContentNames_month.xml create mode 100644 plugins/Contents/tests/System/expected/test_Contents__Contents.getContentPieces_day.xml create mode 100644 plugins/Contents/tests/System/expected/test_Contents__Contents.getContentPieces_month.xml create mode 100644 plugins/Contents/tests/System/expected/test_Contents__Live.getLastVisitsDetails_day.xml create mode 100644 plugins/Contents/tests/System/expected/test_Contents__Live.getLastVisitsDetails_month.xml create mode 100644 plugins/Contents/tests/System/expected/test_Contents_contentInteractionMatch__Actions.getPageUrls_day.xml create mode 100644 plugins/Contents/tests/System/expected/test_Contents_contentInteractionMatch__Contents.getContentNames_day.xml create mode 100644 plugins/Contents/tests/System/expected/test_Contents_contentInteractionMatch__Contents.getContentPieces_day.xml create mode 100644 plugins/Contents/tests/System/expected/test_Contents_contentInteractionMatch__Live.getLastVisitsDetails_day.xml create mode 100644 plugins/Contents/tests/System/expected/test_Contents_contentTargetMatch__Actions.getPageUrls_day.xml create mode 100644 plugins/Contents/tests/System/expected/test_Contents_contentTargetMatch__Contents.getContentNames_day.xml create mode 100644 plugins/Contents/tests/System/expected/test_Contents_contentTargetMatch__Contents.getContentPieces_day.xml create mode 100644 plugins/Contents/tests/System/expected/test_Contents_contentTargetMatch__Live.getLastVisitsDetails_day.xml create mode 100644 plugins/Contents/tests/System/expected/test_ContentscontentNameOrPieceMatch__Actions.getPageUrls_day.xml create mode 100644 plugins/Contents/tests/System/expected/test_ContentscontentNameOrPieceMatch__Contents.getContentNames_day.xml create mode 100644 plugins/Contents/tests/System/expected/test_ContentscontentNameOrPieceMatch__Contents.getContentPieces_day.xml create mode 100644 plugins/Contents/tests/System/expected/test_ContentscontentNameOrPieceMatch__Live.getLastVisitsDetails_day.xml create mode 100644 plugins/Contents/tests/System/processed/.gitkeep create mode 100644 plugins/Contents/tests/System/processed/test_Contents_Contents.getContentNames_lastN__API.getProcessedReport_day.xml create mode 100644 plugins/Contents/tests/System/processed/test_Contents_Contents.getContentPieces_lastN__API.getProcessedReport_day.xml create mode 100644 plugins/Contents/tests/System/processed/test_Contents__Actions.getPageUrls_day.xml create mode 100644 plugins/Contents/tests/System/processed/test_Contents__Actions.getPageUrls_month.xml create mode 100644 plugins/Contents/tests/System/processed/test_Contents__Actions.get_day.xml create mode 100644 plugins/Contents/tests/System/processed/test_Contents__Actions.get_month.xml create mode 100644 plugins/Contents/tests/System/processed/test_Contents__Contents.getContentNames_day.xml create mode 100644 plugins/Contents/tests/System/processed/test_Contents__Contents.getContentNames_month.xml create mode 100644 plugins/Contents/tests/System/processed/test_Contents__Contents.getContentPieces_day.xml create mode 100644 plugins/Contents/tests/System/processed/test_Contents__Contents.getContentPieces_month.xml create mode 100644 plugins/Contents/tests/System/processed/test_Contents__Live.getLastVisitsDetails_day.xml create mode 100644 plugins/Contents/tests/System/processed/test_Contents__Live.getLastVisitsDetails_month.xml create mode 100644 plugins/Contents/tests/System/processed/test_Contents_contentInteractionMatch__Actions.getPageUrls_day.xml create mode 100644 plugins/Contents/tests/System/processed/test_Contents_contentInteractionMatch__Contents.getContentNames_day.xml create mode 100644 plugins/Contents/tests/System/processed/test_Contents_contentInteractionMatch__Contents.getContentPieces_day.xml create mode 100644 plugins/Contents/tests/System/processed/test_Contents_contentInteractionMatch__Live.getLastVisitsDetails_day.xml create mode 100644 plugins/Contents/tests/System/processed/test_Contents_contentTargetMatch__Actions.getPageUrls_day.xml create mode 100644 plugins/Contents/tests/System/processed/test_Contents_contentTargetMatch__Contents.getContentNames_day.xml create mode 100644 plugins/Contents/tests/System/processed/test_Contents_contentTargetMatch__Contents.getContentPieces_day.xml create mode 100644 plugins/Contents/tests/System/processed/test_Contents_contentTargetMatch__Live.getLastVisitsDetails_day.xml create mode 100644 plugins/Contents/tests/System/processed/test_ContentscontentNameOrPieceMatch__Actions.getPageUrls_day.xml create mode 100644 plugins/Contents/tests/System/processed/test_ContentscontentNameOrPieceMatch__Contents.getContentNames_day.xml create mode 100644 plugins/Contents/tests/System/processed/test_ContentscontentNameOrPieceMatch__Contents.getContentPieces_day.xml create mode 100644 plugins/Contents/tests/System/processed/test_ContentscontentNameOrPieceMatch__Live.getLastVisitsDetails_day.xml delete mode 100644 plugins/Contents/tests/expected/test_Contents_Contents.getContentNames_lastN__API.getProcessedReport_day.xml delete mode 100644 plugins/Contents/tests/expected/test_Contents_Contents.getContentPieces_lastN__API.getProcessedReport_day.xml delete mode 100644 plugins/Contents/tests/expected/test_Contents__Actions.getPageUrls_day.xml delete mode 100644 plugins/Contents/tests/expected/test_Contents__Actions.getPageUrls_month.xml delete mode 100644 plugins/Contents/tests/expected/test_Contents__Actions.get_day.xml delete mode 100644 plugins/Contents/tests/expected/test_Contents__Actions.get_month.xml delete mode 100644 plugins/Contents/tests/expected/test_Contents__Contents.getContentNames_day.xml delete mode 100644 plugins/Contents/tests/expected/test_Contents__Contents.getContentNames_month.xml delete mode 100644 plugins/Contents/tests/expected/test_Contents__Contents.getContentPieces_day.xml delete mode 100644 plugins/Contents/tests/expected/test_Contents__Contents.getContentPieces_month.xml delete mode 100644 plugins/Contents/tests/expected/test_Contents__Live.getLastVisitsDetails_day.xml delete mode 100644 plugins/Contents/tests/expected/test_Contents__Live.getLastVisitsDetails_month.xml delete mode 100644 plugins/Contents/tests/expected/test_Contents_contentInteractionMatch__Actions.getPageUrls_day.xml delete mode 100644 plugins/Contents/tests/expected/test_Contents_contentInteractionMatch__Contents.getContentNames_day.xml delete mode 100644 plugins/Contents/tests/expected/test_Contents_contentInteractionMatch__Contents.getContentPieces_day.xml delete mode 100644 plugins/Contents/tests/expected/test_Contents_contentInteractionMatch__Live.getLastVisitsDetails_day.xml delete mode 100644 plugins/Contents/tests/expected/test_Contents_contentTargetMatch__Actions.getPageUrls_day.xml delete mode 100644 plugins/Contents/tests/expected/test_Contents_contentTargetMatch__Contents.getContentNames_day.xml delete mode 100644 plugins/Contents/tests/expected/test_Contents_contentTargetMatch__Contents.getContentPieces_day.xml delete mode 100644 plugins/Contents/tests/expected/test_Contents_contentTargetMatch__Live.getLastVisitsDetails_day.xml delete mode 100644 plugins/Contents/tests/expected/test_ContentscontentNameOrPieceMatch__Actions.getPageUrls_day.xml delete mode 100644 plugins/Contents/tests/expected/test_ContentscontentNameOrPieceMatch__Contents.getContentNames_day.xml delete mode 100644 plugins/Contents/tests/expected/test_ContentscontentNameOrPieceMatch__Contents.getContentPieces_day.xml delete mode 100644 plugins/Contents/tests/expected/test_ContentscontentNameOrPieceMatch__Live.getLastVisitsDetails_day.xml delete mode 100644 plugins/Contents/tests/processed/.gitkeep create mode 100644 plugins/CoreConsole/tests/Integration/TravisYmlViewTest.php create mode 100644 plugins/CoreConsole/tests/Integration/resources/test.travis.yml delete mode 100644 plugins/CoreConsole/tests/Unit/TravisYmlViewTest.php delete mode 100644 plugins/CoreConsole/tests/resources/test.travis.yml create mode 100644 plugins/CorePluginsAdmin/tests/Integration/UpdateCommunicationTest.php delete mode 100644 plugins/CorePluginsAdmin/tests/UpdateCommunicationTest.php create mode 100644 plugins/CoreUpdater/tests/Integration/UpdateCommunicationTest.php delete mode 100644 plugins/CoreUpdater/tests/ModelTest.php create mode 100644 plugins/CoreUpdater/tests/Unit/ModelTest.php delete mode 100644 plugins/CoreUpdater/tests/UpdateCommunicationTest.php create mode 100644 plugins/CustomVariables/.gitignore delete mode 100644 plugins/CustomVariables/tests/CustomVariablesSystemTest.php delete mode 100644 plugins/CustomVariables/tests/CustomVariablesTest.php create mode 100644 plugins/CustomVariables/tests/Integration/CustomVariablesTest.php create mode 100644 plugins/CustomVariables/tests/Integration/ModelTest.php delete mode 100644 plugins/CustomVariables/tests/ModelTest.php create mode 100644 plugins/CustomVariables/tests/System/CustomVariablesSystemTest.php create mode 100644 plugins/CustomVariables/tests/System/expected/test_CustomVariablesSystemTest__CustomVariables.getCustomVariables_day.xml create mode 100644 plugins/CustomVariables/tests/System/expected/test_CustomVariablesSystemTest__Live.getLastVisitsDetails_day.xml create mode 100644 plugins/CustomVariables/tests/System/processed/test_CustomVariablesIntegrationTest__CustomVariables.getCustomVariables_day.xml create mode 100644 plugins/CustomVariables/tests/System/processed/test_CustomVariablesIntegrationTest__Live.getLastVisitsDetails_day.xml create mode 100644 plugins/CustomVariables/tests/System/processed/test_CustomVariablesSystemTest__CustomVariables.getCustomVariables_day.xml create mode 100644 plugins/CustomVariables/tests/System/processed/test_CustomVariablesSystemTest__Live.getLastVisitsDetails_day.xml delete mode 100644 plugins/CustomVariables/tests/expected/test_CustomVariablesSystemTest__CustomVariables.getCustomVariables_day.xml delete mode 100644 plugins/CustomVariables/tests/expected/test_CustomVariablesSystemTest__Live.getLastVisitsDetails_day.xml delete mode 100644 plugins/CustomVariables/tests/processed/test_CustomVariablesIntegrationTest__CustomVariables.getCustomVariables_day.xml delete mode 100644 plugins/CustomVariables/tests/processed/test_CustomVariablesIntegrationTest__Live.getLastVisitsDetails_day.xml delete mode 100644 plugins/CustomVariables/tests/processed/test_CustomVariablesSystemTest__CustomVariables.getCustomVariables_day.xml delete mode 100644 plugins/CustomVariables/tests/processed/test_CustomVariablesSystemTest__Live.getLastVisitsDetails_day.xml create mode 100644 plugins/ExamplePlugin/tests/Fixtures/SimpleFixtureTrackFewVisits.php create mode 100644 plugins/ExamplePlugin/tests/Integration/SimpleTest.php delete mode 100644 plugins/ExamplePlugin/tests/SimpleSystemTest.php delete mode 100644 plugins/ExamplePlugin/tests/SimpleTest.php create mode 100644 plugins/ExamplePlugin/tests/System/SimpleSystemTest.php create mode 100644 plugins/ExamplePlugin/tests/System/expected/test___API.get_day.xml create mode 100644 plugins/ExamplePlugin/tests/System/expected/test___Goals.getItemsSku_day.xml create mode 100644 plugins/ExamplePlugin/tests/System/processed/.gitkeep create mode 100644 plugins/ExamplePlugin/tests/System/processed/test___API.get_day.xml create mode 100644 plugins/ExamplePlugin/tests/System/processed/test___Goals.getItemsSku_day.xml create mode 100644 plugins/ExamplePlugin/tests/Unit/SimpleTest.php delete mode 100644 plugins/ExamplePlugin/tests/expected/test___API.get_day.xml delete mode 100644 plugins/ExamplePlugin/tests/expected/test___Goals.getItemsSku_day.xml delete mode 100644 plugins/ExamplePlugin/tests/fixtures/SimpleFixtureTrackFewVisits.php delete mode 100644 plugins/ExamplePlugin/tests/processed/.gitkeep delete mode 100644 plugins/Goals/tests/APITest.php create mode 100644 plugins/Goals/tests/Integration/APITest.php delete mode 100644 plugins/Insights/tests/ApiTest.php delete mode 100644 plugins/Insights/tests/BaseUnitTest.php delete mode 100644 plugins/Insights/tests/FilterExcludeLowValueTest.php delete mode 100644 plugins/Insights/tests/FilterInsightTest.php delete mode 100644 plugins/Insights/tests/FilterLimitTest.php delete mode 100644 plugins/Insights/tests/FilterMinGrowthTest.php delete mode 100644 plugins/Insights/tests/FilterOrderByTest.php delete mode 100644 plugins/Insights/tests/InsightReportTest.php create mode 100644 plugins/Insights/tests/Integration/ApiTest.php create mode 100644 plugins/Insights/tests/Integration/ModelTest.php delete mode 100644 plugins/Insights/tests/ModelTest.php create mode 100644 plugins/Insights/tests/Unit/BaseUnitTest.php create mode 100644 plugins/Insights/tests/Unit/FilterExcludeLowValueTest.php create mode 100644 plugins/Insights/tests/Unit/FilterInsightTest.php create mode 100644 plugins/Insights/tests/Unit/FilterLimitTest.php create mode 100644 plugins/Insights/tests/Unit/FilterMinGrowthTest.php create mode 100644 plugins/Insights/tests/Unit/FilterOrderByTest.php create mode 100644 plugins/Insights/tests/Unit/InsightReportTest.php create mode 100755 plugins/LanguagesManager/tests/Integration/LanguagesManagerTest.php delete mode 100755 plugins/LanguagesManager/tests/LanguagesManagerTest.php delete mode 100644 plugins/LeftMenu/tests/APITest.php create mode 100644 plugins/LeftMenu/tests/Integration/APITest.php delete mode 100644 plugins/Live/tests/APITest.php create mode 100644 plugins/Live/tests/Integration/APITest.php create mode 100644 plugins/Login/tests/Integration/LoginTest.php delete mode 100644 plugins/Login/tests/LoginTest.php create mode 100644 plugins/MobileMessaging/tests/Integration/MobileMessagingTest.php delete mode 100644 plugins/MobileMessaging/tests/MobileMessagingTest.php create mode 100644 plugins/MultiSites/tests/Integration/MultiSitesTest.php delete mode 100644 plugins/MultiSites/tests/MultiSitesTest.php delete mode 100644 plugins/PrivacyManager/tests/AnonymizeIPTest.php create mode 100644 plugins/PrivacyManager/tests/Integration/PrivacyManagerConfigTest.php create mode 100644 plugins/PrivacyManager/tests/Integration/PrivacyManagerTest.php delete mode 100644 plugins/PrivacyManager/tests/PrivacyManagerConfigTest.php delete mode 100644 plugins/PrivacyManager/tests/PrivacyManagerTest.php create mode 100644 plugins/PrivacyManager/tests/Unit/AnonymizeIPTest.php delete mode 100644 plugins/Proxy/tests/ProxyTest.php create mode 100644 plugins/Proxy/tests/Unit/ProxyTest.php delete mode 100644 plugins/Referrers/tests/ReferrersTest.php create mode 100644 plugins/Referrers/tests/Unit/ReferrersTest.php delete mode 100644 plugins/SEO/tests/SEOTest.php create mode 100644 plugins/SEO/tests/Unit/SEOTest.php delete mode 100644 plugins/ScheduledReports/tests/ApiTest.php create mode 100644 plugins/ScheduledReports/tests/Integration/ApiTest.php create mode 100644 plugins/ScheduledReports/tests/Integration/ScheduledReportsTest.php delete mode 100644 plugins/ScheduledReports/tests/ScheduledReportsTest.php create mode 100644 plugins/SegmentEditor/tests/Integration/SegmentEditorTest.php delete mode 100644 plugins/SegmentEditor/tests/SegmentEditorTest.php create mode 100644 plugins/SitesManager/tests/Integration/SiteUrlsTest.php create mode 100644 plugins/SitesManager/tests/Integration/SitesManagerTest.php delete mode 100644 plugins/SitesManager/tests/SiteUrlsTest.php delete mode 100644 plugins/SitesManager/tests/SitesManagerTest.php create mode 100644 plugins/UserCountry/tests/Unit/UserCountryTest.php delete mode 100644 plugins/UserCountry/tests/UserCountryTest.php create mode 100644 plugins/UserSettings/.gitignore delete mode 100644 plugins/UserSettings/tests/GetLanguageSystemTest.php create mode 100644 plugins/UserSettings/tests/System/GetLanguageSystemTest.php create mode 100644 plugins/UserSettings/tests/System/expected/test___UserSettings.getLanguageCode_day.xml create mode 100644 plugins/UserSettings/tests/System/expected/test___UserSettings.getLanguage_day.xml create mode 100644 plugins/UserSettings/tests/System/processed/.gitkeep create mode 100644 plugins/UserSettings/tests/System/processed/test___UserSettings.getLanguageCode_day.xml create mode 100644 plugins/UserSettings/tests/System/processed/test___UserSettings.getLanguage_day.xml create mode 100644 plugins/UserSettings/tests/Unit/UserSettingsTest.php delete mode 100644 plugins/UserSettings/tests/UserSettingsTest.php delete mode 100644 plugins/UserSettings/tests/expected/test___UserSettings.getLanguageCode_day.xml delete mode 100644 plugins/UserSettings/tests/expected/test___UserSettings.getLanguage_day.xml delete mode 100644 plugins/UserSettings/tests/processed/.gitkeep delete mode 100644 plugins/UserSettings/tests/processed/test___UserSettings.getLanguageCode_day.xml delete mode 100644 plugins/UserSettings/tests/processed/test___UserSettings.getLanguage_day.xml delete mode 100644 plugins/UsersManager/tests/APITest.php create mode 100644 plugins/UsersManager/tests/Integration/APITest.php create mode 100644 plugins/UsersManager/tests/Integration/UserPreferencesTest.php create mode 100644 plugins/UsersManager/tests/Integration/UsersManagerTest.php delete mode 100644 plugins/UsersManager/tests/UserPreferencesTest.php delete mode 100644 plugins/UsersManager/tests/UsersManagerTest.php (limited to 'plugins') diff --git a/plugins/API/tests/ConsoleRendererTest.php b/plugins/API/tests/ConsoleRendererTest.php deleted file mode 100644 index 26357935ff..0000000000 --- a/plugins/API/tests/ConsoleRendererTest.php +++ /dev/null @@ -1,121 +0,0 @@ -builder = $this->makeBuilder(array()); - DataTable\Manager::getInstance()->deleteAll(); - } - - public function test_renderSuccess_shouldAlwaysReturnTrueAndIgnoreMessage() - { - $response = $this->builder->renderSuccess('ok'); - - $this->assertEquals('Success:ok', $response); - } - - public function test_renderException_shouldThrowTheException() - { - $response = $this->builder->renderException('This message should be used', new \BadMethodCallException('The other message')); - - $this->assertEquals('Error: This message should be used', $response); - } - - public function test_renderScalar_shouldReturnTheSameValue() - { - $response = $this->builder->renderScalar(true); - $this->assertSame("- 1 ['0' => 1] [] [idsubtable = ]
-", $response); - - $response = $this->builder->renderScalar(5); - $this->assertSame("- 1 ['0' => 5] [] [idsubtable = ]
-", $response); - - $response = $this->builder->renderScalar('string'); - $this->assertSame("- 1 ['0' => 'string'] [] [idsubtable = ]
-", $response); - } - - public function test_renderObject_shouldReturAnError() - { - $response = $this->builder->renderObject(new \stdClass()); - - $this->assertEquals('Error: The API cannot handle this data structure.', $response); - } - - public function test_renderResource_shouldReturAnError() - { - $response = $this->builder->renderResource(new \stdClass()); - - $this->assertEquals('Error: The API cannot handle this data structure.', $response); - } - - public function test_renderDataTable_shouldReturnResult() - { - $dataTable = new DataTable(); - $dataTable->addRowFromSimpleArray(array('nb_visits' => 5, 'nb_random' => 10)); - - $response = $this->builder->renderDataTable($dataTable); - - $this->assertSame("- 1 ['nb_visits' => 5, 'nb_random' => 10] [] [idsubtable = ]
-", $response); - } - - public function test_renderArray_ShouldReturnConsoleResult() - { - $input = array(1, 2, 5, 'string', 10); - - $response = $this->builder->renderArray($input); - - $this->assertSame("- 1 ['0' => 1] [] [idsubtable = ]
-- 2 ['0' => 2] [] [idsubtable = ]
-- 3 ['0' => 5] [] [idsubtable = ]
-- 4 ['0' => 'string'] [] [idsubtable = ]
-- 5 ['0' => 10] [] [idsubtable = ]
-", $response); - } - - /** - * @expectedException \Exception - * @expectedExceptionMessage Data structure returned is not convertible in the requested format - */ - public function test_renderArray_ShouldConvertMultiDimensionalAssociativeArrayToJson() - { - $input = array( - "firstElement" => "isFirst", - "secondElement" => array( - "firstElement" => "isFirst", - "secondElement" => "isSecond", - ), - "thirdElement" => "isThird"); - - $actual = $this->builder->renderArray($input); - $this->assertSame($input, $actual); - } - - private function makeBuilder($request) - { - return new Console($request); - } -} diff --git a/plugins/API/tests/CsvRendererTest.php b/plugins/API/tests/CsvRendererTest.php deleted file mode 100644 index 526d2f3728..0000000000 --- a/plugins/API/tests/CsvRendererTest.php +++ /dev/null @@ -1,283 +0,0 @@ -builder = $this->makeBuilder(array('method' => 'MultiSites_getAll', 'convertToUnicode' => 0)); - } - - public function test_renderSuccess_shouldIncludeMessage() - { - $response = $this->builder->renderSuccess('ok'); - - $this->assertEquals("message -ok", $response); - } - - public function test_renderException_shouldIncludeTheMessageAndNotExceptionMessage() - { - $response = $this->builder->renderException("The error message", new \Exception('The other message')); - - $this->assertEquals('Error: The error message', $response); - } - - public function test_renderException_shouldRespectNewlines() - { - $response = $this->builder->renderException("The\nerror\nmessage", new \Exception('The other message')); - - $this->assertEquals('Error: The -error -message', $response); - } - - public function test_renderObject_shouldReturAnError() - { - $response = $this->builder->renderObject(new \stdClass()); - - $this->assertEquals('Error: The API cannot handle this data structure.', $response); - } - - public function test_renderResource_shouldReturAnError() - { - $response = $this->builder->renderResource(new \stdClass()); - - $this->assertEquals('Error: The API cannot handle this data structure.', $response); - } - - public function test_renderScalar_shouldConvertToUnicodeByDefault() - { - $builder = $this->makeBuilder(array('method' => 'MultiSites_getAll')); - $response = $builder->renderScalar(true); - - $this->assertStringStartsWith(chr(255) . chr(254), $response); - } - - public function test_renderScalar_shouldReturnABooleanAsIntegerWrappedInTable() - { - $response = $this->builder->renderScalar(true); - - $this->assertEquals('value -1', $response); - } - - public function test_renderScalar_shouldReturnAnIntegerWrappedInTable() - { - $response = $this->builder->renderScalar(5); - - $this->assertEquals('value -5', $response); - } - - public function test_renderScalar_shouldReturnAStringWrappedInValue() - { - $response = $this->builder->renderScalar('The Output'); - - $this->assertEquals('value -The Output', $response); - } - - public function test_renderScalar_shouldNotRemoveLineBreaks() - { - $response = $this->builder->renderScalar('The\nOutput'); - - $this->assertEquals('value -The\nOutput', $response); - } - - public function test_renderDataTable_shouldRenderABasicDataTable() - { - $dataTable = new DataTable(); - $dataTable->addRowFromSimpleArray(array('nb_visits' => 5, 'nb_random' => 10)); - - $response = $this->builder->renderDataTable($dataTable); - - $this->assertEquals('nb_visits,nb_random -5,10', $response); - } - - public function test_renderDataTable_shouldNotRenderSubtables_AsItIsNotSupportedYet() - { - $subtable = new DataTable(); - $subtable->addRowFromSimpleArray(array('nb_visits' => 2, 'nb_random' => 6)); - - $dataTable = new DataTable(); - $dataTable->addRowFromSimpleArray(array('nb_visits' => 5, 'nb_random' => 10)); - $dataTable->getFirstRow()->setSubtable($subtable); - - $response = $this->builder->renderDataTable($dataTable); - - $this->assertEquals('nb_visits,nb_random -5,10', $response); - } - - public function test_renderDataTable_shouldRenderDataTableMaps() - { - $map = new DataTable\Map(); - - $dataTable = new DataTable(); - $dataTable->addRowFromSimpleArray(array('nb_visits' => 5, 'nb_random' => 10)); - - $dataTable2 = new DataTable(); - $dataTable2->addRowFromSimpleArray(array('nb_visits' => 3, 'nb_random' => 6)); - - $map->addTable($dataTable, 'table1'); - $map->addTable($dataTable2, 'table2'); - - $response = $this->builder->renderDataTable($map); - - $this->assertEquals('defaultKeyName,nb_visits,nb_random -table1,5,10 -table2,3,6', $response); - } - - public function test_renderDataTable_shouldRenderSimpleDataTable() - { - $dataTable = new DataTable\Simple(); - $dataTable->addRowsFromArray(array('nb_visits' => 3, 'nb_random' => 6)); - - $response = $this->builder->renderDataTable($dataTable); - - $this->assertEquals('nb_visits,nb_random -3,6', $response); - } - - public function test_renderArray_ShouldConvertSimpleArrayToJson() - { - $input = array(1, 2, 5, 'string', 10); - - $response = $this->builder->renderArray($input); - - $this->assertEquals('1 -2 -5 -string -10', $response); - } - - public function test_renderArray_ShouldRenderAnEmptyArray() - { - $response = $this->builder->renderArray(array()); - - $this->assertEquals('No data available', $response); - } - - public function test_renderArray_ShouldConvertAssociativeArrayToJson() - { - $input = array('nb_visits' => 6, 'nb_random' => 8); - - $response = $this->builder->renderArray($input); - - $this->assertEquals('nb_visits,nb_random -6,8', $response); - } - - public function test_renderArray_ShouldConvertsIndexedAssociativeArrayToJson() - { - $input = array( - array('nb_visits' => 6, 'nb_random' => 8), - array('nb_visits' => 3, 'nb_random' => 4) - ); - - $response = $this->builder->renderArray($input); - - $this->assertEquals('nb_visits,nb_random -6,8 -3,4', $response); - } - - public function test_renderArray_ShouldConvertMultiDimensionalStandardArrayToJson() - { - $input = array("firstElement", - array( - "firstElement", - "secondElement", - ), - "thirdElement"); - - $actual = $this->builder->renderArray($input); - $this->assertEquals('0,1,2 -firstElement,, -firstElement,secondElement, -,,thirdElement', $actual); - } - - /** - * @expectedException \Exception - * @expectedExceptionMessage Data structure returned is not convertible in the requested format - */ - public function test_renderArray_ShouldConvertMultiDimensionalAssociativeArrayToJson() - { - $input = array( - "firstElement" => "isFirst", - "secondElement" => array( - "firstElement" => "isFirst", - "secondElement" => "isSecond", - ), - "thirdElement" => "isThird"); - - $this->builder->renderArray($input); - } - - /** - * @expectedException \Exception - * @expectedExceptionMessage Data structure returned is not convertible in the requested format - */ - public function test_renderArray_ShouldConvertMultiDimensionalIndexArrayToJson() - { - $input = array(array("firstElement", - array( - "firstElement", - "secondElement", - ), - "thirdElement")); - - $this->builder->renderArray($input); - } - - /** - * @expectedException \Exception - * @expectedExceptionMessage Data structure returned is not convertible in the requested format - */ - public function test_renderArray_ShouldConvertMultiDimensionalMixedArrayToJson() - { - $input = array( - "firstElement" => "isFirst", - array( - "firstElement", - "secondElement", - ), - "thirdElement" => array( - "firstElement" => "isFirst", - "secondElement" => "isSecond", - ) - ); - - $this->builder->renderArray($input); - } - - private function makeBuilder($request) - { - return new Csv($request); - } -} diff --git a/plugins/API/tests/HtmlRendererTest.php b/plugins/API/tests/HtmlRendererTest.php deleted file mode 100644 index 4cf4f98c9b..0000000000 --- a/plugins/API/tests/HtmlRendererTest.php +++ /dev/null @@ -1,459 +0,0 @@ -builder = $this->makeBuilder(array('method' => 'MultiSites_getAll')); - DataTable\Manager::getInstance()->deleteAll(); - } - - public function test_renderSuccess_shouldIncludeMessage() - { - $response = $this->builder->renderSuccess('ok'); - - $this->assertEquals('Success:ok', $response); - } - - public function test_renderException_shouldIncludeTheMessageAndNotExceptionMessage() - { - $response = $this->builder->renderException("The error message", new \Exception('The other message')); - - $this->assertEquals('The error message', $response); - } - - public function test_renderException_shouldConvertNewLinesToBr() - { - $response = $this->builder->renderException("The\nerror\nmessage", new \Exception('The other message')); - - $this->assertEquals('The
-error
-message', $response); - } - - public function test_renderObject_shouldReturAnError() - { - $response = $this->builder->renderObject(new \stdClass()); - - $this->assertEquals('The API cannot handle this data structure.', $response); - } - - public function test_renderResource_shouldReturAnError() - { - $response = $this->builder->renderResource(new \stdClass()); - - $this->assertEquals('The API cannot handle this data structure.', $response); - } - - public function test_renderScalar_shouldReturnABooleanAsIntegerWrappedInTable() - { - $response = $this->builder->renderScalar(true); - - $this->assertEquals(' - - - - - - - - - - -
value
1
-', $response); - } - - public function test_renderScalar_shouldReturnAnIntegerWrappedInTable() - { - $response = $this->builder->renderScalar(5); - - $this->assertEquals(' - - - - - - - - - - -
value
5
-', $response); - } - - public function test_renderScalar_shouldReturnAStringWrappedInValue() - { - $response = $this->builder->renderScalar('The Output'); - - $this->assertEquals(' - - - - - - - - - - -
value
The Output
-', $response); - } - - public function test_renderScalar_shouldNotRemoveLineBreaks() - { - $response = $this->builder->renderScalar('The\nOutput'); - - $this->assertEquals(' - - - - - - - - - - -
value
The\nOutput
-', $response); - } - - public function test_renderDataTable_shouldRenderABasicDataTable() - { - $dataTable = new DataTable(); - $dataTable->addRowFromSimpleArray(array('nb_visits' => 5, 'nb_random' => 10)); - - $response = $this->builder->renderDataTable($dataTable); - - $this->assertEquals(' - - - - - - - - - - - - -
nb_visitsnb_random
510
-', $response); - } - - public function test_renderDataTable_shouldRenderSubtables() - { - $subtable = new DataTable(); - $subtable->addRowFromSimpleArray(array('nb_visits' => 2, 'nb_random' => 6)); - - $dataTable = new DataTable(); - $dataTable->addRowFromSimpleArray(array('nb_visits' => 5, 'nb_random' => 10)); - $dataTable->getFirstRow()->setSubtable($subtable); - - $response = $this->builder->renderDataTable($dataTable); - - $this->assertEquals(' - - - - - - - - - - - - - - -
nb_visitsnb_random_idSubtable
5101
-', $response); - } - - public function test_renderDataTable_shouldRenderDataTableMaps() - { - $map = new DataTable\Map(); - - $dataTable = new DataTable(); - $dataTable->addRowFromSimpleArray(array('nb_visits' => 5, 'nb_random' => 10)); - - $dataTable2 = new DataTable(); - $dataTable2->addRowFromSimpleArray(array('nb_visits' => 3, 'nb_random' => 6)); - - $map->addTable($dataTable, 'table1'); - $map->addTable($dataTable2, 'table2'); - - $response = $this->builder->renderDataTable($map); - - $this->assertEquals(' - - - - - - - - - - - - - - - - - - - -
_defaultKeyNamenb_visitsnb_random
table1510
table236
-', $response); - } - - public function test_renderDataTable_shouldRenderSimpleDataTable() - { - $dataTable = new DataTable\Simple(); - $dataTable->addRowsFromArray(array('nb_visits' => 3, 'nb_random' => 6)); - - $response = $this->builder->renderDataTable($dataTable); - - $this->assertEquals(' - - - - - - - - - - - - -
nb_visitsnb_random
36
-', $response); - } - - public function test_renderArray_ShouldConvertSimpleArrayToJson() - { - $input = array(1, 2, 5, 'string', 10); - - $response = $this->builder->renderArray($input); - - $this->assertEquals(' - - - - - - - - - - - - - - - - - - - - - - -
value
1
2
5
string
10
-', $response); - } - - public function test_renderArray_ShouldRenderAnEmptyArray() - { - $response = $this->builder->renderArray(array()); - - $this->assertEquals(' - - - - - - -
-', $response); - } - - public function test_renderArray_ShouldConvertAssociativeArrayToJson() - { - $input = array('nb_visits' => 6, 'nb_random' => 8); - - $response = $this->builder->renderArray($input); - - $this->assertEquals(' - - - - - - - - - - - - -
nb_visitsnb_random
68
-', $response); - } - - public function test_renderArray_ShouldConvertsIndexedAssociativeArrayToJson() - { - $input = array( - array('nb_visits' => 6, 'nb_random' => 8), - array('nb_visits' => 3, 'nb_random' => 4) - ); - - $response = $this->builder->renderArray($input); - - $this->assertEquals(' - - - - - - - - - - - - - - - - -
nb_visitsnb_random
68
34
-', $response); - } - - public function test_renderArray_ShouldConvertMultiDimensionalStandardArrayToJson() - { - $input = array("firstElement", - array( - "firstElement", - "secondElement", - ), - "thirdElement"); - - $actual = $this->builder->renderArray($input); - $this->assertEquals(' - - - - - - - - - - - - - - - - - - - - - - - - -
value12
firstElement--
firstElementsecondElement-
--thirdElement
-', $actual); - } - - /** - * @expectedException \Exception - * @expectedExceptionMessage Data structure returned is not convertible in the requested format - */ - public function test_renderArray_ShouldConvertMultiDimensionalAssociativeArrayToJson() - { - $input = array( - "firstElement" => "isFirst", - "secondElement" => array( - "firstElement" => "isFirst", - "secondElement" => "isSecond", - ), - "thirdElement" => "isThird"); - - $this->builder->renderArray($input); - } - - /** - * @expectedException \Exception - * @expectedExceptionMessage Data structure returned is not convertible in the requested format - */ - public function test_renderArray_ShouldConvertMultiDimensionalIndexArrayToJson() - { - $input = array(array("firstElement", - array( - "firstElement", - "secondElement", - ), - "thirdElement")); - - $this->builder->renderArray($input); - } - - /** - * @expectedException \Exception - * @expectedExceptionMessage Data structure returned is not convertible in the requested format - */ - public function test_renderArray_ShouldConvertMultiDimensionalMixedArrayToJson() - { - $input = array( - "firstElement" => "isFirst", - array( - "firstElement", - "secondElement", - ), - "thirdElement" => array( - "firstElement" => "isFirst", - "secondElement" => "isSecond", - ) - ); - - $this->builder->renderArray($input); - } - - private function makeBuilder($request) - { - return new Html($request); - } -} diff --git a/plugins/API/tests/Integration/RowEvolutionTest.php b/plugins/API/tests/Integration/RowEvolutionTest.php new file mode 100644 index 0000000000..555921e56e --- /dev/null +++ b/plugins/API/tests/Integration/RowEvolutionTest.php @@ -0,0 +1,45 @@ +getRowEvolution(1, 'day', 'last7', 'VisitsSummary', 'get'); + } + + public function test_getRowEvolution_shouldNotTriggerAnException_IfReportHasADimension() + { + $rowEvolution = new RowEvolution(); + $table = $rowEvolution->getRowEvolution(1, 'day', 'last7', 'Actions', 'getPageUrls'); + $this->assertNotEmpty($table); + } + +} diff --git a/plugins/API/tests/Integration/RssRendererTest.php b/plugins/API/tests/Integration/RssRendererTest.php new file mode 100644 index 0000000000..8bc9fb0792 --- /dev/null +++ b/plugins/API/tests/Integration/RssRendererTest.php @@ -0,0 +1,192 @@ +builder = $this->makeBuilder(array('method' => 'MultiSites_getAll', 'idSite' => $idSite)); + } + + public function test_renderSuccess_shouldIncludeMessage() + { + $response = $this->builder->renderSuccess('ok'); + + $this->assertEquals('Success:ok', $response); + } + + public function test_renderException_shouldIncludeTheMessageAndNotExceptionMessage() + { + $response = $this->builder->renderException("The error message", new \Exception('The other message')); + + $this->assertEquals('Error: The error message', $response); + } + + public function test_renderObject_shouldReturAnError() + { + $response = $this->builder->renderObject(new \stdClass()); + + $this->assertEquals('Error: The API cannot handle this data structure.', $response); + } + + public function test_renderResource_shouldReturAnError() + { + $response = $this->builder->renderResource(new \stdClass()); + + $this->assertEquals('Error: The API cannot handle this data structure.', $response); + } + + /** + * @expectedException \Exception + * @expectedExceptionMessage RSS feeds can be generated for one specific website + */ + public function test_renderScalar_shouldFailForBooleanScalar() + { + $this->builder->renderScalar(true); + } + + /** + * @expectedException \Exception + * @expectedExceptionMessage RSS feeds can be generated for one specific website + */ + public function test_renderScalar_shouldFailForIntegerScalar() + { + $this->builder->renderScalar(5); + } + + /** + * @expectedException \Exception + * @expectedExceptionMessage RSS feeds can be generated for one specific website + */ + public function test_renderScalar_shouldFailForStringScalar() + { + $this->builder->renderScalar('string'); + } + + /** + * @expectedException \Exception + * @expectedExceptionMessage RSS feeds can be generated for one specific website + */ + public function test_renderDataTable_shouldFailForDataTable() + { + $dataTable = new DataTable(); + $dataTable->addRowFromSimpleArray(array('nb_visits' => 5, 'nb_random' => 10)); + + $this->builder->renderDataTable($dataTable); + } + + /** + * @expectedException \Exception + * @expectedExceptionMessage RSS feeds can be generated for one specific website + */ + public function test_renderDataTable_shouldFailForSubtables() + { + $subtable = new DataTable(); + $subtable->addRowFromSimpleArray(array('nb_visits' => 2, 'nb_random' => 6)); + + $dataTable = new DataTable(); + $dataTable->addRowFromSimpleArray(array('nb_visits' => 5, 'nb_random' => 10)); + $dataTable->getFirstRow()->setSubtable($subtable); + + $this->builder->renderDataTable($dataTable); + } + + /** + * @expectedException \Exception + * @expectedExceptionMessage RSS feeds can be generated for one specific website + */ + public function test_renderDataTable_shouldFail_IfKeynameIsNotDate() + { + $map = new DataTable\Map(); + + $dataTable = new DataTable(); + $dataTable->addRowFromSimpleArray(array('nb_visits' => 5, 'nb_random' => 10)); + + $map->addTable($dataTable, 'table1'); + $map->addTable($dataTable, 'table2'); + + $this->builder->renderDataTable($map); + } + + public function test_renderDataTable_shouldRenderDataTableMaps_IfKeynameIsDate() + { + $map = new DataTable\Map(); + $map->setKeyName('date'); + $_GET['period'] = 'day'; + + $response = $this->builder->renderDataTable($map); + + unset($_GET['period']); + + $response = preg_replace(array('/(.*)<\/pubDate>/','/(.*)<\/lastBuildDate>/'), '', $response); + + $this->assertEquals(' + + + piwik statistics - RSS + http://piwik.org + Piwik RSS feed + + piwik + en + +', $response); + } + + /** + * @expectedException \Exception + * @expectedExceptionMessage RSS feeds can be generated for one specific website + */ + public function test_renderDataTable_shouldFailForSimpleDataTable() + { + $dataTable = new DataTable\Simple(); + $dataTable->addRowsFromArray(array('nb_visits' => 3, 'nb_random' => 6)); + + $this->builder->renderDataTable($dataTable); + } + + /** + * @expectedException \Exception + * @expectedExceptionMessage RSS feeds can be generated for one specific website + */ + public function test_renderArray_ShouldFailForArrays() + { + $input = array(1, 2, 5, 'string', 10); + + $this->builder->renderArray($input); + } + + private function makeBuilder($request) + { + return new Rss($request); + } +} diff --git a/plugins/API/tests/JsonRendererTest.php b/plugins/API/tests/JsonRendererTest.php deleted file mode 100644 index fc1bf5d502..0000000000 --- a/plugins/API/tests/JsonRendererTest.php +++ /dev/null @@ -1,385 +0,0 @@ -jsonBuilder = $this->makeBuilder(array()); - DataTable\Manager::getInstance()->deleteAll(); - } - - public function test_renderSuccess_shouldIncludeMessage() - { - $response = $this->jsonBuilder->renderSuccess('ok'); - - $this->assertEquals('{"result":"success","message":"ok"}', $response); - $this->assertEquals((array) array('result' => 'success', 'message' => 'ok'), json_decode($response, true)); - $this->assertNoJsonError($response); - } - - public function test_renderSuccess_shouldWrapIfEnabledAndCallbackShouldBePreferred() - { - $builder = $this->makeBuilder(array('callback' => 'myName', 'jsoncallback' => 'myOther')); - $response = $builder->renderSuccess('ok'); - - $this->assertEquals('myName({"result":"success","message":"ok"})', $response); - $this->assertNoJsonError($response); - } - - public function test_renderSuccess_shouldWrapIfEnabledAndFallbackToJsonCallbackIfCallbackNotSet() - { - $builder = $this->makeBuilder(array('jsoncallback' => 'myOther')); - $response = $builder->renderSuccess('ok'); - - $this->assertEquals('myOther({"result":"success","message":"ok"})', $response); - $this->assertNoJsonError($response); - } - - public function test_renderSuccess_shouldNotWrapIfCallbackContainsInvalidCharacters() - { - $builder = $this->makeBuilder(array('callback' => 'myOther#?._kek')); - $response = $builder->renderSuccess('ok'); - - $this->assertEquals('{"result":"success","message":"ok"}', $response); - $this->assertNoJsonError($response); - } - - public function test_renderException_shouldIncludeTheMessageAndNotExceptionMessage() - { - $response = $this->jsonBuilder->renderException("The error message", new \Exception('The other message')); - - $this->assertEquals('{"result":"error","message":"The error message"}', $response); - $this->assertEquals((array) array('result' => 'error', 'message' => 'The error message'), json_decode($response, true)); - $this->assertNoJsonError($response); - } - - public function test_renderException_shouldRemoveWhitespace() - { - $response = $this->jsonBuilder->renderException("The\nerror\r\nmessage", new \Exception()); - - $this->assertEquals('{"result":"error","message":"Theerrormessage"}', $response); - $this->assertEquals((array) array('result' => 'error', 'message' => 'Theerrormessage'), json_decode($response, true)); - $this->assertNoJsonError($response); - } - - public function test_renderException_shouldWrapIfEnabled() - { - $builder = $this->makeBuilder(array('callback' => 'myName')); - $response = $builder->renderException('error', new \Exception()); - - $this->assertEquals('myName({"result":"error","message":"error"})', $response); - $this->assertNoJsonError($response); - } - - public function test_renderObject_shouldReturAnError() - { - $response = $this->jsonBuilder->renderObject(new \stdClass()); - - $this->assertEquals('{"result":"error","message":"The API cannot handle this data structure."}', $response); - $this->assertNoJsonError($response); - } - - public function test_renderResource_shouldReturAnError() - { - $response = $this->jsonBuilder->renderResource(new \stdClass()); - - $this->assertEquals('{"result":"error","message":"The API cannot handle this data structure."}', $response); - $this->assertNoJsonError($response); - } - - public function test_renderScalar_shouldReturnABooleanWrappedInValue() - { - $response = $this->jsonBuilder->renderScalar(true); - - $this->assertEquals('{"value":true}', $response); - $this->assertNoJsonError($response); - } - - public function test_renderScalar_shouldReturnAnIntegerWrappedInValue() - { - $response = $this->jsonBuilder->renderScalar(5); - - $this->assertEquals('{"value":5}', $response); - $this->assertNoJsonError($response); - } - - public function test_renderScalar_shouldReturnAStringWrappedInValue() - { - $response = $this->jsonBuilder->renderScalar('The Output'); - - $this->assertEquals('{"value":"The Output"}', $response); - $this->assertNoJsonError($response); - } - - public function test_renderScalar_shouldNotRemoveLineBreaks() - { - $response = $this->jsonBuilder->renderScalar('The\nOutput'); - - $this->assertEquals('{"value":"The\\\\nOutput"}', $response); - $this->assertNoJsonError($response); - } - - public function test_renderScalar_shouldWrapJsonIfNeeded() - { - $builder = $this->makeBuilder(array('callback' => 'myName')); - $response = $builder->renderScalar(true); - - $this->assertEquals('myName({"value":true})', $response); - $this->assertNoJsonError($response); - } - - public function test_renderDataTable_shouldRenderABasicDataTable() - { - $dataTable = new DataTable(); - $dataTable->addRowFromSimpleArray(array('nb_visits' => 5, 'nb_random' => 10)); - - $response = $this->jsonBuilder->renderDataTable($dataTable); - - $this->assertEquals('[{"nb_visits":5,"nb_random":10}]', $response); - $this->assertNoJsonError($response); - } - - public function test_renderDataTable_shouldRenderSubtables() - { - $subtable = new DataTable(); - $subtable->addRowFromSimpleArray(array('nb_visits' => 2, 'nb_random' => 6)); - - $dataTable = new DataTable(); - $dataTable->addRowFromSimpleArray(array('nb_visits' => 5, 'nb_random' => 10)); - $dataTable->getFirstRow()->setSubtable($subtable); - - $response = $this->jsonBuilder->renderDataTable($dataTable); - - $this->assertEquals('[{"nb_visits":5,"nb_random":10,"idsubdatatable":1}]', $response); - $this->assertNoJsonError($response); - } - - public function test_renderDataTable_shouldRenderDataTableMaps() - { - $map = new DataTable\Map(); - - $dataTable = new DataTable(); - $dataTable->addRowFromSimpleArray(array('nb_visits' => 5, 'nb_random' => 10)); - - $dataTable2 = new DataTable(); - $dataTable2->addRowFromSimpleArray(array('nb_visits' => 3, 'nb_random' => 6)); - - $map->addTable($dataTable, 'table1'); - $map->addTable($dataTable2, 'table2'); - - $response = $this->jsonBuilder->renderDataTable($map); - - $this->assertEquals('{"table1":[{"nb_visits":5,"nb_random":10}],"table2":[{"nb_visits":3,"nb_random":6}]}', $response); - $this->assertNoJsonError($response); - } - - public function test_renderDataTable_shouldRenderSimpleDataTable() - { - $dataTable = new DataTable\Simple(); - $dataTable->addRowsFromArray(array('nb_visits' => 3, 'nb_random' => 6)); - - $response = $this->jsonBuilder->renderDataTable($dataTable); - - $this->assertEquals('{"nb_visits":3,"nb_random":6}', $response); - $this->assertNoJsonError($response); - } - - public function test_renderDataTable_shouldWrapADataTable() - { - $builder = $this->makeBuilder(array('callback' => 'myName')); - $dataTable = new DataTable(); - $dataTable->addRowFromSimpleArray(array('nb_visits' => 5, 'nb_random' => 10)); - - $response = $builder->renderDataTable($dataTable); - - $this->assertEquals('myName([{"nb_visits":5,"nb_random":10}])', $response); - $this->assertNoJsonError($response); - } - - public function test_renderArray_ShouldConvertSimpleArrayToJson() - { - $input = array(1, 2, 5, 'string', 10); - - $response = $this->jsonBuilder->renderArray($input); - - $this->assertEquals('[1,2,5,"string",10]', $response); - $this->assertNoJsonError($response); - } - - public function test_renderArray_ShouldWrapJsonIfRequested() - { - $input = array(1, 2, 5, 'string', 10); - - $builder = $this->makeBuilder(array('jsoncallback' => 'myName')); - $response = $builder->renderArray($input); - - $this->assertEquals('myName([1,2,5,"string",10])', $response); - } - - public function test_renderArray_ShouldRenderAnEmptyArray() - { - $response = $this->jsonBuilder->renderArray(array()); - - $this->assertEquals('[]', $response); - $this->assertNoJsonError($response); - } - - public function test_renderArray_ShouldConvertAssociativeArrayToJson() - { - $input = array('nb_visits' => 6, 'nb_random' => 8); - - $response = $this->jsonBuilder->renderArray($input); - $expected = json_encode($input); - - $this->assertEquals($expected, $response); - $this->assertNoJsonError($response); - } - - public function test_renderArray_ShouldConvertsIndexedAssociativeArrayToJson() - { - $input = array( - array('nb_visits' => 6, 'nb_random' => 8), - array('nb_visits' => 3, 'nb_random' => 4) - ); - - $response = $this->jsonBuilder->renderArray($input); - $expected = json_encode($input); - - $this->assertEquals($expected, $response); - $this->assertNoJsonError($response); - } - - public function test_renderArray_ShouldConvertMultiDimensionalStandardArrayToJson() - { - $input = array("firstElement", - array( - "firstElement", - "secondElement", - ), - "thirdElement"); - - $expected = json_encode($input); - - $actual = $this->jsonBuilder->renderArray($input); - $this->assertEquals($expected, $actual); - $this->assertNoJsonError($actual); - } - - public function test_renderArray_ShouldConvertMultiDimensionalAssociativeArrayToJson() - { - $input = array( - "firstElement" => "isFirst", - "secondElement" => array( - "firstElement" => "isFirst", - "secondElement" => "isSecond", - ), - "thirdElement" => "isThird"); - - $expected = json_encode($input); - - $actual = $this->jsonBuilder->renderArray($input); - $this->assertEquals($expected, $actual); - $this->assertNoJsonError($actual); - } - - public function test_renderArray_ShouldConvertSingleDimensionalAssociativeArrayToJson() - { - $input = array( - "fistElement" => "isFirst", - "secondElement" => "isSecond" - ); - - $expected = json_encode($input); - - $actual = $this->jsonBuilder->renderArray($input); - $this->assertEquals($expected, $actual); - $this->assertNoJsonError($actual); - } - - public function test_renderArray_ShouldConvertMultiDimensionalIndexArrayToJson() - { - $input = array(array("firstElement", - array( - "firstElement", - "secondElement", - ), - "thirdElement")); - - $expected = json_encode($input); - - $actual = $this->jsonBuilder->renderArray($input); - $this->assertEquals($expected, $actual); - $this->assertNoJsonError($actual); - } - - public function test_renderArray_ShouldConvertMultiDimensionalMixedArrayToJson() - { - $input = array( - "firstElement" => "isFirst", - array( - "firstElement", - "secondElement", - ), - "thirdElement" => array( - "firstElement" => "isFirst", - "secondElement" => "isSecond", - ) - ); - - $expected = json_encode($input); - - $actual = $this->jsonBuilder->renderArray($input); - $this->assertEquals($expected, $actual); - $this->assertNoJsonError($actual); - } - - /** - * backwards compatibility test - */ - public function test_oldJson_renderArray_ShouldConvertSingleDimensionalAssociativeArray() - { - $input = array( - "firstElement" => "isFirst", - "secondElement" => "isSecond" - ); - - $expected = '[{"firstElement":"isFirst","secondElement":"isSecond"}]'; - - $oldJsonBuilder = new Json($input); - $actual = $oldJsonBuilder->renderArray($input); - $this->assertEquals($expected, $actual); - $this->assertNoJsonError($actual); - } - - private function makeBuilder($request) - { - return new Json2($request); - } - - private function assertNoJsonError($response) - { - return null !== json_decode($response); - } -} diff --git a/plugins/API/tests/OriginalRendererTest.php b/plugins/API/tests/OriginalRendererTest.php deleted file mode 100644 index 40a3575ec7..0000000000 Binary files a/plugins/API/tests/OriginalRendererTest.php and /dev/null differ diff --git a/plugins/API/tests/PhpRendererTest.php b/plugins/API/tests/PhpRendererTest.php deleted file mode 100644 index 5234db8df1..0000000000 --- a/plugins/API/tests/PhpRendererTest.php +++ /dev/null @@ -1,218 +0,0 @@ -builder = $this->makeBuilder(array('serialize' => 0)); - DataTable\Manager::getInstance()->deleteAll(); - } - - public function test_renderSuccess_shouldAlwaysReturnTrueAndIgnoreMessage() - { - $response = $this->builder->renderSuccess('ok'); - $expected = array('result' => 'success', 'message' => 'ok'); - - $this->assertEquals($expected, $response); - } - - public function test_renderSuccess_shouldSerializeByDefault() - { - $response = $this->makeBuilder(array())->renderSuccess('ok'); - $expected = 'a:2:{s:6:"result";s:7:"success";s:7:"message";s:2:"ok";}'; - - $this->assertEquals($expected, $response); - } - - public function test_renderException_shouldReturnTheMessageAndNotTheExceptionMessage() - { - $response = $this->builder->renderException('This message should be ignored', new \BadMethodCallException('The other message')); - $expected = array('result' => 'error', 'message' => 'This message should be ignored'); - - $this->assertEquals($expected, $response); - } - - public function test_renderException_shouldSerializeByDefault() - { - $response = $this->makeBuilder(array())->renderException('This message should be ignored', new \BadMethodCallException('The other message')); - $expected = 'a:2:{s:6:"result";s:5:"error";s:7:"message";s:30:"This message should be ignored";}'; - - $this->assertEquals($expected, $response); - } - - public function test_renderScalar_shouldReturnTheSameValue() - { - $response = $this->builder->renderScalar(true); - $this->assertEquals(true, $response); - - $response = $this->builder->renderScalar(5); - $this->assertEquals(5, $response); - - $response = $this->builder->renderScalar('string'); - $this->assertEquals('string', $response); - } - - public function test_renderObject_shouldReturnTheSameValue() - { - $response = $this->builder->renderObject($this); - $expected = array('result' => 'error', 'message' => 'The API cannot handle this data structure.'); - - $this->assertEquals($expected, $response); - } - - public function test_renderResource_shouldReturnTheSameValue() - { - $resource = curl_init(); - $response = $this->builder->renderResource($resource); - $expected = array('result' => 'error', 'message' => 'The API cannot handle this data structure.'); - - $this->assertEquals($expected, $response); - } - - public function test_renderDataTable_shouldNotSerializeIfDisabled() - { - $dataTable = new DataTable(); - $dataTable->addRowFromSimpleArray(array('nb_visits' => 5, 'nb_random' => 10)); - - $response = $this->builder->renderDataTable($dataTable); - $expected = array( - array('nb_visits' => 5, 'nb_random' => 10) - ); - $this->assertEquals($expected, $response); - } - - public function test_renderDataTable_shouldSerializeByDefault() - { - $dataTable = new DataTable(); - $dataTable->addRowFromSimpleArray(array('nb_visits' => 5, 'nb_random' => 10)); - - $builder = $this->makeBuilder(array()); - $response = $builder->renderDataTable($dataTable); - - $expected = 'a:1:{i:0;a:2:{s:9:"nb_visits";i:5;s:9:"nb_random";i:10;}}'; - $this->assertSame($expected, $response); - } - - public function test_renderDataTable_shouldRenderSubtables() - { - $subtable = new DataTable(); - $subtable->addRowFromSimpleArray(array('nb_visits' => 2, 'nb_random' => 6)); - - $dataTable = new DataTable(); - $dataTable->addRowFromSimpleArray(array('nb_visits' => 5, 'nb_random' => 10)); - $dataTable->getFirstRow()->setSubtable($subtable); - - $response = $this->builder->renderDataTable($dataTable); - $expected = array(array('nb_visits' => 5, 'nb_random' => 10, 'idsubdatatable' => 1)); - - $this->assertEquals($expected, $response); - } - - public function test_renderDataTable_shouldRenderDataTableMaps() - { - $map = new DataTable\Map(); - - $dataTable = new DataTable(); - $dataTable->addRowFromSimpleArray(array('nb_visits' => 5, 'nb_random' => 10)); - - $dataTable2 = new DataTable(); - $dataTable2->addRowFromSimpleArray(array('nb_visits' => 3, 'nb_random' => 6)); - - $map->addTable($dataTable, 'table1'); - $map->addTable($dataTable2, 'table2'); - - $response = $this->builder->renderDataTable($map); - $expected = array( - 'table1' => array(array('nb_visits' => 5, 'nb_random' => 10)), - 'table2' => array(array('nb_visits' => 3, 'nb_random' => 6)) - ); - - $this->assertEquals($expected, $response); - } - - public function test_renderDataTable_shouldRenderSimpleDataTable() - { - $dataTable = new DataTable\Simple(); - $dataTable->addRowsFromArray(array('nb_visits' => 3, 'nb_random' => 6)); - - $response = $this->builder->renderDataTable($dataTable); - $expected = array('nb_visits' => 3, 'nb_random' => 6); - - $this->assertEquals($expected, $response); - } - - public function test_renderArray_ShouldReturnSameArrayNotSerialize() - { - $input = array(1, 2, 5, 'string', 10); - - // builder has serialize=0 - $response = $this->builder->renderArray($input); - - $this->assertSame($input, $response); - } - - public function test_renderArray_ShouldSerializeByDefault() - { - $builder = $this->makeBuilder(array()); - $input = array(1, 2, 5, 'string', 10); - - $response = $builder->renderArray($input); - - $this->assertSame('a:5:{i:0;i:1;i:1;i:2;i:2;i:5;i:3;s:6:"string";i:4;i:10;}', $response); - } - - public function test_renderArray_ShouldSerializeByDefaulMultiDimensionalArray() - { - $input = array( - "firstElement" => "isFirst", - "secondElement" => array( - "firstElement" => "isFirst", - "secondElement" => "isSecond", - ), - "thirdElement" => "isThird"); - - $builder = $this->makeBuilder(array()); - $actual = $builder->renderArray($input); - $this->assertSame( serialize($input), $actual); - } - - public function test_renderArray_ShouldConvertMultiDimensionalAssociativeArrayToJson() - { - $input = array( - "firstElement" => "isFirst", - "secondElement" => array( - "firstElement" => "isFirst", - "secondElement" => "isSecond", - ), - "thirdElement" => "isThird"); - - $actual = $this->builder->renderArray($input); - $this->assertSame($input, $actual); - } - - private function makeBuilder($request) - { - return new Php($request); - } -} diff --git a/plugins/API/tests/RowEvolutionTest.php b/plugins/API/tests/RowEvolutionTest.php deleted file mode 100644 index 21ea9224bd..0000000000 --- a/plugins/API/tests/RowEvolutionTest.php +++ /dev/null @@ -1,44 +0,0 @@ -getRowEvolution(1, 'day', 'last7', 'VisitsSummary', 'get'); - } - - public function test_getRowEvolution_shouldNotTriggerAnException_IfReportHasADimension() - { - $rowEvolution = new RowEvolution(); - $table = $rowEvolution->getRowEvolution(1, 'day', 'last7', 'Actions', 'getPageUrls'); - $this->assertNotEmpty($table); - } - -} diff --git a/plugins/API/tests/RssRendererTest.php b/plugins/API/tests/RssRendererTest.php deleted file mode 100644 index 7187bae1d2..0000000000 --- a/plugins/API/tests/RssRendererTest.php +++ /dev/null @@ -1,192 +0,0 @@ -builder = $this->makeBuilder(array('method' => 'MultiSites_getAll', 'idSite' => $idSite)); - } - - public function test_renderSuccess_shouldIncludeMessage() - { - $response = $this->builder->renderSuccess('ok'); - - $this->assertEquals('Success:ok', $response); - } - - public function test_renderException_shouldIncludeTheMessageAndNotExceptionMessage() - { - $response = $this->builder->renderException("The error message", new \Exception('The other message')); - - $this->assertEquals('Error: The error message', $response); - } - - public function test_renderObject_shouldReturAnError() - { - $response = $this->builder->renderObject(new \stdClass()); - - $this->assertEquals('Error: The API cannot handle this data structure.', $response); - } - - public function test_renderResource_shouldReturAnError() - { - $response = $this->builder->renderResource(new \stdClass()); - - $this->assertEquals('Error: The API cannot handle this data structure.', $response); - } - - /** - * @expectedException \Exception - * @expectedExceptionMessage RSS feeds can be generated for one specific website - */ - public function test_renderScalar_shouldFailForBooleanScalar() - { - $this->builder->renderScalar(true); - } - - /** - * @expectedException \Exception - * @expectedExceptionMessage RSS feeds can be generated for one specific website - */ - public function test_renderScalar_shouldFailForIntegerScalar() - { - $this->builder->renderScalar(5); - } - - /** - * @expectedException \Exception - * @expectedExceptionMessage RSS feeds can be generated for one specific website - */ - public function test_renderScalar_shouldFailForStringScalar() - { - $this->builder->renderScalar('string'); - } - - /** - * @expectedException \Exception - * @expectedExceptionMessage RSS feeds can be generated for one specific website - */ - public function test_renderDataTable_shouldFailForDataTable() - { - $dataTable = new DataTable(); - $dataTable->addRowFromSimpleArray(array('nb_visits' => 5, 'nb_random' => 10)); - - $this->builder->renderDataTable($dataTable); - } - - /** - * @expectedException \Exception - * @expectedExceptionMessage RSS feeds can be generated for one specific website - */ - public function test_renderDataTable_shouldFailForSubtables() - { - $subtable = new DataTable(); - $subtable->addRowFromSimpleArray(array('nb_visits' => 2, 'nb_random' => 6)); - - $dataTable = new DataTable(); - $dataTable->addRowFromSimpleArray(array('nb_visits' => 5, 'nb_random' => 10)); - $dataTable->getFirstRow()->setSubtable($subtable); - - $this->builder->renderDataTable($dataTable); - } - - /** - * @expectedException \Exception - * @expectedExceptionMessage RSS feeds can be generated for one specific website - */ - public function test_renderDataTable_shouldFail_IfKeynameIsNotDate() - { - $map = new DataTable\Map(); - - $dataTable = new DataTable(); - $dataTable->addRowFromSimpleArray(array('nb_visits' => 5, 'nb_random' => 10)); - - $map->addTable($dataTable, 'table1'); - $map->addTable($dataTable, 'table2'); - - $this->builder->renderDataTable($map); - } - - public function test_renderDataTable_shouldRenderDataTableMaps_IfKeynameIsDate() - { - $map = new DataTable\Map(); - $map->setKeyName('date'); - $_GET['period'] = 'day'; - - $response = $this->builder->renderDataTable($map); - - unset($_GET['period']); - - $response = preg_replace(array('/(.*)<\/pubDate>/','/(.*)<\/lastBuildDate>/'), '', $response); - - $this->assertEquals(' - - - piwik statistics - RSS - http://piwik.org - Piwik RSS feed - - piwik - en - -', $response); - } - - /** - * @expectedException \Exception - * @expectedExceptionMessage RSS feeds can be generated for one specific website - */ - public function test_renderDataTable_shouldFailForSimpleDataTable() - { - $dataTable = new DataTable\Simple(); - $dataTable->addRowsFromArray(array('nb_visits' => 3, 'nb_random' => 6)); - - $this->builder->renderDataTable($dataTable); - } - - /** - * @expectedException \Exception - * @expectedExceptionMessage RSS feeds can be generated for one specific website - */ - public function test_renderArray_ShouldFailForArrays() - { - $input = array(1, 2, 5, 'string', 10); - - $this->builder->renderArray($input); - } - - private function makeBuilder($request) - { - return new Rss($request); - } -} diff --git a/plugins/API/tests/Unit/ConsoleRendererTest.php b/plugins/API/tests/Unit/ConsoleRendererTest.php new file mode 100644 index 0000000000..bd556809ff --- /dev/null +++ b/plugins/API/tests/Unit/ConsoleRendererTest.php @@ -0,0 +1,121 @@ +builder = $this->makeBuilder(array()); + DataTable\Manager::getInstance()->deleteAll(); + } + + public function test_renderSuccess_shouldAlwaysReturnTrueAndIgnoreMessage() + { + $response = $this->builder->renderSuccess('ok'); + + $this->assertEquals('Success:ok', $response); + } + + public function test_renderException_shouldThrowTheException() + { + $response = $this->builder->renderException('This message should be used', new \BadMethodCallException('The other message')); + + $this->assertEquals('Error: This message should be used', $response); + } + + public function test_renderScalar_shouldReturnTheSameValue() + { + $response = $this->builder->renderScalar(true); + $this->assertSame("- 1 ['0' => 1] [] [idsubtable = ]
+", $response); + + $response = $this->builder->renderScalar(5); + $this->assertSame("- 1 ['0' => 5] [] [idsubtable = ]
+", $response); + + $response = $this->builder->renderScalar('string'); + $this->assertSame("- 1 ['0' => 'string'] [] [idsubtable = ]
+", $response); + } + + public function test_renderObject_shouldReturAnError() + { + $response = $this->builder->renderObject(new \stdClass()); + + $this->assertEquals('Error: The API cannot handle this data structure.', $response); + } + + public function test_renderResource_shouldReturAnError() + { + $response = $this->builder->renderResource(new \stdClass()); + + $this->assertEquals('Error: The API cannot handle this data structure.', $response); + } + + public function test_renderDataTable_shouldReturnResult() + { + $dataTable = new DataTable(); + $dataTable->addRowFromSimpleArray(array('nb_visits' => 5, 'nb_random' => 10)); + + $response = $this->builder->renderDataTable($dataTable); + + $this->assertSame("- 1 ['nb_visits' => 5, 'nb_random' => 10] [] [idsubtable = ]
+", $response); + } + + public function test_renderArray_ShouldReturnConsoleResult() + { + $input = array(1, 2, 5, 'string', 10); + + $response = $this->builder->renderArray($input); + + $this->assertSame("- 1 ['0' => 1] [] [idsubtable = ]
+- 2 ['0' => 2] [] [idsubtable = ]
+- 3 ['0' => 5] [] [idsubtable = ]
+- 4 ['0' => 'string'] [] [idsubtable = ]
+- 5 ['0' => 10] [] [idsubtable = ]
+", $response); + } + + /** + * @expectedException \Exception + * @expectedExceptionMessage Data structure returned is not convertible in the requested format + */ + public function test_renderArray_ShouldConvertMultiDimensionalAssociativeArrayToJson() + { + $input = array( + "firstElement" => "isFirst", + "secondElement" => array( + "firstElement" => "isFirst", + "secondElement" => "isSecond", + ), + "thirdElement" => "isThird"); + + $actual = $this->builder->renderArray($input); + $this->assertSame($input, $actual); + } + + private function makeBuilder($request) + { + return new Console($request); + } +} diff --git a/plugins/API/tests/Unit/CsvRendererTest.php b/plugins/API/tests/Unit/CsvRendererTest.php new file mode 100644 index 0000000000..76d16ed515 --- /dev/null +++ b/plugins/API/tests/Unit/CsvRendererTest.php @@ -0,0 +1,283 @@ +builder = $this->makeBuilder(array('method' => 'MultiSites_getAll', 'convertToUnicode' => 0)); + } + + public function test_renderSuccess_shouldIncludeMessage() + { + $response = $this->builder->renderSuccess('ok'); + + $this->assertEquals("message +ok", $response); + } + + public function test_renderException_shouldIncludeTheMessageAndNotExceptionMessage() + { + $response = $this->builder->renderException("The error message", new \Exception('The other message')); + + $this->assertEquals('Error: The error message', $response); + } + + public function test_renderException_shouldRespectNewlines() + { + $response = $this->builder->renderException("The\nerror\nmessage", new \Exception('The other message')); + + $this->assertEquals('Error: The +error +message', $response); + } + + public function test_renderObject_shouldReturAnError() + { + $response = $this->builder->renderObject(new \stdClass()); + + $this->assertEquals('Error: The API cannot handle this data structure.', $response); + } + + public function test_renderResource_shouldReturAnError() + { + $response = $this->builder->renderResource(new \stdClass()); + + $this->assertEquals('Error: The API cannot handle this data structure.', $response); + } + + public function test_renderScalar_shouldConvertToUnicodeByDefault() + { + $builder = $this->makeBuilder(array('method' => 'MultiSites_getAll')); + $response = $builder->renderScalar(true); + + $this->assertStringStartsWith(chr(255) . chr(254), $response); + } + + public function test_renderScalar_shouldReturnABooleanAsIntegerWrappedInTable() + { + $response = $this->builder->renderScalar(true); + + $this->assertEquals('value +1', $response); + } + + public function test_renderScalar_shouldReturnAnIntegerWrappedInTable() + { + $response = $this->builder->renderScalar(5); + + $this->assertEquals('value +5', $response); + } + + public function test_renderScalar_shouldReturnAStringWrappedInValue() + { + $response = $this->builder->renderScalar('The Output'); + + $this->assertEquals('value +The Output', $response); + } + + public function test_renderScalar_shouldNotRemoveLineBreaks() + { + $response = $this->builder->renderScalar('The\nOutput'); + + $this->assertEquals('value +The\nOutput', $response); + } + + public function test_renderDataTable_shouldRenderABasicDataTable() + { + $dataTable = new DataTable(); + $dataTable->addRowFromSimpleArray(array('nb_visits' => 5, 'nb_random' => 10)); + + $response = $this->builder->renderDataTable($dataTable); + + $this->assertEquals('nb_visits,nb_random +5,10', $response); + } + + public function test_renderDataTable_shouldNotRenderSubtables_AsItIsNotSupportedYet() + { + $subtable = new DataTable(); + $subtable->addRowFromSimpleArray(array('nb_visits' => 2, 'nb_random' => 6)); + + $dataTable = new DataTable(); + $dataTable->addRowFromSimpleArray(array('nb_visits' => 5, 'nb_random' => 10)); + $dataTable->getFirstRow()->setSubtable($subtable); + + $response = $this->builder->renderDataTable($dataTable); + + $this->assertEquals('nb_visits,nb_random +5,10', $response); + } + + public function test_renderDataTable_shouldRenderDataTableMaps() + { + $map = new DataTable\Map(); + + $dataTable = new DataTable(); + $dataTable->addRowFromSimpleArray(array('nb_visits' => 5, 'nb_random' => 10)); + + $dataTable2 = new DataTable(); + $dataTable2->addRowFromSimpleArray(array('nb_visits' => 3, 'nb_random' => 6)); + + $map->addTable($dataTable, 'table1'); + $map->addTable($dataTable2, 'table2'); + + $response = $this->builder->renderDataTable($map); + + $this->assertEquals('defaultKeyName,nb_visits,nb_random +table1,5,10 +table2,3,6', $response); + } + + public function test_renderDataTable_shouldRenderSimpleDataTable() + { + $dataTable = new DataTable\Simple(); + $dataTable->addRowsFromArray(array('nb_visits' => 3, 'nb_random' => 6)); + + $response = $this->builder->renderDataTable($dataTable); + + $this->assertEquals('nb_visits,nb_random +3,6', $response); + } + + public function test_renderArray_ShouldConvertSimpleArrayToJson() + { + $input = array(1, 2, 5, 'string', 10); + + $response = $this->builder->renderArray($input); + + $this->assertEquals('1 +2 +5 +string +10', $response); + } + + public function test_renderArray_ShouldRenderAnEmptyArray() + { + $response = $this->builder->renderArray(array()); + + $this->assertEquals('No data available', $response); + } + + public function test_renderArray_ShouldConvertAssociativeArrayToJson() + { + $input = array('nb_visits' => 6, 'nb_random' => 8); + + $response = $this->builder->renderArray($input); + + $this->assertEquals('nb_visits,nb_random +6,8', $response); + } + + public function test_renderArray_ShouldConvertsIndexedAssociativeArrayToJson() + { + $input = array( + array('nb_visits' => 6, 'nb_random' => 8), + array('nb_visits' => 3, 'nb_random' => 4) + ); + + $response = $this->builder->renderArray($input); + + $this->assertEquals('nb_visits,nb_random +6,8 +3,4', $response); + } + + public function test_renderArray_ShouldConvertMultiDimensionalStandardArrayToJson() + { + $input = array("firstElement", + array( + "firstElement", + "secondElement", + ), + "thirdElement"); + + $actual = $this->builder->renderArray($input); + $this->assertEquals('0,1,2 +firstElement,, +firstElement,secondElement, +,,thirdElement', $actual); + } + + /** + * @expectedException \Exception + * @expectedExceptionMessage Data structure returned is not convertible in the requested format + */ + public function test_renderArray_ShouldConvertMultiDimensionalAssociativeArrayToJson() + { + $input = array( + "firstElement" => "isFirst", + "secondElement" => array( + "firstElement" => "isFirst", + "secondElement" => "isSecond", + ), + "thirdElement" => "isThird"); + + $this->builder->renderArray($input); + } + + /** + * @expectedException \Exception + * @expectedExceptionMessage Data structure returned is not convertible in the requested format + */ + public function test_renderArray_ShouldConvertMultiDimensionalIndexArrayToJson() + { + $input = array(array("firstElement", + array( + "firstElement", + "secondElement", + ), + "thirdElement")); + + $this->builder->renderArray($input); + } + + /** + * @expectedException \Exception + * @expectedExceptionMessage Data structure returned is not convertible in the requested format + */ + public function test_renderArray_ShouldConvertMultiDimensionalMixedArrayToJson() + { + $input = array( + "firstElement" => "isFirst", + array( + "firstElement", + "secondElement", + ), + "thirdElement" => array( + "firstElement" => "isFirst", + "secondElement" => "isSecond", + ) + ); + + $this->builder->renderArray($input); + } + + private function makeBuilder($request) + { + return new Csv($request); + } +} diff --git a/plugins/API/tests/Unit/HtmlRendererTest.php b/plugins/API/tests/Unit/HtmlRendererTest.php new file mode 100644 index 0000000000..374f33e0b6 --- /dev/null +++ b/plugins/API/tests/Unit/HtmlRendererTest.php @@ -0,0 +1,459 @@ +builder = $this->makeBuilder(array('method' => 'MultiSites_getAll')); + DataTable\Manager::getInstance()->deleteAll(); + } + + public function test_renderSuccess_shouldIncludeMessage() + { + $response = $this->builder->renderSuccess('ok'); + + $this->assertEquals('Success:ok', $response); + } + + public function test_renderException_shouldIncludeTheMessageAndNotExceptionMessage() + { + $response = $this->builder->renderException("The error message", new \Exception('The other message')); + + $this->assertEquals('The error message', $response); + } + + public function test_renderException_shouldConvertNewLinesToBr() + { + $response = $this->builder->renderException("The\nerror\nmessage", new \Exception('The other message')); + + $this->assertEquals('The
+error
+message', $response); + } + + public function test_renderObject_shouldReturAnError() + { + $response = $this->builder->renderObject(new \stdClass()); + + $this->assertEquals('The API cannot handle this data structure.', $response); + } + + public function test_renderResource_shouldReturAnError() + { + $response = $this->builder->renderResource(new \stdClass()); + + $this->assertEquals('The API cannot handle this data structure.', $response); + } + + public function test_renderScalar_shouldReturnABooleanAsIntegerWrappedInTable() + { + $response = $this->builder->renderScalar(true); + + $this->assertEquals(' + + + + + + + + + + +
value
1
+', $response); + } + + public function test_renderScalar_shouldReturnAnIntegerWrappedInTable() + { + $response = $this->builder->renderScalar(5); + + $this->assertEquals(' + + + + + + + + + + +
value
5
+', $response); + } + + public function test_renderScalar_shouldReturnAStringWrappedInValue() + { + $response = $this->builder->renderScalar('The Output'); + + $this->assertEquals(' + + + + + + + + + + +
value
The Output
+', $response); + } + + public function test_renderScalar_shouldNotRemoveLineBreaks() + { + $response = $this->builder->renderScalar('The\nOutput'); + + $this->assertEquals(' + + + + + + + + + + +
value
The\nOutput
+', $response); + } + + public function test_renderDataTable_shouldRenderABasicDataTable() + { + $dataTable = new DataTable(); + $dataTable->addRowFromSimpleArray(array('nb_visits' => 5, 'nb_random' => 10)); + + $response = $this->builder->renderDataTable($dataTable); + + $this->assertEquals(' + + + + + + + + + + + + +
nb_visitsnb_random
510
+', $response); + } + + public function test_renderDataTable_shouldRenderSubtables() + { + $subtable = new DataTable(); + $subtable->addRowFromSimpleArray(array('nb_visits' => 2, 'nb_random' => 6)); + + $dataTable = new DataTable(); + $dataTable->addRowFromSimpleArray(array('nb_visits' => 5, 'nb_random' => 10)); + $dataTable->getFirstRow()->setSubtable($subtable); + + $response = $this->builder->renderDataTable($dataTable); + + $this->assertEquals(' + + + + + + + + + + + + + + +
nb_visitsnb_random_idSubtable
5101
+', $response); + } + + public function test_renderDataTable_shouldRenderDataTableMaps() + { + $map = new DataTable\Map(); + + $dataTable = new DataTable(); + $dataTable->addRowFromSimpleArray(array('nb_visits' => 5, 'nb_random' => 10)); + + $dataTable2 = new DataTable(); + $dataTable2->addRowFromSimpleArray(array('nb_visits' => 3, 'nb_random' => 6)); + + $map->addTable($dataTable, 'table1'); + $map->addTable($dataTable2, 'table2'); + + $response = $this->builder->renderDataTable($map); + + $this->assertEquals(' + + + + + + + + + + + + + + + + + + + +
_defaultKeyNamenb_visitsnb_random
table1510
table236
+', $response); + } + + public function test_renderDataTable_shouldRenderSimpleDataTable() + { + $dataTable = new DataTable\Simple(); + $dataTable->addRowsFromArray(array('nb_visits' => 3, 'nb_random' => 6)); + + $response = $this->builder->renderDataTable($dataTable); + + $this->assertEquals(' + + + + + + + + + + + + +
nb_visitsnb_random
36
+', $response); + } + + public function test_renderArray_ShouldConvertSimpleArrayToJson() + { + $input = array(1, 2, 5, 'string', 10); + + $response = $this->builder->renderArray($input); + + $this->assertEquals(' + + + + + + + + + + + + + + + + + + + + + + +
value
1
2
5
string
10
+', $response); + } + + public function test_renderArray_ShouldRenderAnEmptyArray() + { + $response = $this->builder->renderArray(array()); + + $this->assertEquals(' + + + + + + +
+', $response); + } + + public function test_renderArray_ShouldConvertAssociativeArrayToJson() + { + $input = array('nb_visits' => 6, 'nb_random' => 8); + + $response = $this->builder->renderArray($input); + + $this->assertEquals(' + + + + + + + + + + + + +
nb_visitsnb_random
68
+', $response); + } + + public function test_renderArray_ShouldConvertsIndexedAssociativeArrayToJson() + { + $input = array( + array('nb_visits' => 6, 'nb_random' => 8), + array('nb_visits' => 3, 'nb_random' => 4) + ); + + $response = $this->builder->renderArray($input); + + $this->assertEquals(' + + + + + + + + + + + + + + + + +
nb_visitsnb_random
68
34
+', $response); + } + + public function test_renderArray_ShouldConvertMultiDimensionalStandardArrayToJson() + { + $input = array("firstElement", + array( + "firstElement", + "secondElement", + ), + "thirdElement"); + + $actual = $this->builder->renderArray($input); + $this->assertEquals(' + + + + + + + + + + + + + + + + + + + + + + + + +
value12
firstElement--
firstElementsecondElement-
--thirdElement
+', $actual); + } + + /** + * @expectedException \Exception + * @expectedExceptionMessage Data structure returned is not convertible in the requested format + */ + public function test_renderArray_ShouldConvertMultiDimensionalAssociativeArrayToJson() + { + $input = array( + "firstElement" => "isFirst", + "secondElement" => array( + "firstElement" => "isFirst", + "secondElement" => "isSecond", + ), + "thirdElement" => "isThird"); + + $this->builder->renderArray($input); + } + + /** + * @expectedException \Exception + * @expectedExceptionMessage Data structure returned is not convertible in the requested format + */ + public function test_renderArray_ShouldConvertMultiDimensionalIndexArrayToJson() + { + $input = array(array("firstElement", + array( + "firstElement", + "secondElement", + ), + "thirdElement")); + + $this->builder->renderArray($input); + } + + /** + * @expectedException \Exception + * @expectedExceptionMessage Data structure returned is not convertible in the requested format + */ + public function test_renderArray_ShouldConvertMultiDimensionalMixedArrayToJson() + { + $input = array( + "firstElement" => "isFirst", + array( + "firstElement", + "secondElement", + ), + "thirdElement" => array( + "firstElement" => "isFirst", + "secondElement" => "isSecond", + ) + ); + + $this->builder->renderArray($input); + } + + private function makeBuilder($request) + { + return new Html($request); + } +} diff --git a/plugins/API/tests/Unit/JsonRendererTest.php b/plugins/API/tests/Unit/JsonRendererTest.php new file mode 100644 index 0000000000..c4fa076483 --- /dev/null +++ b/plugins/API/tests/Unit/JsonRendererTest.php @@ -0,0 +1,385 @@ +jsonBuilder = $this->makeBuilder(array()); + DataTable\Manager::getInstance()->deleteAll(); + } + + public function test_renderSuccess_shouldIncludeMessage() + { + $response = $this->jsonBuilder->renderSuccess('ok'); + + $this->assertEquals('{"result":"success","message":"ok"}', $response); + $this->assertEquals((array) array('result' => 'success', 'message' => 'ok'), json_decode($response, true)); + $this->assertNoJsonError($response); + } + + public function test_renderSuccess_shouldWrapIfEnabledAndCallbackShouldBePreferred() + { + $builder = $this->makeBuilder(array('callback' => 'myName', 'jsoncallback' => 'myOther')); + $response = $builder->renderSuccess('ok'); + + $this->assertEquals('myName({"result":"success","message":"ok"})', $response); + $this->assertNoJsonError($response); + } + + public function test_renderSuccess_shouldWrapIfEnabledAndFallbackToJsonCallbackIfCallbackNotSet() + { + $builder = $this->makeBuilder(array('jsoncallback' => 'myOther')); + $response = $builder->renderSuccess('ok'); + + $this->assertEquals('myOther({"result":"success","message":"ok"})', $response); + $this->assertNoJsonError($response); + } + + public function test_renderSuccess_shouldNotWrapIfCallbackContainsInvalidCharacters() + { + $builder = $this->makeBuilder(array('callback' => 'myOther#?._kek')); + $response = $builder->renderSuccess('ok'); + + $this->assertEquals('{"result":"success","message":"ok"}', $response); + $this->assertNoJsonError($response); + } + + public function test_renderException_shouldIncludeTheMessageAndNotExceptionMessage() + { + $response = $this->jsonBuilder->renderException("The error message", new \Exception('The other message')); + + $this->assertEquals('{"result":"error","message":"The error message"}', $response); + $this->assertEquals((array) array('result' => 'error', 'message' => 'The error message'), json_decode($response, true)); + $this->assertNoJsonError($response); + } + + public function test_renderException_shouldRemoveWhitespace() + { + $response = $this->jsonBuilder->renderException("The\nerror\r\nmessage", new \Exception()); + + $this->assertEquals('{"result":"error","message":"Theerrormessage"}', $response); + $this->assertEquals((array) array('result' => 'error', 'message' => 'Theerrormessage'), json_decode($response, true)); + $this->assertNoJsonError($response); + } + + public function test_renderException_shouldWrapIfEnabled() + { + $builder = $this->makeBuilder(array('callback' => 'myName')); + $response = $builder->renderException('error', new \Exception()); + + $this->assertEquals('myName({"result":"error","message":"error"})', $response); + $this->assertNoJsonError($response); + } + + public function test_renderObject_shouldReturAnError() + { + $response = $this->jsonBuilder->renderObject(new \stdClass()); + + $this->assertEquals('{"result":"error","message":"The API cannot handle this data structure."}', $response); + $this->assertNoJsonError($response); + } + + public function test_renderResource_shouldReturAnError() + { + $response = $this->jsonBuilder->renderResource(new \stdClass()); + + $this->assertEquals('{"result":"error","message":"The API cannot handle this data structure."}', $response); + $this->assertNoJsonError($response); + } + + public function test_renderScalar_shouldReturnABooleanWrappedInValue() + { + $response = $this->jsonBuilder->renderScalar(true); + + $this->assertEquals('{"value":true}', $response); + $this->assertNoJsonError($response); + } + + public function test_renderScalar_shouldReturnAnIntegerWrappedInValue() + { + $response = $this->jsonBuilder->renderScalar(5); + + $this->assertEquals('{"value":5}', $response); + $this->assertNoJsonError($response); + } + + public function test_renderScalar_shouldReturnAStringWrappedInValue() + { + $response = $this->jsonBuilder->renderScalar('The Output'); + + $this->assertEquals('{"value":"The Output"}', $response); + $this->assertNoJsonError($response); + } + + public function test_renderScalar_shouldNotRemoveLineBreaks() + { + $response = $this->jsonBuilder->renderScalar('The\nOutput'); + + $this->assertEquals('{"value":"The\\\\nOutput"}', $response); + $this->assertNoJsonError($response); + } + + public function test_renderScalar_shouldWrapJsonIfNeeded() + { + $builder = $this->makeBuilder(array('callback' => 'myName')); + $response = $builder->renderScalar(true); + + $this->assertEquals('myName({"value":true})', $response); + $this->assertNoJsonError($response); + } + + public function test_renderDataTable_shouldRenderABasicDataTable() + { + $dataTable = new DataTable(); + $dataTable->addRowFromSimpleArray(array('nb_visits' => 5, 'nb_random' => 10)); + + $response = $this->jsonBuilder->renderDataTable($dataTable); + + $this->assertEquals('[{"nb_visits":5,"nb_random":10}]', $response); + $this->assertNoJsonError($response); + } + + public function test_renderDataTable_shouldRenderSubtables() + { + $subtable = new DataTable(); + $subtable->addRowFromSimpleArray(array('nb_visits' => 2, 'nb_random' => 6)); + + $dataTable = new DataTable(); + $dataTable->addRowFromSimpleArray(array('nb_visits' => 5, 'nb_random' => 10)); + $dataTable->getFirstRow()->setSubtable($subtable); + + $response = $this->jsonBuilder->renderDataTable($dataTable); + + $this->assertEquals('[{"nb_visits":5,"nb_random":10,"idsubdatatable":1}]', $response); + $this->assertNoJsonError($response); + } + + public function test_renderDataTable_shouldRenderDataTableMaps() + { + $map = new DataTable\Map(); + + $dataTable = new DataTable(); + $dataTable->addRowFromSimpleArray(array('nb_visits' => 5, 'nb_random' => 10)); + + $dataTable2 = new DataTable(); + $dataTable2->addRowFromSimpleArray(array('nb_visits' => 3, 'nb_random' => 6)); + + $map->addTable($dataTable, 'table1'); + $map->addTable($dataTable2, 'table2'); + + $response = $this->jsonBuilder->renderDataTable($map); + + $this->assertEquals('{"table1":[{"nb_visits":5,"nb_random":10}],"table2":[{"nb_visits":3,"nb_random":6}]}', $response); + $this->assertNoJsonError($response); + } + + public function test_renderDataTable_shouldRenderSimpleDataTable() + { + $dataTable = new DataTable\Simple(); + $dataTable->addRowsFromArray(array('nb_visits' => 3, 'nb_random' => 6)); + + $response = $this->jsonBuilder->renderDataTable($dataTable); + + $this->assertEquals('{"nb_visits":3,"nb_random":6}', $response); + $this->assertNoJsonError($response); + } + + public function test_renderDataTable_shouldWrapADataTable() + { + $builder = $this->makeBuilder(array('callback' => 'myName')); + $dataTable = new DataTable(); + $dataTable->addRowFromSimpleArray(array('nb_visits' => 5, 'nb_random' => 10)); + + $response = $builder->renderDataTable($dataTable); + + $this->assertEquals('myName([{"nb_visits":5,"nb_random":10}])', $response); + $this->assertNoJsonError($response); + } + + public function test_renderArray_ShouldConvertSimpleArrayToJson() + { + $input = array(1, 2, 5, 'string', 10); + + $response = $this->jsonBuilder->renderArray($input); + + $this->assertEquals('[1,2,5,"string",10]', $response); + $this->assertNoJsonError($response); + } + + public function test_renderArray_ShouldWrapJsonIfRequested() + { + $input = array(1, 2, 5, 'string', 10); + + $builder = $this->makeBuilder(array('jsoncallback' => 'myName')); + $response = $builder->renderArray($input); + + $this->assertEquals('myName([1,2,5,"string",10])', $response); + } + + public function test_renderArray_ShouldRenderAnEmptyArray() + { + $response = $this->jsonBuilder->renderArray(array()); + + $this->assertEquals('[]', $response); + $this->assertNoJsonError($response); + } + + public function test_renderArray_ShouldConvertAssociativeArrayToJson() + { + $input = array('nb_visits' => 6, 'nb_random' => 8); + + $response = $this->jsonBuilder->renderArray($input); + $expected = json_encode($input); + + $this->assertEquals($expected, $response); + $this->assertNoJsonError($response); + } + + public function test_renderArray_ShouldConvertsIndexedAssociativeArrayToJson() + { + $input = array( + array('nb_visits' => 6, 'nb_random' => 8), + array('nb_visits' => 3, 'nb_random' => 4) + ); + + $response = $this->jsonBuilder->renderArray($input); + $expected = json_encode($input); + + $this->assertEquals($expected, $response); + $this->assertNoJsonError($response); + } + + public function test_renderArray_ShouldConvertMultiDimensionalStandardArrayToJson() + { + $input = array("firstElement", + array( + "firstElement", + "secondElement", + ), + "thirdElement"); + + $expected = json_encode($input); + + $actual = $this->jsonBuilder->renderArray($input); + $this->assertEquals($expected, $actual); + $this->assertNoJsonError($actual); + } + + public function test_renderArray_ShouldConvertMultiDimensionalAssociativeArrayToJson() + { + $input = array( + "firstElement" => "isFirst", + "secondElement" => array( + "firstElement" => "isFirst", + "secondElement" => "isSecond", + ), + "thirdElement" => "isThird"); + + $expected = json_encode($input); + + $actual = $this->jsonBuilder->renderArray($input); + $this->assertEquals($expected, $actual); + $this->assertNoJsonError($actual); + } + + public function test_renderArray_ShouldConvertSingleDimensionalAssociativeArrayToJson() + { + $input = array( + "fistElement" => "isFirst", + "secondElement" => "isSecond" + ); + + $expected = json_encode($input); + + $actual = $this->jsonBuilder->renderArray($input); + $this->assertEquals($expected, $actual); + $this->assertNoJsonError($actual); + } + + public function test_renderArray_ShouldConvertMultiDimensionalIndexArrayToJson() + { + $input = array(array("firstElement", + array( + "firstElement", + "secondElement", + ), + "thirdElement")); + + $expected = json_encode($input); + + $actual = $this->jsonBuilder->renderArray($input); + $this->assertEquals($expected, $actual); + $this->assertNoJsonError($actual); + } + + public function test_renderArray_ShouldConvertMultiDimensionalMixedArrayToJson() + { + $input = array( + "firstElement" => "isFirst", + array( + "firstElement", + "secondElement", + ), + "thirdElement" => array( + "firstElement" => "isFirst", + "secondElement" => "isSecond", + ) + ); + + $expected = json_encode($input); + + $actual = $this->jsonBuilder->renderArray($input); + $this->assertEquals($expected, $actual); + $this->assertNoJsonError($actual); + } + + /** + * backwards compatibility test + */ + public function test_oldJson_renderArray_ShouldConvertSingleDimensionalAssociativeArray() + { + $input = array( + "firstElement" => "isFirst", + "secondElement" => "isSecond" + ); + + $expected = '[{"firstElement":"isFirst","secondElement":"isSecond"}]'; + + $oldJsonBuilder = new Json($input); + $actual = $oldJsonBuilder->renderArray($input); + $this->assertEquals($expected, $actual); + $this->assertNoJsonError($actual); + } + + private function makeBuilder($request) + { + return new Json2($request); + } + + private function assertNoJsonError($response) + { + return null !== json_decode($response); + } +} diff --git a/plugins/API/tests/Unit/OriginalRendererTest.php b/plugins/API/tests/Unit/OriginalRendererTest.php new file mode 100644 index 0000000000..bed40d1e29 Binary files /dev/null and b/plugins/API/tests/Unit/OriginalRendererTest.php differ diff --git a/plugins/API/tests/Unit/PhpRendererTest.php b/plugins/API/tests/Unit/PhpRendererTest.php new file mode 100644 index 0000000000..77a5efa568 --- /dev/null +++ b/plugins/API/tests/Unit/PhpRendererTest.php @@ -0,0 +1,218 @@ +builder = $this->makeBuilder(array('serialize' => 0)); + DataTable\Manager::getInstance()->deleteAll(); + } + + public function test_renderSuccess_shouldAlwaysReturnTrueAndIgnoreMessage() + { + $response = $this->builder->renderSuccess('ok'); + $expected = array('result' => 'success', 'message' => 'ok'); + + $this->assertEquals($expected, $response); + } + + public function test_renderSuccess_shouldSerializeByDefault() + { + $response = $this->makeBuilder(array())->renderSuccess('ok'); + $expected = 'a:2:{s:6:"result";s:7:"success";s:7:"message";s:2:"ok";}'; + + $this->assertEquals($expected, $response); + } + + public function test_renderException_shouldReturnTheMessageAndNotTheExceptionMessage() + { + $response = $this->builder->renderException('This message should be ignored', new \BadMethodCallException('The other message')); + $expected = array('result' => 'error', 'message' => 'This message should be ignored'); + + $this->assertEquals($expected, $response); + } + + public function test_renderException_shouldSerializeByDefault() + { + $response = $this->makeBuilder(array())->renderException('This message should be ignored', new \BadMethodCallException('The other message')); + $expected = 'a:2:{s:6:"result";s:5:"error";s:7:"message";s:30:"This message should be ignored";}'; + + $this->assertEquals($expected, $response); + } + + public function test_renderScalar_shouldReturnTheSameValue() + { + $response = $this->builder->renderScalar(true); + $this->assertEquals(true, $response); + + $response = $this->builder->renderScalar(5); + $this->assertEquals(5, $response); + + $response = $this->builder->renderScalar('string'); + $this->assertEquals('string', $response); + } + + public function test_renderObject_shouldReturnTheSameValue() + { + $response = $this->builder->renderObject($this); + $expected = array('result' => 'error', 'message' => 'The API cannot handle this data structure.'); + + $this->assertEquals($expected, $response); + } + + public function test_renderResource_shouldReturnTheSameValue() + { + $resource = curl_init(); + $response = $this->builder->renderResource($resource); + $expected = array('result' => 'error', 'message' => 'The API cannot handle this data structure.'); + + $this->assertEquals($expected, $response); + } + + public function test_renderDataTable_shouldNotSerializeIfDisabled() + { + $dataTable = new DataTable(); + $dataTable->addRowFromSimpleArray(array('nb_visits' => 5, 'nb_random' => 10)); + + $response = $this->builder->renderDataTable($dataTable); + $expected = array( + array('nb_visits' => 5, 'nb_random' => 10) + ); + $this->assertEquals($expected, $response); + } + + public function test_renderDataTable_shouldSerializeByDefault() + { + $dataTable = new DataTable(); + $dataTable->addRowFromSimpleArray(array('nb_visits' => 5, 'nb_random' => 10)); + + $builder = $this->makeBuilder(array()); + $response = $builder->renderDataTable($dataTable); + + $expected = 'a:1:{i:0;a:2:{s:9:"nb_visits";i:5;s:9:"nb_random";i:10;}}'; + $this->assertSame($expected, $response); + } + + public function test_renderDataTable_shouldRenderSubtables() + { + $subtable = new DataTable(); + $subtable->addRowFromSimpleArray(array('nb_visits' => 2, 'nb_random' => 6)); + + $dataTable = new DataTable(); + $dataTable->addRowFromSimpleArray(array('nb_visits' => 5, 'nb_random' => 10)); + $dataTable->getFirstRow()->setSubtable($subtable); + + $response = $this->builder->renderDataTable($dataTable); + $expected = array(array('nb_visits' => 5, 'nb_random' => 10, 'idsubdatatable' => 1)); + + $this->assertEquals($expected, $response); + } + + public function test_renderDataTable_shouldRenderDataTableMaps() + { + $map = new DataTable\Map(); + + $dataTable = new DataTable(); + $dataTable->addRowFromSimpleArray(array('nb_visits' => 5, 'nb_random' => 10)); + + $dataTable2 = new DataTable(); + $dataTable2->addRowFromSimpleArray(array('nb_visits' => 3, 'nb_random' => 6)); + + $map->addTable($dataTable, 'table1'); + $map->addTable($dataTable2, 'table2'); + + $response = $this->builder->renderDataTable($map); + $expected = array( + 'table1' => array(array('nb_visits' => 5, 'nb_random' => 10)), + 'table2' => array(array('nb_visits' => 3, 'nb_random' => 6)) + ); + + $this->assertEquals($expected, $response); + } + + public function test_renderDataTable_shouldRenderSimpleDataTable() + { + $dataTable = new DataTable\Simple(); + $dataTable->addRowsFromArray(array('nb_visits' => 3, 'nb_random' => 6)); + + $response = $this->builder->renderDataTable($dataTable); + $expected = array('nb_visits' => 3, 'nb_random' => 6); + + $this->assertEquals($expected, $response); + } + + public function test_renderArray_ShouldReturnSameArrayNotSerialize() + { + $input = array(1, 2, 5, 'string', 10); + + // builder has serialize=0 + $response = $this->builder->renderArray($input); + + $this->assertSame($input, $response); + } + + public function test_renderArray_ShouldSerializeByDefault() + { + $builder = $this->makeBuilder(array()); + $input = array(1, 2, 5, 'string', 10); + + $response = $builder->renderArray($input); + + $this->assertSame('a:5:{i:0;i:1;i:1;i:2;i:2;i:5;i:3;s:6:"string";i:4;i:10;}', $response); + } + + public function test_renderArray_ShouldSerializeByDefaulMultiDimensionalArray() + { + $input = array( + "firstElement" => "isFirst", + "secondElement" => array( + "firstElement" => "isFirst", + "secondElement" => "isSecond", + ), + "thirdElement" => "isThird"); + + $builder = $this->makeBuilder(array()); + $actual = $builder->renderArray($input); + $this->assertSame( serialize($input), $actual); + } + + public function test_renderArray_ShouldConvertMultiDimensionalAssociativeArrayToJson() + { + $input = array( + "firstElement" => "isFirst", + "secondElement" => array( + "firstElement" => "isFirst", + "secondElement" => "isSecond", + ), + "thirdElement" => "isThird"); + + $actual = $this->builder->renderArray($input); + $this->assertSame($input, $actual); + } + + private function makeBuilder($request) + { + return new Php($request); + } +} diff --git a/plugins/API/tests/Unit/XmlRendererTest.php b/plugins/API/tests/Unit/XmlRendererTest.php new file mode 100644 index 0000000000..f3ca71a10d --- /dev/null +++ b/plugins/API/tests/Unit/XmlRendererTest.php @@ -0,0 +1,346 @@ +builder = $this->makeBuilder(array()); + DataTable\Manager::getInstance()->deleteAll(); + } + + public function test_renderSuccess_shouldIncludeMessage() + { + $response = $this->builder->renderSuccess('ok'); + + $this->assertEquals(' + + +', $response); + } + + public function test_renderException_shouldIncludeTheMessageAndNotExceptionMessage() + { + $response = $this->builder->renderException("The error message", new \Exception('The other message')); + + $this->assertEquals(' + + +', $response); + } + + public function test_renderObject_shouldReturAnError() + { + $response = $this->builder->renderObject(new \stdClass()); + + $this->assertEquals(' + + +', $response); + } + + public function test_renderResource_shouldReturAnError() + { + $response = $this->builder->renderResource(new \stdClass()); + + $this->assertEquals(' + + +', $response); + } + + public function test_renderScalar_shouldReturnABooleanAsIntegerWrappedInResult() + { + $response = $this->builder->renderScalar(true); + + $this->assertEquals(' +1', $response); + } + + public function test_renderScalar_shouldReturnAnIntegerWrappedInResult() + { + $response = $this->builder->renderScalar(5); + + $this->assertEquals(' +5', $response); + } + + public function test_renderScalar_shouldReturnAStringWrappedInValue() + { + $response = $this->builder->renderScalar('The Output'); + + $this->assertEquals(' +The Output', $response); + } + + public function test_renderScalar_shouldNotRemoveLineBreaks() + { + $response = $this->builder->renderScalar('The\nOutput'); + + $this->assertEquals(' +The\nOutput', $response); + } + + public function test_renderDataTable_shouldRenderABasicDataTable() + { + $dataTable = new DataTable(); + $dataTable->addRowFromSimpleArray(array('nb_visits' => 5, 'nb_random' => 10)); + + $response = $this->builder->renderDataTable($dataTable); + + $this->assertEquals(' + + + 5 + 10 + +', $response); + } + + public function test_renderDataTable_shouldRenderSubtables() + { + $subtable = new DataTable(); + $subtable->addRowFromSimpleArray(array('nb_visits' => 2, 'nb_random' => 6)); + + $dataTable = new DataTable(); + $dataTable->addRowFromSimpleArray(array('nb_visits' => 5, 'nb_random' => 10)); + $dataTable->getFirstRow()->setSubtable($subtable); + + $response = $this->builder->renderDataTable($dataTable); + + $this->assertEquals(' + + + 5 + 10 + 1 + +', $response); + } + + public function test_renderDataTable_shouldRenderDataTableMaps() + { + $map = new DataTable\Map(); + + $dataTable = new DataTable(); + $dataTable->addRowFromSimpleArray(array('nb_visits' => 5, 'nb_random' => 10)); + + $dataTable2 = new DataTable(); + $dataTable2->addRowFromSimpleArray(array('nb_visits' => 3, 'nb_random' => 6)); + + $map->addTable($dataTable, 'table1'); + $map->addTable($dataTable2, 'table2'); + + $response = $this->builder->renderDataTable($map); + + $this->assertEquals(' + + + + 5 + 10 + + + + + 3 + 6 + + +', $response); + } + + public function test_renderDataTable_shouldRenderSimpleDataTable() + { + $dataTable = new DataTable\Simple(); + $dataTable->addRowsFromArray(array('nb_visits' => 3, 'nb_random' => 6)); + + $response = $this->builder->renderDataTable($dataTable); + + $this->assertEquals(' + + 3 + 6 +', $response); + } + + public function test_renderArray_ShouldConvertSimpleArrayToJson() + { + $input = array(1, 2, 5, 'string', 10); + + $response = $this->builder->renderArray($input); + + $this->assertEquals(' + + 1 + 2 + 5 + string + 10 +', $response); + } + + public function test_renderArray_ShouldRenderAnEmptyArray() + { + $response = $this->builder->renderArray(array()); + + $this->assertEquals(' +', $response); + } + + public function test_renderArray_ShouldConvertAssociativeArrayToJson() + { + $input = array('nb_visits' => 6, 'nb_random' => 8); + + $response = $this->builder->renderArray($input); + + $this->assertEquals(' + + + 6 + 8 + +', $response); + } + + public function test_renderArray_ShouldConvertsIndexedAssociativeArrayToJson() + { + $input = array( + array('nb_visits' => 6, 'nb_random' => 8), + array('nb_visits' => 3, 'nb_random' => 4) + ); + + $response = $this->builder->renderArray($input); + + $this->assertEquals(' + + + 6 + 8 + + + 3 + 4 + +', $response); + } + + public function test_renderArray_ShouldConvertMultiDimensionalStandardArrayToJson() + { + $input = array("firstElement", + array( + "firstElement", + "secondElement", + ), + "thirdElement"); + + $actual = $this->builder->renderArray($input); + $this->assertEquals(' + + firstElement + + firstElement + secondElement + + thirdElement +', $actual); + } + + public function test_renderArray_ShouldConvertMultiDimensionalAssociativeArrayToJson() + { + $input = array( + "firstElement" => "isFirst", + "secondElement" => array( + "firstElement" => "isFirst", + "secondElement" => "isSecond", + ), + "thirdElement" => "isThird"); + + $actual = $this->builder->renderArray($input); + $this->assertEquals(' + + isFirst + + isFirst + isSecond + + isThird +', $actual); + } + + public function test_renderArray_ShouldConvertMultiDimensionalIndexArrayToJson() + { + $input = array(array("firstElement", + array( + "firstElement", + "secondElement", + ), + "thirdElement")); + + $actual = $this->builder->renderArray($input); + $this->assertEquals(' + + + firstElement + + firstElement + secondElement + + thirdElement + +', $actual); + } + + public function test_renderArray_ShouldConvertMultiDimensionalMixedArrayToJson() + { + $input = array( + "firstElement" => "isFirst", + array( + "firstElement", + "secondElement", + ), + "thirdElement" => array( + "firstElement" => "isFirst", + "secondElement" => "isSecond", + ) + ); + + $actual = $this->builder->renderArray($input); + $this->assertEquals(' + + isFirst + + firstElement + secondElement + + + isFirst + isSecond + +', $actual); + } + + private function makeBuilder($request) + { + return new Xml($request); + } +} diff --git a/plugins/API/tests/XmlRendererTest.php b/plugins/API/tests/XmlRendererTest.php deleted file mode 100644 index 1d222290bd..0000000000 --- a/plugins/API/tests/XmlRendererTest.php +++ /dev/null @@ -1,346 +0,0 @@ -builder = $this->makeBuilder(array()); - DataTable\Manager::getInstance()->deleteAll(); - } - - public function test_renderSuccess_shouldIncludeMessage() - { - $response = $this->builder->renderSuccess('ok'); - - $this->assertEquals(' - - -', $response); - } - - public function test_renderException_shouldIncludeTheMessageAndNotExceptionMessage() - { - $response = $this->builder->renderException("The error message", new \Exception('The other message')); - - $this->assertEquals(' - - -', $response); - } - - public function test_renderObject_shouldReturAnError() - { - $response = $this->builder->renderObject(new \stdClass()); - - $this->assertEquals(' - - -', $response); - } - - public function test_renderResource_shouldReturAnError() - { - $response = $this->builder->renderResource(new \stdClass()); - - $this->assertEquals(' - - -', $response); - } - - public function test_renderScalar_shouldReturnABooleanAsIntegerWrappedInResult() - { - $response = $this->builder->renderScalar(true); - - $this->assertEquals(' -1', $response); - } - - public function test_renderScalar_shouldReturnAnIntegerWrappedInResult() - { - $response = $this->builder->renderScalar(5); - - $this->assertEquals(' -5', $response); - } - - public function test_renderScalar_shouldReturnAStringWrappedInValue() - { - $response = $this->builder->renderScalar('The Output'); - - $this->assertEquals(' -The Output', $response); - } - - public function test_renderScalar_shouldNotRemoveLineBreaks() - { - $response = $this->builder->renderScalar('The\nOutput'); - - $this->assertEquals(' -The\nOutput', $response); - } - - public function test_renderDataTable_shouldRenderABasicDataTable() - { - $dataTable = new DataTable(); - $dataTable->addRowFromSimpleArray(array('nb_visits' => 5, 'nb_random' => 10)); - - $response = $this->builder->renderDataTable($dataTable); - - $this->assertEquals(' - - - 5 - 10 - -', $response); - } - - public function test_renderDataTable_shouldRenderSubtables() - { - $subtable = new DataTable(); - $subtable->addRowFromSimpleArray(array('nb_visits' => 2, 'nb_random' => 6)); - - $dataTable = new DataTable(); - $dataTable->addRowFromSimpleArray(array('nb_visits' => 5, 'nb_random' => 10)); - $dataTable->getFirstRow()->setSubtable($subtable); - - $response = $this->builder->renderDataTable($dataTable); - - $this->assertEquals(' - - - 5 - 10 - 1 - -', $response); - } - - public function test_renderDataTable_shouldRenderDataTableMaps() - { - $map = new DataTable\Map(); - - $dataTable = new DataTable(); - $dataTable->addRowFromSimpleArray(array('nb_visits' => 5, 'nb_random' => 10)); - - $dataTable2 = new DataTable(); - $dataTable2->addRowFromSimpleArray(array('nb_visits' => 3, 'nb_random' => 6)); - - $map->addTable($dataTable, 'table1'); - $map->addTable($dataTable2, 'table2'); - - $response = $this->builder->renderDataTable($map); - - $this->assertEquals(' - - - - 5 - 10 - - - - - 3 - 6 - - -', $response); - } - - public function test_renderDataTable_shouldRenderSimpleDataTable() - { - $dataTable = new DataTable\Simple(); - $dataTable->addRowsFromArray(array('nb_visits' => 3, 'nb_random' => 6)); - - $response = $this->builder->renderDataTable($dataTable); - - $this->assertEquals(' - - 3 - 6 -', $response); - } - - public function test_renderArray_ShouldConvertSimpleArrayToJson() - { - $input = array(1, 2, 5, 'string', 10); - - $response = $this->builder->renderArray($input); - - $this->assertEquals(' - - 1 - 2 - 5 - string - 10 -', $response); - } - - public function test_renderArray_ShouldRenderAnEmptyArray() - { - $response = $this->builder->renderArray(array()); - - $this->assertEquals(' -', $response); - } - - public function test_renderArray_ShouldConvertAssociativeArrayToJson() - { - $input = array('nb_visits' => 6, 'nb_random' => 8); - - $response = $this->builder->renderArray($input); - - $this->assertEquals(' - - - 6 - 8 - -', $response); - } - - public function test_renderArray_ShouldConvertsIndexedAssociativeArrayToJson() - { - $input = array( - array('nb_visits' => 6, 'nb_random' => 8), - array('nb_visits' => 3, 'nb_random' => 4) - ); - - $response = $this->builder->renderArray($input); - - $this->assertEquals(' - - - 6 - 8 - - - 3 - 4 - -', $response); - } - - public function test_renderArray_ShouldConvertMultiDimensionalStandardArrayToJson() - { - $input = array("firstElement", - array( - "firstElement", - "secondElement", - ), - "thirdElement"); - - $actual = $this->builder->renderArray($input); - $this->assertEquals(' - - firstElement - - firstElement - secondElement - - thirdElement -', $actual); - } - - public function test_renderArray_ShouldConvertMultiDimensionalAssociativeArrayToJson() - { - $input = array( - "firstElement" => "isFirst", - "secondElement" => array( - "firstElement" => "isFirst", - "secondElement" => "isSecond", - ), - "thirdElement" => "isThird"); - - $actual = $this->builder->renderArray($input); - $this->assertEquals(' - - isFirst - - isFirst - isSecond - - isThird -', $actual); - } - - public function test_renderArray_ShouldConvertMultiDimensionalIndexArrayToJson() - { - $input = array(array("firstElement", - array( - "firstElement", - "secondElement", - ), - "thirdElement")); - - $actual = $this->builder->renderArray($input); - $this->assertEquals(' - - - firstElement - - firstElement - secondElement - - thirdElement - -', $actual); - } - - public function test_renderArray_ShouldConvertMultiDimensionalMixedArrayToJson() - { - $input = array( - "firstElement" => "isFirst", - array( - "firstElement", - "secondElement", - ), - "thirdElement" => array( - "firstElement" => "isFirst", - "secondElement" => "isSecond", - ) - ); - - $actual = $this->builder->renderArray($input); - $this->assertEquals(' - - isFirst - - firstElement - secondElement - - - isFirst - isSecond - -', $actual); - } - - private function makeBuilder($request) - { - return new Xml($request); - } -} diff --git a/plugins/Actions/tests/ArchiverTest.php b/plugins/Actions/tests/ArchiverTest.php deleted file mode 100644 index 6458f425fa..0000000000 --- a/plugins/Actions/tests/ArchiverTest.php +++ /dev/null @@ -1,130 +0,0 @@ - array('name' => 'http://example.org/', 'type' => Action::TYPE_PAGE_URL, 'urlPrefix' => null), - 'expected' => array('/index'), - ), - array( - 'params' => array('name' => 'example.org/', 'type' => Action::TYPE_PAGE_URL, 'urlPrefix' => 1), - 'expected' => array('/index'), - ), - array( - 'params' => array('name' => 'example.org/', 'type' => Action::TYPE_PAGE_URL, 'urlPrefix' => 2), - 'expected' => array('/index'), - ), - array( - 'params' => array('name' => 'example.org/', 'type' => Action::TYPE_PAGE_URL, 'urlPrefix' => 3), - 'expected' => array('/index'), - ), - array( - 'params' => array('name' => 'example.org/', 'type' => Action::TYPE_PAGE_URL, 'urlPrefix' => 4), - 'expected' => array('/index'), - ), - array( - 'params' => array('name' => 'example.org/path/', 'type' => Action::TYPE_PAGE_URL, 'urlPrefix' => 4), - 'expected' => array('path', '/index'), - ), - array( - 'params' => array('name' => 'example.org/test/path', 'type' => Action::TYPE_PAGE_URL, 'urlPrefix' => 1), - 'expected' => array('test', '/path'), - ), - array( - 'params' => array('name' => 'http://example.org/path/', 'type' => Action::TYPE_PAGE_URL), - 'expected' => array('path', '/index'), - ), - array( - 'params' => array('name' => 'example.org/test/path', 'type' => Action::TYPE_PAGE_URL, 'urlPrefix' => 1), - 'expected' => array('test', '/path'), - ), - array( - 'params' => array('name' => 'Test / Path', 'type' => Action::TYPE_PAGE_URL), - 'expected' => array('Test', '/Path'), - ), - array( - 'params' => array('name' => ' Test trim ', 'type' => Action::TYPE_PAGE_URL), - 'expected' => array('/Test trim'), - ), - array( - 'params' => array('name' => 'Category / Subcategory', 'type' => Action::TYPE_PAGE_TITLE), - 'expected' => array('Category', ' Subcategory'), - ), - array( - 'params' => array('name' => '/path/index.php?var=test', 'type' => Action::TYPE_PAGE_TITLE), - 'expected' => array('path', ' index.php?var=test'), - ), - array( - 'params' => array('name' => 'http://example.org/path/Default.aspx#anchor', 'type' => Action::TYPE_PAGE_TITLE), - 'expected' => array('path', ' Default.aspx#anchor'), - ), - array( - 'params' => array('name' => '', 'type' => Action::TYPE_PAGE_TITLE), - 'expected' => array('Page Name not defined'), - ), - array( - 'params' => array('name' => '', 'type' => Action::TYPE_PAGE_URL), - 'expected' => array('Page URL not defined'), - ), - array( - 'params' => array('name' => 'http://example.org/download.zip', 'type' => Action::TYPE_DOWNLOAD), - 'expected' => array('example.org', '/download.zip'), - ), - array( - 'params' => array('name' => 'http://example.org/download/1/', 'type' => Action::TYPE_DOWNLOAD), - 'expected' => array('example.org', '/download/1/'), - ), - array( - 'params' => array('name' => 'http://example.org/link', 'type' => Action::TYPE_OUTLINK), - 'expected' => array('example.org', '/link'), - ), - array( - 'params' => array('name' => 'http://example.org/some/path/', 'type' => Action::TYPE_OUTLINK), - 'expected' => array('example.org', '/some/path/'), - ), - ); - } - - /** - * @dataProvider getActionNameTestData - */ - public function testGetActionExplodedNames($params, $expected) - { - ArchivingHelper::reloadConfig(); - $processed = ArchivingHelper::getActionExplodedNames($params['name'], $params['type'], (isset($params['urlPrefix']) ? $params['urlPrefix'] : null)); - $this->assertEquals($expected, $processed); - } -} - diff --git a/plugins/Actions/tests/Unit/ArchiverTest.php b/plugins/Actions/tests/Unit/ArchiverTest.php new file mode 100644 index 0000000000..a3ba57511a --- /dev/null +++ b/plugins/Actions/tests/Unit/ArchiverTest.php @@ -0,0 +1,130 @@ + array('name' => 'http://example.org/', 'type' => Action::TYPE_PAGE_URL, 'urlPrefix' => null), + 'expected' => array('/index'), + ), + array( + 'params' => array('name' => 'example.org/', 'type' => Action::TYPE_PAGE_URL, 'urlPrefix' => 1), + 'expected' => array('/index'), + ), + array( + 'params' => array('name' => 'example.org/', 'type' => Action::TYPE_PAGE_URL, 'urlPrefix' => 2), + 'expected' => array('/index'), + ), + array( + 'params' => array('name' => 'example.org/', 'type' => Action::TYPE_PAGE_URL, 'urlPrefix' => 3), + 'expected' => array('/index'), + ), + array( + 'params' => array('name' => 'example.org/', 'type' => Action::TYPE_PAGE_URL, 'urlPrefix' => 4), + 'expected' => array('/index'), + ), + array( + 'params' => array('name' => 'example.org/path/', 'type' => Action::TYPE_PAGE_URL, 'urlPrefix' => 4), + 'expected' => array('path', '/index'), + ), + array( + 'params' => array('name' => 'example.org/test/path', 'type' => Action::TYPE_PAGE_URL, 'urlPrefix' => 1), + 'expected' => array('test', '/path'), + ), + array( + 'params' => array('name' => 'http://example.org/path/', 'type' => Action::TYPE_PAGE_URL), + 'expected' => array('path', '/index'), + ), + array( + 'params' => array('name' => 'example.org/test/path', 'type' => Action::TYPE_PAGE_URL, 'urlPrefix' => 1), + 'expected' => array('test', '/path'), + ), + array( + 'params' => array('name' => 'Test / Path', 'type' => Action::TYPE_PAGE_URL), + 'expected' => array('Test', '/Path'), + ), + array( + 'params' => array('name' => ' Test trim ', 'type' => Action::TYPE_PAGE_URL), + 'expected' => array('/Test trim'), + ), + array( + 'params' => array('name' => 'Category / Subcategory', 'type' => Action::TYPE_PAGE_TITLE), + 'expected' => array('Category', ' Subcategory'), + ), + array( + 'params' => array('name' => '/path/index.php?var=test', 'type' => Action::TYPE_PAGE_TITLE), + 'expected' => array('path', ' index.php?var=test'), + ), + array( + 'params' => array('name' => 'http://example.org/path/Default.aspx#anchor', 'type' => Action::TYPE_PAGE_TITLE), + 'expected' => array('path', ' Default.aspx#anchor'), + ), + array( + 'params' => array('name' => '', 'type' => Action::TYPE_PAGE_TITLE), + 'expected' => array('Page Name not defined'), + ), + array( + 'params' => array('name' => '', 'type' => Action::TYPE_PAGE_URL), + 'expected' => array('Page URL not defined'), + ), + array( + 'params' => array('name' => 'http://example.org/download.zip', 'type' => Action::TYPE_DOWNLOAD), + 'expected' => array('example.org', '/download.zip'), + ), + array( + 'params' => array('name' => 'http://example.org/download/1/', 'type' => Action::TYPE_DOWNLOAD), + 'expected' => array('example.org', '/download/1/'), + ), + array( + 'params' => array('name' => 'http://example.org/link', 'type' => Action::TYPE_OUTLINK), + 'expected' => array('example.org', '/link'), + ), + array( + 'params' => array('name' => 'http://example.org/some/path/', 'type' => Action::TYPE_OUTLINK), + 'expected' => array('example.org', '/some/path/'), + ), + ); + } + + /** + * @dataProvider getActionNameTestData + */ + public function testGetActionExplodedNames($params, $expected) + { + ArchivingHelper::reloadConfig(); + $processed = ArchivingHelper::getActionExplodedNames($params['name'], $params['type'], (isset($params['urlPrefix']) ? $params['urlPrefix'] : null)); + $this->assertEquals($expected, $processed); + } +} + diff --git a/plugins/Contents/.gitignore b/plugins/Contents/.gitignore index b141f4501f..c8c9480010 100644 --- a/plugins/Contents/.gitignore +++ b/plugins/Contents/.gitignore @@ -1 +1 @@ -tests/processed/*xml \ No newline at end of file +tests/System/processed/*xml \ No newline at end of file diff --git a/plugins/Contents/tests/ContentsTest.php b/plugins/Contents/tests/ContentsTest.php deleted file mode 100644 index c07f491546..0000000000 --- a/plugins/Contents/tests/ContentsTest.php +++ /dev/null @@ -1,135 +0,0 @@ -runApiTests($api, $params); - } - - protected function getApiToCall() - { - return array( - 'Contents.getContentNames', - 'Contents.getContentPieces', - 'Actions.get', - 'Actions.getPageUrls', - 'Live.getLastVisitsDetails' - ); - } - - protected function setup() - { - parent::setup(); - Translate::reloadLanguage('en'); - } - - protected function tearDown() - { - parent::tearDown(); - } - - public function getApiForTesting() - { - $dateTime = self::$fixture->dateTime; - $idSite1 = self::$fixture->idSite; - - $apiToCallProcessedReportMetadata = $this->getApiToCall(); - - $dayPeriod = 'day'; - $periods = array($dayPeriod, 'month'); - - $apisToTest = array('Contents', 'Actions.getPageUrls', 'Live.getLastVisitsDetails'); - $result = array( - array($apiToCallProcessedReportMetadata, array( - 'idSite' => $idSite1, - 'date' => $dateTime, - 'periods' => $periods, - 'setDateLastN' => false, - 'testSuffix' => '')), - - array($apisToTest, array( - 'idSite' => $idSite1, - 'date' => $dateTime, - 'periods' => $dayPeriod, - 'segment' => "contentName==ImageAd,contentPiece==".urlencode('Click to download Piwik now'), - 'setDateLastN' => false, - 'testSuffix' => 'contentNameOrPieceMatch') - ), - - array($apisToTest, array( - 'idSite' => $idSite1, - 'date' => $dateTime, - 'periods' => $dayPeriod, - 'segment' => "contentTarget==".urlencode('http://www.example.com'), - 'setDateLastN' => false, - 'testSuffix' => '_contentTargetMatch') - ), - - array($apisToTest, array( - 'idSite' => $idSite1, - 'date' => $dateTime, - 'periods' => $dayPeriod, - 'segment' => "contentInteraction==click", - 'setDateLastN' => false, - 'testSuffix' => '_contentInteractionMatch') - ) - ); - - $apiToCallProcessedReportMetadata = array( - 'Contents.getContentNames', - 'Contents.getContentPieces' - ); - // testing metadata API for Contents reports - foreach ($apiToCallProcessedReportMetadata as $api) { - list($apiModule, $apiAction) = explode(".", $api); - - $result[] = array( - 'API.getProcessedReport', array('idSite' => $idSite1, - 'date' => $dateTime, - 'periods' => $dayPeriod, - 'setDateLastN' => true, - 'apiModule' => $apiModule, - 'apiAction' => $apiAction, - 'testSuffix' => '_' . $api . '_lastN') - ); - } - - return $result; - } - - public static function getOutputPrefix() - { - return 'Contents'; - } - - public static function getPathToTestDirectory() - { - return dirname(__FILE__); - } -} - -ContentsTest::$fixture = new TwoVisitsWithContents(); \ No newline at end of file diff --git a/plugins/Contents/tests/System/ContentsTest.php b/plugins/Contents/tests/System/ContentsTest.php new file mode 100644 index 0000000000..d348133c2b --- /dev/null +++ b/plugins/Contents/tests/System/ContentsTest.php @@ -0,0 +1,135 @@ +runApiTests($api, $params); + } + + protected function getApiToCall() + { + return array( + 'Contents.getContentNames', + 'Contents.getContentPieces', + 'Actions.get', + 'Actions.getPageUrls', + 'Live.getLastVisitsDetails' + ); + } + + protected function setup() + { + parent::setup(); + Translate::reloadLanguage('en'); + } + + protected function tearDown() + { + parent::tearDown(); + } + + public function getApiForTesting() + { + $dateTime = self::$fixture->dateTime; + $idSite1 = self::$fixture->idSite; + + $apiToCallProcessedReportMetadata = $this->getApiToCall(); + + $dayPeriod = 'day'; + $periods = array($dayPeriod, 'month'); + + $apisToTest = array('Contents', 'Actions.getPageUrls', 'Live.getLastVisitsDetails'); + $result = array( + array($apiToCallProcessedReportMetadata, array( + 'idSite' => $idSite1, + 'date' => $dateTime, + 'periods' => $periods, + 'setDateLastN' => false, + 'testSuffix' => '')), + + array($apisToTest, array( + 'idSite' => $idSite1, + 'date' => $dateTime, + 'periods' => $dayPeriod, + 'segment' => "contentName==ImageAd,contentPiece==".urlencode('Click to download Piwik now'), + 'setDateLastN' => false, + 'testSuffix' => 'contentNameOrPieceMatch') + ), + + array($apisToTest, array( + 'idSite' => $idSite1, + 'date' => $dateTime, + 'periods' => $dayPeriod, + 'segment' => "contentTarget==".urlencode('http://www.example.com'), + 'setDateLastN' => false, + 'testSuffix' => '_contentTargetMatch') + ), + + array($apisToTest, array( + 'idSite' => $idSite1, + 'date' => $dateTime, + 'periods' => $dayPeriod, + 'segment' => "contentInteraction==click", + 'setDateLastN' => false, + 'testSuffix' => '_contentInteractionMatch') + ) + ); + + $apiToCallProcessedReportMetadata = array( + 'Contents.getContentNames', + 'Contents.getContentPieces' + ); + // testing metadata API for Contents reports + foreach ($apiToCallProcessedReportMetadata as $api) { + list($apiModule, $apiAction) = explode(".", $api); + + $result[] = array( + 'API.getProcessedReport', array('idSite' => $idSite1, + 'date' => $dateTime, + 'periods' => $dayPeriod, + 'setDateLastN' => true, + 'apiModule' => $apiModule, + 'apiAction' => $apiAction, + 'testSuffix' => '_' . $api . '_lastN') + ); + } + + return $result; + } + + public static function getOutputPrefix() + { + return 'Contents'; + } + + public static function getPathToTestDirectory() + { + return dirname(__FILE__); + } +} + +ContentsTest::$fixture = new TwoVisitsWithContents(); \ No newline at end of file diff --git a/plugins/Contents/tests/System/expected/test_Contents_Contents.getContentNames_lastN__API.getProcessedReport_day.xml b/plugins/Contents/tests/System/expected/test_Contents_Contents.getContentNames_lastN__API.getProcessedReport_day.xml new file mode 100644 index 0000000000..d3e1af1e2e --- /dev/null +++ b/plugins/Contents/tests/System/expected/test_Contents_Contents.getContentNames_lastN__API.getProcessedReport_day.xml @@ -0,0 +1,83 @@ + + + Piwik test + 3 Jan 10 - 9 Jan 10 + + Actions + Content Name + Contents + getContentNames + Content Name + + Impressions + Interactions + + + Interaction Rate + + getContentNames + index.php?module=API&method=ImageGraph.get&idSite=1&apiModule=Contents&apiAction=getContentNames&period=range&date=2010-01-03,2010-01-09 + index.php?module=API&method=ImageGraph.get&idSite=1&apiModule=Contents&apiAction=getContentNames&period=day&date=2010-01-03,2010-01-09 + Contents_getContentNames + + + + Impressions + Interactions + Interaction Rate + + + + + + 8 + 2 + 25% + + + + 6 + 4 + 66.67% + + + + 2 + 0 + 0% + + + + + + + + + + + + + http://www.example.com + + + + http://piwik.org/ + + + + + + + + + + + + + + + + 16 + 16 + + \ No newline at end of file diff --git a/plugins/Contents/tests/System/expected/test_Contents_Contents.getContentPieces_lastN__API.getProcessedReport_day.xml b/plugins/Contents/tests/System/expected/test_Contents_Contents.getContentPieces_lastN__API.getProcessedReport_day.xml new file mode 100644 index 0000000000..402909f7d5 --- /dev/null +++ b/plugins/Contents/tests/System/expected/test_Contents_Contents.getContentPieces_lastN__API.getProcessedReport_day.xml @@ -0,0 +1,123 @@ + + + Piwik test + 3 Jan 10 - 9 Jan 10 + + Actions + Content Piece + Contents + getContentPieces + Content Piece + + Impressions + Interactions + + + Interaction Rate + + getContentPieces + index.php?module=API&method=ImageGraph.get&idSite=1&apiModule=Contents&apiAction=getContentPieces&period=range&date=2010-01-03,2010-01-09 + index.php?module=API&method=ImageGraph.get&idSite=1&apiModule=Contents&apiAction=getContentPieces&period=day&date=2010-01-03,2010-01-09 + Contents_getContentPieces + + + + Impressions + Interactions + Interaction Rate + + + + + + 4 + 2 + 50% + + + + 2 + 2 + 100% + + + + 2 + 0 + 0% + + + + 2 + 2 + 100% + + + + 2 + 0 + 0% + + + + 2 + 0 + 0% + + + + 2 + 0 + 0% + + + + + + + + + + + + + http://piwik.org/download + + + + http://www.example.com + + + + http://www.example.com + + + + http://piwik.org/ + + + + + + + + + + + + + + + + + + + + + + + + 16 + 16 + + \ No newline at end of file diff --git a/plugins/Contents/tests/System/expected/test_Contents__Actions.getPageUrls_day.xml b/plugins/Contents/tests/System/expected/test_Contents__Actions.getPageUrls_day.xml new file mode 100644 index 0000000000..fde347f2b5 --- /dev/null +++ b/plugins/Contents/tests/System/expected/test_Contents__Actions.getPageUrls_day.xml @@ -0,0 +1,25 @@ + + + + + 2 + 2 + 2 + 540 + 2 + 0.333 + 0.333 + 2 + 2 + 2 + 542 + 2 + 2 + 2 + 270 + 100% + 100% + 0.333 + http://www.example.org/page + + \ No newline at end of file diff --git a/plugins/Contents/tests/System/expected/test_Contents__Actions.getPageUrls_month.xml b/plugins/Contents/tests/System/expected/test_Contents__Actions.getPageUrls_month.xml new file mode 100644 index 0000000000..3dc775d40a --- /dev/null +++ b/plugins/Contents/tests/System/expected/test_Contents__Actions.getPageUrls_month.xml @@ -0,0 +1,25 @@ + + + + + 2 + 2 + 540 + 2 + 0.333 + 0.333 + 2 + 2 + 542 + 2 + 2 + 2 + 2 + 2 + 270 + 100% + 100% + 0.333 + http://www.example.org/page + + \ No newline at end of file diff --git a/plugins/Contents/tests/System/expected/test_Contents__Actions.get_day.xml b/plugins/Contents/tests/System/expected/test_Contents__Actions.get_day.xml new file mode 100644 index 0000000000..f51cfaf913 --- /dev/null +++ b/plugins/Contents/tests/System/expected/test_Contents__Actions.get_day.xml @@ -0,0 +1,12 @@ + + + 2 + 2 + 0 + 0 + 0 + 0 + 0 + 0 + 0.335 + \ No newline at end of file diff --git a/plugins/Contents/tests/System/expected/test_Contents__Actions.get_month.xml b/plugins/Contents/tests/System/expected/test_Contents__Actions.get_month.xml new file mode 100644 index 0000000000..f51cfaf913 --- /dev/null +++ b/plugins/Contents/tests/System/expected/test_Contents__Actions.get_month.xml @@ -0,0 +1,12 @@ + + + 2 + 2 + 0 + 0 + 0 + 0 + 0 + 0 + 0.335 + \ No newline at end of file diff --git a/plugins/Contents/tests/System/expected/test_Contents__Contents.getContentNames_day.xml b/plugins/Contents/tests/System/expected/test_Contents__Contents.getContentNames_day.xml new file mode 100644 index 0000000000..957c6fa85a --- /dev/null +++ b/plugins/Contents/tests/System/expected/test_Contents__Contents.getContentNames_day.xml @@ -0,0 +1,30 @@ + + + + + 8 + 8 + 8 + 2 + 25% + http://www.example.com + + + + 6 + 6 + 6 + 4 + 66.67% + http://piwik.org/ + + + + 2 + 2 + 2 + 0 + 0% + + + \ No newline at end of file diff --git a/plugins/Contents/tests/System/expected/test_Contents__Contents.getContentNames_month.xml b/plugins/Contents/tests/System/expected/test_Contents__Contents.getContentNames_month.xml new file mode 100644 index 0000000000..44bfdfd54e --- /dev/null +++ b/plugins/Contents/tests/System/expected/test_Contents__Contents.getContentNames_month.xml @@ -0,0 +1,30 @@ + + + + + 8 + 8 + 2 + 8 + 25% + http://www.example.com + + + + 6 + 6 + 4 + 6 + 66.67% + http://piwik.org/ + + + + 2 + 2 + 0 + 2 + 0% + + + \ No newline at end of file diff --git a/plugins/Contents/tests/System/expected/test_Contents__Contents.getContentPieces_day.xml b/plugins/Contents/tests/System/expected/test_Contents__Contents.getContentPieces_day.xml new file mode 100644 index 0000000000..8927f8a8ec --- /dev/null +++ b/plugins/Contents/tests/System/expected/test_Contents__Contents.getContentPieces_day.xml @@ -0,0 +1,66 @@ + + + + + 4 + 4 + 4 + 2 + 50% + http://piwik.org/download + + + + 2 + 2 + 2 + 2 + 100% + http://www.example.com + + + + 2 + 2 + 2 + 0 + 0% + http://www.example.com + + + + 2 + 2 + 2 + 2 + 100% + http://piwik.org/ + + + + 2 + 2 + 2 + 0 + 0% + + + + + 2 + 2 + 2 + 0 + 0% + + + + + 2 + 2 + 2 + 0 + 0% + + + \ No newline at end of file diff --git a/plugins/Contents/tests/System/expected/test_Contents__Contents.getContentPieces_month.xml b/plugins/Contents/tests/System/expected/test_Contents__Contents.getContentPieces_month.xml new file mode 100644 index 0000000000..b604544417 --- /dev/null +++ b/plugins/Contents/tests/System/expected/test_Contents__Contents.getContentPieces_month.xml @@ -0,0 +1,66 @@ + + + + + 4 + 4 + 2 + 4 + 50% + http://piwik.org/download + + + + 2 + 2 + 2 + 2 + 100% + http://www.example.com + + + + 2 + 2 + 0 + 2 + 0% + http://www.example.com + + + + 2 + 2 + 2 + 2 + 100% + http://piwik.org/ + + + + 2 + 2 + 0 + 2 + 0% + + + + + 2 + 2 + 0 + 2 + 0% + + + + + 2 + 2 + 0 + 2 + 0% + + + \ No newline at end of file diff --git a/plugins/Contents/tests/System/expected/test_Contents__Live.getLastVisitsDetails_day.xml b/plugins/Contents/tests/System/expected/test_Contents__Live.getLastVisitsDetails_day.xml new file mode 100644 index 0000000000..989f816722 --- /dev/null +++ b/plugins/Contents/tests/System/expected/test_Contents__Live.getLastVisitsDetails_day.xml @@ -0,0 +1,199 @@ + + + + 1 + 1 + 156.5.3.2 + + + + action + http://www.example.org/page + Ads + 2 + + 1 + 0.33s + 0 + 0s + + + + 0 + USD + $ + + + + + 0 + 1 + + new + + 0 + + 1 + + none + + 0 + 0 + 271 + 4 min 31s + + + Desktop + 0 + Unknown + Unknown + http://piwik.org/faq/general/#faq_52 + direct + Direct Entry + + + + + + + Europe + eur + France + fr + plugins/UserCountry/images/flags/fr.png + + + + France + + + Windows XP + WXP + Win XP + plugins/UserSettings/images/os/WXP.gif + gecko + Gecko (Firefox) + Firefox 3.6 + plugins/UserSettings/images/browsers/FF.gif + FF + 3.6 + normal + 1024x768 + plugins/UserSettings/images/screens/normal.gif + flash, java + + + plugins/UserSettings/images/plugins/flash.gif + flash + + + plugins/UserSettings/images/plugins/java.gif + java + + + 12:34:06 + 12 + 0 + + + + + + + + 1 + 2 + 111.1.1.1 + + + + action + http://www.example.org/page + Ads + 2 + + 13 + 0.33s + 0 + 0s + + + + 0 + USD + $ + + + + + 0 + 1 + + new + + 0 + + 1 + + none + + 0 + 0 + 271 + 4 min 31s + + + Desktop + 0 + Unknown + Unknown + http://piwik.org/faq/general/#faq_52 + direct + Direct Entry + + + + + + + Europe + eur + France + fr + plugins/UserCountry/images/flags/fr.png + + + + France + + + Windows XP + WXP + Win XP + plugins/UserSettings/images/os/WXP.gif + gecko + Gecko (Firefox) + Firefox 3.6 + plugins/UserSettings/images/browsers/FF.gif + FF + 3.6 + normal + 1024x768 + plugins/UserSettings/images/screens/normal.gif + director + + + plugins/UserSettings/images/plugins/director.gif + director + + + 12:34:06 + 12 + 0 + + + + + + + \ No newline at end of file diff --git a/plugins/Contents/tests/System/expected/test_Contents__Live.getLastVisitsDetails_month.xml b/plugins/Contents/tests/System/expected/test_Contents__Live.getLastVisitsDetails_month.xml new file mode 100644 index 0000000000..989f816722 --- /dev/null +++ b/plugins/Contents/tests/System/expected/test_Contents__Live.getLastVisitsDetails_month.xml @@ -0,0 +1,199 @@ + + + + 1 + 1 + 156.5.3.2 + + + + action + http://www.example.org/page + Ads + 2 + + 1 + 0.33s + 0 + 0s + + + + 0 + USD + $ + + + + + 0 + 1 + + new + + 0 + + 1 + + none + + 0 + 0 + 271 + 4 min 31s + + + Desktop + 0 + Unknown + Unknown + http://piwik.org/faq/general/#faq_52 + direct + Direct Entry + + + + + + + Europe + eur + France + fr + plugins/UserCountry/images/flags/fr.png + + + + France + + + Windows XP + WXP + Win XP + plugins/UserSettings/images/os/WXP.gif + gecko + Gecko (Firefox) + Firefox 3.6 + plugins/UserSettings/images/browsers/FF.gif + FF + 3.6 + normal + 1024x768 + plugins/UserSettings/images/screens/normal.gif + flash, java + + + plugins/UserSettings/images/plugins/flash.gif + flash + + + plugins/UserSettings/images/plugins/java.gif + java + + + 12:34:06 + 12 + 0 + + + + + + + + 1 + 2 + 111.1.1.1 + + + + action + http://www.example.org/page + Ads + 2 + + 13 + 0.33s + 0 + 0s + + + + 0 + USD + $ + + + + + 0 + 1 + + new + + 0 + + 1 + + none + + 0 + 0 + 271 + 4 min 31s + + + Desktop + 0 + Unknown + Unknown + http://piwik.org/faq/general/#faq_52 + direct + Direct Entry + + + + + + + Europe + eur + France + fr + plugins/UserCountry/images/flags/fr.png + + + + France + + + Windows XP + WXP + Win XP + plugins/UserSettings/images/os/WXP.gif + gecko + Gecko (Firefox) + Firefox 3.6 + plugins/UserSettings/images/browsers/FF.gif + FF + 3.6 + normal + 1024x768 + plugins/UserSettings/images/screens/normal.gif + director + + + plugins/UserSettings/images/plugins/director.gif + director + + + 12:34:06 + 12 + 0 + + + + + + + \ No newline at end of file diff --git a/plugins/Contents/tests/System/expected/test_Contents_contentInteractionMatch__Actions.getPageUrls_day.xml b/plugins/Contents/tests/System/expected/test_Contents_contentInteractionMatch__Actions.getPageUrls_day.xml new file mode 100644 index 0000000000..c234bed59e --- /dev/null +++ b/plugins/Contents/tests/System/expected/test_Contents_contentInteractionMatch__Actions.getPageUrls_day.xml @@ -0,0 +1,2 @@ + + \ No newline at end of file diff --git a/plugins/Contents/tests/System/expected/test_Contents_contentInteractionMatch__Contents.getContentNames_day.xml b/plugins/Contents/tests/System/expected/test_Contents_contentInteractionMatch__Contents.getContentNames_day.xml new file mode 100644 index 0000000000..c234bed59e --- /dev/null +++ b/plugins/Contents/tests/System/expected/test_Contents_contentInteractionMatch__Contents.getContentNames_day.xml @@ -0,0 +1,2 @@ + + \ No newline at end of file diff --git a/plugins/Contents/tests/System/expected/test_Contents_contentInteractionMatch__Contents.getContentPieces_day.xml b/plugins/Contents/tests/System/expected/test_Contents_contentInteractionMatch__Contents.getContentPieces_day.xml new file mode 100644 index 0000000000..c234bed59e --- /dev/null +++ b/plugins/Contents/tests/System/expected/test_Contents_contentInteractionMatch__Contents.getContentPieces_day.xml @@ -0,0 +1,2 @@ + + \ No newline at end of file diff --git a/plugins/Contents/tests/System/expected/test_Contents_contentInteractionMatch__Live.getLastVisitsDetails_day.xml b/plugins/Contents/tests/System/expected/test_Contents_contentInteractionMatch__Live.getLastVisitsDetails_day.xml new file mode 100644 index 0000000000..989f816722 --- /dev/null +++ b/plugins/Contents/tests/System/expected/test_Contents_contentInteractionMatch__Live.getLastVisitsDetails_day.xml @@ -0,0 +1,199 @@ + + + + 1 + 1 + 156.5.3.2 + + + + action + http://www.example.org/page + Ads + 2 + + 1 + 0.33s + 0 + 0s + + + + 0 + USD + $ + + + + + 0 + 1 + + new + + 0 + + 1 + + none + + 0 + 0 + 271 + 4 min 31s + + + Desktop + 0 + Unknown + Unknown + http://piwik.org/faq/general/#faq_52 + direct + Direct Entry + + + + + + + Europe + eur + France + fr + plugins/UserCountry/images/flags/fr.png + + + + France + + + Windows XP + WXP + Win XP + plugins/UserSettings/images/os/WXP.gif + gecko + Gecko (Firefox) + Firefox 3.6 + plugins/UserSettings/images/browsers/FF.gif + FF + 3.6 + normal + 1024x768 + plugins/UserSettings/images/screens/normal.gif + flash, java + + + plugins/UserSettings/images/plugins/flash.gif + flash + + + plugins/UserSettings/images/plugins/java.gif + java + + + 12:34:06 + 12 + 0 + + + + + + + + 1 + 2 + 111.1.1.1 + + + + action + http://www.example.org/page + Ads + 2 + + 13 + 0.33s + 0 + 0s + + + + 0 + USD + $ + + + + + 0 + 1 + + new + + 0 + + 1 + + none + + 0 + 0 + 271 + 4 min 31s + + + Desktop + 0 + Unknown + Unknown + http://piwik.org/faq/general/#faq_52 + direct + Direct Entry + + + + + + + Europe + eur + France + fr + plugins/UserCountry/images/flags/fr.png + + + + France + + + Windows XP + WXP + Win XP + plugins/UserSettings/images/os/WXP.gif + gecko + Gecko (Firefox) + Firefox 3.6 + plugins/UserSettings/images/browsers/FF.gif + FF + 3.6 + normal + 1024x768 + plugins/UserSettings/images/screens/normal.gif + director + + + plugins/UserSettings/images/plugins/director.gif + director + + + 12:34:06 + 12 + 0 + + + + + + + \ No newline at end of file diff --git a/plugins/Contents/tests/System/expected/test_Contents_contentTargetMatch__Actions.getPageUrls_day.xml b/plugins/Contents/tests/System/expected/test_Contents_contentTargetMatch__Actions.getPageUrls_day.xml new file mode 100644 index 0000000000..c234bed59e --- /dev/null +++ b/plugins/Contents/tests/System/expected/test_Contents_contentTargetMatch__Actions.getPageUrls_day.xml @@ -0,0 +1,2 @@ + + \ No newline at end of file diff --git a/plugins/Contents/tests/System/expected/test_Contents_contentTargetMatch__Contents.getContentNames_day.xml b/plugins/Contents/tests/System/expected/test_Contents_contentTargetMatch__Contents.getContentNames_day.xml new file mode 100644 index 0000000000..5212486a1c --- /dev/null +++ b/plugins/Contents/tests/System/expected/test_Contents_contentTargetMatch__Contents.getContentNames_day.xml @@ -0,0 +1,12 @@ + + + + + 4 + 4 + 4 + 2 + 50% + http://www.example.com + + \ No newline at end of file diff --git a/plugins/Contents/tests/System/expected/test_Contents_contentTargetMatch__Contents.getContentPieces_day.xml b/plugins/Contents/tests/System/expected/test_Contents_contentTargetMatch__Contents.getContentPieces_day.xml new file mode 100644 index 0000000000..ac1d39a577 --- /dev/null +++ b/plugins/Contents/tests/System/expected/test_Contents_contentTargetMatch__Contents.getContentPieces_day.xml @@ -0,0 +1,21 @@ + + + + + 2 + 2 + 2 + 2 + 100% + http://www.example.com + + + + 2 + 2 + 2 + 0 + 0% + http://www.example.com + + \ No newline at end of file diff --git a/plugins/Contents/tests/System/expected/test_Contents_contentTargetMatch__Live.getLastVisitsDetails_day.xml b/plugins/Contents/tests/System/expected/test_Contents_contentTargetMatch__Live.getLastVisitsDetails_day.xml new file mode 100644 index 0000000000..989f816722 --- /dev/null +++ b/plugins/Contents/tests/System/expected/test_Contents_contentTargetMatch__Live.getLastVisitsDetails_day.xml @@ -0,0 +1,199 @@ + + + + 1 + 1 + 156.5.3.2 + + + + action + http://www.example.org/page + Ads + 2 + + 1 + 0.33s + 0 + 0s + + + + 0 + USD + $ + + + + + 0 + 1 + + new + + 0 + + 1 + + none + + 0 + 0 + 271 + 4 min 31s + + + Desktop + 0 + Unknown + Unknown + http://piwik.org/faq/general/#faq_52 + direct + Direct Entry + + + + + + + Europe + eur + France + fr + plugins/UserCountry/images/flags/fr.png + + + + France + + + Windows XP + WXP + Win XP + plugins/UserSettings/images/os/WXP.gif + gecko + Gecko (Firefox) + Firefox 3.6 + plugins/UserSettings/images/browsers/FF.gif + FF + 3.6 + normal + 1024x768 + plugins/UserSettings/images/screens/normal.gif + flash, java + + + plugins/UserSettings/images/plugins/flash.gif + flash + + + plugins/UserSettings/images/plugins/java.gif + java + + + 12:34:06 + 12 + 0 + + + + + + + + 1 + 2 + 111.1.1.1 + + + + action + http://www.example.org/page + Ads + 2 + + 13 + 0.33s + 0 + 0s + + + + 0 + USD + $ + + + + + 0 + 1 + + new + + 0 + + 1 + + none + + 0 + 0 + 271 + 4 min 31s + + + Desktop + 0 + Unknown + Unknown + http://piwik.org/faq/general/#faq_52 + direct + Direct Entry + + + + + + + Europe + eur + France + fr + plugins/UserCountry/images/flags/fr.png + + + + France + + + Windows XP + WXP + Win XP + plugins/UserSettings/images/os/WXP.gif + gecko + Gecko (Firefox) + Firefox 3.6 + plugins/UserSettings/images/browsers/FF.gif + FF + 3.6 + normal + 1024x768 + plugins/UserSettings/images/screens/normal.gif + director + + + plugins/UserSettings/images/plugins/director.gif + director + + + 12:34:06 + 12 + 0 + + + + + + + \ No newline at end of file diff --git a/plugins/Contents/tests/System/expected/test_ContentscontentNameOrPieceMatch__Actions.getPageUrls_day.xml b/plugins/Contents/tests/System/expected/test_ContentscontentNameOrPieceMatch__Actions.getPageUrls_day.xml new file mode 100644 index 0000000000..c234bed59e --- /dev/null +++ b/plugins/Contents/tests/System/expected/test_ContentscontentNameOrPieceMatch__Actions.getPageUrls_day.xml @@ -0,0 +1,2 @@ + + \ No newline at end of file diff --git a/plugins/Contents/tests/System/expected/test_ContentscontentNameOrPieceMatch__Contents.getContentNames_day.xml b/plugins/Contents/tests/System/expected/test_ContentscontentNameOrPieceMatch__Contents.getContentNames_day.xml new file mode 100644 index 0000000000..17b781db1c --- /dev/null +++ b/plugins/Contents/tests/System/expected/test_ContentscontentNameOrPieceMatch__Contents.getContentNames_day.xml @@ -0,0 +1,21 @@ + + + + + 8 + 8 + 8 + 2 + 25% + http://www.example.com + + + + 4 + 4 + 4 + 2 + 50% + http://piwik.org/download + + \ No newline at end of file diff --git a/plugins/Contents/tests/System/expected/test_ContentscontentNameOrPieceMatch__Contents.getContentPieces_day.xml b/plugins/Contents/tests/System/expected/test_ContentscontentNameOrPieceMatch__Contents.getContentPieces_day.xml new file mode 100644 index 0000000000..7df6e4f0e1 --- /dev/null +++ b/plugins/Contents/tests/System/expected/test_ContentscontentNameOrPieceMatch__Contents.getContentPieces_day.xml @@ -0,0 +1,48 @@ + + + + + 4 + 4 + 4 + 2 + 50% + http://piwik.org/download + + + + 2 + 2 + 2 + 2 + 100% + http://www.example.com + + + + 2 + 2 + 2 + 0 + 0% + http://www.example.com + + + + 2 + 2 + 2 + 0 + 0% + + + + + 2 + 2 + 2 + 0 + 0% + + + \ No newline at end of file diff --git a/plugins/Contents/tests/System/expected/test_ContentscontentNameOrPieceMatch__Live.getLastVisitsDetails_day.xml b/plugins/Contents/tests/System/expected/test_ContentscontentNameOrPieceMatch__Live.getLastVisitsDetails_day.xml new file mode 100644 index 0000000000..989f816722 --- /dev/null +++ b/plugins/Contents/tests/System/expected/test_ContentscontentNameOrPieceMatch__Live.getLastVisitsDetails_day.xml @@ -0,0 +1,199 @@ + + + + 1 + 1 + 156.5.3.2 + + + + action + http://www.example.org/page + Ads + 2 + + 1 + 0.33s + 0 + 0s + + + + 0 + USD + $ + + + + + 0 + 1 + + new + + 0 + + 1 + + none + + 0 + 0 + 271 + 4 min 31s + + + Desktop + 0 + Unknown + Unknown + http://piwik.org/faq/general/#faq_52 + direct + Direct Entry + + + + + + + Europe + eur + France + fr + plugins/UserCountry/images/flags/fr.png + + + + France + + + Windows XP + WXP + Win XP + plugins/UserSettings/images/os/WXP.gif + gecko + Gecko (Firefox) + Firefox 3.6 + plugins/UserSettings/images/browsers/FF.gif + FF + 3.6 + normal + 1024x768 + plugins/UserSettings/images/screens/normal.gif + flash, java + + + plugins/UserSettings/images/plugins/flash.gif + flash + + + plugins/UserSettings/images/plugins/java.gif + java + + + 12:34:06 + 12 + 0 + + + + + + + + 1 + 2 + 111.1.1.1 + + + + action + http://www.example.org/page + Ads + 2 + + 13 + 0.33s + 0 + 0s + + + + 0 + USD + $ + + + + + 0 + 1 + + new + + 0 + + 1 + + none + + 0 + 0 + 271 + 4 min 31s + + + Desktop + 0 + Unknown + Unknown + http://piwik.org/faq/general/#faq_52 + direct + Direct Entry + + + + + + + Europe + eur + France + fr + plugins/UserCountry/images/flags/fr.png + + + + France + + + Windows XP + WXP + Win XP + plugins/UserSettings/images/os/WXP.gif + gecko + Gecko (Firefox) + Firefox 3.6 + plugins/UserSettings/images/browsers/FF.gif + FF + 3.6 + normal + 1024x768 + plugins/UserSettings/images/screens/normal.gif + director + + + plugins/UserSettings/images/plugins/director.gif + director + + + 12:34:06 + 12 + 0 + + + + + + + \ No newline at end of file diff --git a/plugins/Contents/tests/System/processed/.gitkeep b/plugins/Contents/tests/System/processed/.gitkeep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/plugins/Contents/tests/System/processed/test_Contents_Contents.getContentNames_lastN__API.getProcessedReport_day.xml b/plugins/Contents/tests/System/processed/test_Contents_Contents.getContentNames_lastN__API.getProcessedReport_day.xml new file mode 100644 index 0000000000..d3e1af1e2e --- /dev/null +++ b/plugins/Contents/tests/System/processed/test_Contents_Contents.getContentNames_lastN__API.getProcessedReport_day.xml @@ -0,0 +1,83 @@ + + + Piwik test + 3 Jan 10 - 9 Jan 10 + + Actions + Content Name + Contents + getContentNames + Content Name + + Impressions + Interactions + + + Interaction Rate + + getContentNames + index.php?module=API&method=ImageGraph.get&idSite=1&apiModule=Contents&apiAction=getContentNames&period=range&date=2010-01-03,2010-01-09 + index.php?module=API&method=ImageGraph.get&idSite=1&apiModule=Contents&apiAction=getContentNames&period=day&date=2010-01-03,2010-01-09 + Contents_getContentNames + + + + Impressions + Interactions + Interaction Rate + + + + + + 8 + 2 + 25% + + + + 6 + 4 + 66.67% + + + + 2 + 0 + 0% + + + + + + + + + + + + + http://www.example.com + + + + http://piwik.org/ + + + + + + + + + + + + + + + + 16 + 16 + + \ No newline at end of file diff --git a/plugins/Contents/tests/System/processed/test_Contents_Contents.getContentPieces_lastN__API.getProcessedReport_day.xml b/plugins/Contents/tests/System/processed/test_Contents_Contents.getContentPieces_lastN__API.getProcessedReport_day.xml new file mode 100644 index 0000000000..402909f7d5 --- /dev/null +++ b/plugins/Contents/tests/System/processed/test_Contents_Contents.getContentPieces_lastN__API.getProcessedReport_day.xml @@ -0,0 +1,123 @@ + + + Piwik test + 3 Jan 10 - 9 Jan 10 + + Actions + Content Piece + Contents + getContentPieces + Content Piece + + Impressions + Interactions + + + Interaction Rate + + getContentPieces + index.php?module=API&method=ImageGraph.get&idSite=1&apiModule=Contents&apiAction=getContentPieces&period=range&date=2010-01-03,2010-01-09 + index.php?module=API&method=ImageGraph.get&idSite=1&apiModule=Contents&apiAction=getContentPieces&period=day&date=2010-01-03,2010-01-09 + Contents_getContentPieces + + + + Impressions + Interactions + Interaction Rate + + + + + + 4 + 2 + 50% + + + + 2 + 2 + 100% + + + + 2 + 0 + 0% + + + + 2 + 2 + 100% + + + + 2 + 0 + 0% + + + + 2 + 0 + 0% + + + + 2 + 0 + 0% + + + + + + + + + + + + + http://piwik.org/download + + + + http://www.example.com + + + + http://www.example.com + + + + http://piwik.org/ + + + + + + + + + + + + + + + + + + + + + + + + 16 + 16 + + \ No newline at end of file diff --git a/plugins/Contents/tests/System/processed/test_Contents__Actions.getPageUrls_day.xml b/plugins/Contents/tests/System/processed/test_Contents__Actions.getPageUrls_day.xml new file mode 100644 index 0000000000..fde347f2b5 --- /dev/null +++ b/plugins/Contents/tests/System/processed/test_Contents__Actions.getPageUrls_day.xml @@ -0,0 +1,25 @@ + + + + + 2 + 2 + 2 + 540 + 2 + 0.333 + 0.333 + 2 + 2 + 2 + 542 + 2 + 2 + 2 + 270 + 100% + 100% + 0.333 + http://www.example.org/page + + \ No newline at end of file diff --git a/plugins/Contents/tests/System/processed/test_Contents__Actions.getPageUrls_month.xml b/plugins/Contents/tests/System/processed/test_Contents__Actions.getPageUrls_month.xml new file mode 100644 index 0000000000..3dc775d40a --- /dev/null +++ b/plugins/Contents/tests/System/processed/test_Contents__Actions.getPageUrls_month.xml @@ -0,0 +1,25 @@ + + + + + 2 + 2 + 540 + 2 + 0.333 + 0.333 + 2 + 2 + 542 + 2 + 2 + 2 + 2 + 2 + 270 + 100% + 100% + 0.333 + http://www.example.org/page + + \ No newline at end of file diff --git a/plugins/Contents/tests/System/processed/test_Contents__Actions.get_day.xml b/plugins/Contents/tests/System/processed/test_Contents__Actions.get_day.xml new file mode 100644 index 0000000000..f51cfaf913 --- /dev/null +++ b/plugins/Contents/tests/System/processed/test_Contents__Actions.get_day.xml @@ -0,0 +1,12 @@ + + + 2 + 2 + 0 + 0 + 0 + 0 + 0 + 0 + 0.335 + \ No newline at end of file diff --git a/plugins/Contents/tests/System/processed/test_Contents__Actions.get_month.xml b/plugins/Contents/tests/System/processed/test_Contents__Actions.get_month.xml new file mode 100644 index 0000000000..f51cfaf913 --- /dev/null +++ b/plugins/Contents/tests/System/processed/test_Contents__Actions.get_month.xml @@ -0,0 +1,12 @@ + + + 2 + 2 + 0 + 0 + 0 + 0 + 0 + 0 + 0.335 + \ No newline at end of file diff --git a/plugins/Contents/tests/System/processed/test_Contents__Contents.getContentNames_day.xml b/plugins/Contents/tests/System/processed/test_Contents__Contents.getContentNames_day.xml new file mode 100644 index 0000000000..957c6fa85a --- /dev/null +++ b/plugins/Contents/tests/System/processed/test_Contents__Contents.getContentNames_day.xml @@ -0,0 +1,30 @@ + + + + + 8 + 8 + 8 + 2 + 25% + http://www.example.com + + + + 6 + 6 + 6 + 4 + 66.67% + http://piwik.org/ + + + + 2 + 2 + 2 + 0 + 0% + + + \ No newline at end of file diff --git a/plugins/Contents/tests/System/processed/test_Contents__Contents.getContentNames_month.xml b/plugins/Contents/tests/System/processed/test_Contents__Contents.getContentNames_month.xml new file mode 100644 index 0000000000..44bfdfd54e --- /dev/null +++ b/plugins/Contents/tests/System/processed/test_Contents__Contents.getContentNames_month.xml @@ -0,0 +1,30 @@ + + + + + 8 + 8 + 2 + 8 + 25% + http://www.example.com + + + + 6 + 6 + 4 + 6 + 66.67% + http://piwik.org/ + + + + 2 + 2 + 0 + 2 + 0% + + + \ No newline at end of file diff --git a/plugins/Contents/tests/System/processed/test_Contents__Contents.getContentPieces_day.xml b/plugins/Contents/tests/System/processed/test_Contents__Contents.getContentPieces_day.xml new file mode 100644 index 0000000000..8927f8a8ec --- /dev/null +++ b/plugins/Contents/tests/System/processed/test_Contents__Contents.getContentPieces_day.xml @@ -0,0 +1,66 @@ + + + + + 4 + 4 + 4 + 2 + 50% + http://piwik.org/download + + + + 2 + 2 + 2 + 2 + 100% + http://www.example.com + + + + 2 + 2 + 2 + 0 + 0% + http://www.example.com + + + + 2 + 2 + 2 + 2 + 100% + http://piwik.org/ + + + + 2 + 2 + 2 + 0 + 0% + + + + + 2 + 2 + 2 + 0 + 0% + + + + + 2 + 2 + 2 + 0 + 0% + + + \ No newline at end of file diff --git a/plugins/Contents/tests/System/processed/test_Contents__Contents.getContentPieces_month.xml b/plugins/Contents/tests/System/processed/test_Contents__Contents.getContentPieces_month.xml new file mode 100644 index 0000000000..b604544417 --- /dev/null +++ b/plugins/Contents/tests/System/processed/test_Contents__Contents.getContentPieces_month.xml @@ -0,0 +1,66 @@ + + + + + 4 + 4 + 2 + 4 + 50% + http://piwik.org/download + + + + 2 + 2 + 2 + 2 + 100% + http://www.example.com + + + + 2 + 2 + 0 + 2 + 0% + http://www.example.com + + + + 2 + 2 + 2 + 2 + 100% + http://piwik.org/ + + + + 2 + 2 + 0 + 2 + 0% + + + + + 2 + 2 + 0 + 2 + 0% + + + + + 2 + 2 + 0 + 2 + 0% + + + \ No newline at end of file diff --git a/plugins/Contents/tests/System/processed/test_Contents__Live.getLastVisitsDetails_day.xml b/plugins/Contents/tests/System/processed/test_Contents__Live.getLastVisitsDetails_day.xml new file mode 100644 index 0000000000..989f816722 --- /dev/null +++ b/plugins/Contents/tests/System/processed/test_Contents__Live.getLastVisitsDetails_day.xml @@ -0,0 +1,199 @@ + + + + 1 + 1 + 156.5.3.2 + + + + action + http://www.example.org/page + Ads + 2 + + 1 + 0.33s + 0 + 0s + + + + 0 + USD + $ + + + + + 0 + 1 + + new + + 0 + + 1 + + none + + 0 + 0 + 271 + 4 min 31s + + + Desktop + 0 + Unknown + Unknown + http://piwik.org/faq/general/#faq_52 + direct + Direct Entry + + + + + + + Europe + eur + France + fr + plugins/UserCountry/images/flags/fr.png + + + + France + + + Windows XP + WXP + Win XP + plugins/UserSettings/images/os/WXP.gif + gecko + Gecko (Firefox) + Firefox 3.6 + plugins/UserSettings/images/browsers/FF.gif + FF + 3.6 + normal + 1024x768 + plugins/UserSettings/images/screens/normal.gif + flash, java + + + plugins/UserSettings/images/plugins/flash.gif + flash + + + plugins/UserSettings/images/plugins/java.gif + java + + + 12:34:06 + 12 + 0 + + + + + + + + 1 + 2 + 111.1.1.1 + + + + action + http://www.example.org/page + Ads + 2 + + 13 + 0.33s + 0 + 0s + + + + 0 + USD + $ + + + + + 0 + 1 + + new + + 0 + + 1 + + none + + 0 + 0 + 271 + 4 min 31s + + + Desktop + 0 + Unknown + Unknown + http://piwik.org/faq/general/#faq_52 + direct + Direct Entry + + + + + + + Europe + eur + France + fr + plugins/UserCountry/images/flags/fr.png + + + + France + + + Windows XP + WXP + Win XP + plugins/UserSettings/images/os/WXP.gif + gecko + Gecko (Firefox) + Firefox 3.6 + plugins/UserSettings/images/browsers/FF.gif + FF + 3.6 + normal + 1024x768 + plugins/UserSettings/images/screens/normal.gif + director + + + plugins/UserSettings/images/plugins/director.gif + director + + + 12:34:06 + 12 + 0 + + + + + + + \ No newline at end of file diff --git a/plugins/Contents/tests/System/processed/test_Contents__Live.getLastVisitsDetails_month.xml b/plugins/Contents/tests/System/processed/test_Contents__Live.getLastVisitsDetails_month.xml new file mode 100644 index 0000000000..989f816722 --- /dev/null +++ b/plugins/Contents/tests/System/processed/test_Contents__Live.getLastVisitsDetails_month.xml @@ -0,0 +1,199 @@ + + + + 1 + 1 + 156.5.3.2 + + + + action + http://www.example.org/page + Ads + 2 + + 1 + 0.33s + 0 + 0s + + + + 0 + USD + $ + + + + + 0 + 1 + + new + + 0 + + 1 + + none + + 0 + 0 + 271 + 4 min 31s + + + Desktop + 0 + Unknown + Unknown + http://piwik.org/faq/general/#faq_52 + direct + Direct Entry + + + + + + + Europe + eur + France + fr + plugins/UserCountry/images/flags/fr.png + + + + France + + + Windows XP + WXP + Win XP + plugins/UserSettings/images/os/WXP.gif + gecko + Gecko (Firefox) + Firefox 3.6 + plugins/UserSettings/images/browsers/FF.gif + FF + 3.6 + normal + 1024x768 + plugins/UserSettings/images/screens/normal.gif + flash, java + + + plugins/UserSettings/images/plugins/flash.gif + flash + + + plugins/UserSettings/images/plugins/java.gif + java + + + 12:34:06 + 12 + 0 + + + + + + + + 1 + 2 + 111.1.1.1 + + + + action + http://www.example.org/page + Ads + 2 + + 13 + 0.33s + 0 + 0s + + + + 0 + USD + $ + + + + + 0 + 1 + + new + + 0 + + 1 + + none + + 0 + 0 + 271 + 4 min 31s + + + Desktop + 0 + Unknown + Unknown + http://piwik.org/faq/general/#faq_52 + direct + Direct Entry + + + + + + + Europe + eur + France + fr + plugins/UserCountry/images/flags/fr.png + + + + France + + + Windows XP + WXP + Win XP + plugins/UserSettings/images/os/WXP.gif + gecko + Gecko (Firefox) + Firefox 3.6 + plugins/UserSettings/images/browsers/FF.gif + FF + 3.6 + normal + 1024x768 + plugins/UserSettings/images/screens/normal.gif + director + + + plugins/UserSettings/images/plugins/director.gif + director + + + 12:34:06 + 12 + 0 + + + + + + + \ No newline at end of file diff --git a/plugins/Contents/tests/System/processed/test_Contents_contentInteractionMatch__Actions.getPageUrls_day.xml b/plugins/Contents/tests/System/processed/test_Contents_contentInteractionMatch__Actions.getPageUrls_day.xml new file mode 100644 index 0000000000..c234bed59e --- /dev/null +++ b/plugins/Contents/tests/System/processed/test_Contents_contentInteractionMatch__Actions.getPageUrls_day.xml @@ -0,0 +1,2 @@ + + \ No newline at end of file diff --git a/plugins/Contents/tests/System/processed/test_Contents_contentInteractionMatch__Contents.getContentNames_day.xml b/plugins/Contents/tests/System/processed/test_Contents_contentInteractionMatch__Contents.getContentNames_day.xml new file mode 100644 index 0000000000..c234bed59e --- /dev/null +++ b/plugins/Contents/tests/System/processed/test_Contents_contentInteractionMatch__Contents.getContentNames_day.xml @@ -0,0 +1,2 @@ + + \ No newline at end of file diff --git a/plugins/Contents/tests/System/processed/test_Contents_contentInteractionMatch__Contents.getContentPieces_day.xml b/plugins/Contents/tests/System/processed/test_Contents_contentInteractionMatch__Contents.getContentPieces_day.xml new file mode 100644 index 0000000000..c234bed59e --- /dev/null +++ b/plugins/Contents/tests/System/processed/test_Contents_contentInteractionMatch__Contents.getContentPieces_day.xml @@ -0,0 +1,2 @@ + + \ No newline at end of file diff --git a/plugins/Contents/tests/System/processed/test_Contents_contentInteractionMatch__Live.getLastVisitsDetails_day.xml b/plugins/Contents/tests/System/processed/test_Contents_contentInteractionMatch__Live.getLastVisitsDetails_day.xml new file mode 100644 index 0000000000..989f816722 --- /dev/null +++ b/plugins/Contents/tests/System/processed/test_Contents_contentInteractionMatch__Live.getLastVisitsDetails_day.xml @@ -0,0 +1,199 @@ + + + + 1 + 1 + 156.5.3.2 + + + + action + http://www.example.org/page + Ads + 2 + + 1 + 0.33s + 0 + 0s + + + + 0 + USD + $ + + + + + 0 + 1 + + new + + 0 + + 1 + + none + + 0 + 0 + 271 + 4 min 31s + + + Desktop + 0 + Unknown + Unknown + http://piwik.org/faq/general/#faq_52 + direct + Direct Entry + + + + + + + Europe + eur + France + fr + plugins/UserCountry/images/flags/fr.png + + + + France + + + Windows XP + WXP + Win XP + plugins/UserSettings/images/os/WXP.gif + gecko + Gecko (Firefox) + Firefox 3.6 + plugins/UserSettings/images/browsers/FF.gif + FF + 3.6 + normal + 1024x768 + plugins/UserSettings/images/screens/normal.gif + flash, java + + + plugins/UserSettings/images/plugins/flash.gif + flash + + + plugins/UserSettings/images/plugins/java.gif + java + + + 12:34:06 + 12 + 0 + + + + + + + + 1 + 2 + 111.1.1.1 + + + + action + http://www.example.org/page + Ads + 2 + + 13 + 0.33s + 0 + 0s + + + + 0 + USD + $ + + + + + 0 + 1 + + new + + 0 + + 1 + + none + + 0 + 0 + 271 + 4 min 31s + + + Desktop + 0 + Unknown + Unknown + http://piwik.org/faq/general/#faq_52 + direct + Direct Entry + + + + + + + Europe + eur + France + fr + plugins/UserCountry/images/flags/fr.png + + + + France + + + Windows XP + WXP + Win XP + plugins/UserSettings/images/os/WXP.gif + gecko + Gecko (Firefox) + Firefox 3.6 + plugins/UserSettings/images/browsers/FF.gif + FF + 3.6 + normal + 1024x768 + plugins/UserSettings/images/screens/normal.gif + director + + + plugins/UserSettings/images/plugins/director.gif + director + + + 12:34:06 + 12 + 0 + + + + + + + \ No newline at end of file diff --git a/plugins/Contents/tests/System/processed/test_Contents_contentTargetMatch__Actions.getPageUrls_day.xml b/plugins/Contents/tests/System/processed/test_Contents_contentTargetMatch__Actions.getPageUrls_day.xml new file mode 100644 index 0000000000..c234bed59e --- /dev/null +++ b/plugins/Contents/tests/System/processed/test_Contents_contentTargetMatch__Actions.getPageUrls_day.xml @@ -0,0 +1,2 @@ + + \ No newline at end of file diff --git a/plugins/Contents/tests/System/processed/test_Contents_contentTargetMatch__Contents.getContentNames_day.xml b/plugins/Contents/tests/System/processed/test_Contents_contentTargetMatch__Contents.getContentNames_day.xml new file mode 100644 index 0000000000..5212486a1c --- /dev/null +++ b/plugins/Contents/tests/System/processed/test_Contents_contentTargetMatch__Contents.getContentNames_day.xml @@ -0,0 +1,12 @@ + + + + + 4 + 4 + 4 + 2 + 50% + http://www.example.com + + \ No newline at end of file diff --git a/plugins/Contents/tests/System/processed/test_Contents_contentTargetMatch__Contents.getContentPieces_day.xml b/plugins/Contents/tests/System/processed/test_Contents_contentTargetMatch__Contents.getContentPieces_day.xml new file mode 100644 index 0000000000..ac1d39a577 --- /dev/null +++ b/plugins/Contents/tests/System/processed/test_Contents_contentTargetMatch__Contents.getContentPieces_day.xml @@ -0,0 +1,21 @@ + + + + + 2 + 2 + 2 + 2 + 100% + http://www.example.com + + + + 2 + 2 + 2 + 0 + 0% + http://www.example.com + + \ No newline at end of file diff --git a/plugins/Contents/tests/System/processed/test_Contents_contentTargetMatch__Live.getLastVisitsDetails_day.xml b/plugins/Contents/tests/System/processed/test_Contents_contentTargetMatch__Live.getLastVisitsDetails_day.xml new file mode 100644 index 0000000000..989f816722 --- /dev/null +++ b/plugins/Contents/tests/System/processed/test_Contents_contentTargetMatch__Live.getLastVisitsDetails_day.xml @@ -0,0 +1,199 @@ + + + + 1 + 1 + 156.5.3.2 + + + + action + http://www.example.org/page + Ads + 2 + + 1 + 0.33s + 0 + 0s + + + + 0 + USD + $ + + + + + 0 + 1 + + new + + 0 + + 1 + + none + + 0 + 0 + 271 + 4 min 31s + + + Desktop + 0 + Unknown + Unknown + http://piwik.org/faq/general/#faq_52 + direct + Direct Entry + + + + + + + Europe + eur + France + fr + plugins/UserCountry/images/flags/fr.png + + + + France + + + Windows XP + WXP + Win XP + plugins/UserSettings/images/os/WXP.gif + gecko + Gecko (Firefox) + Firefox 3.6 + plugins/UserSettings/images/browsers/FF.gif + FF + 3.6 + normal + 1024x768 + plugins/UserSettings/images/screens/normal.gif + flash, java + + + plugins/UserSettings/images/plugins/flash.gif + flash + + + plugins/UserSettings/images/plugins/java.gif + java + + + 12:34:06 + 12 + 0 + + + + + + + + 1 + 2 + 111.1.1.1 + + + + action + http://www.example.org/page + Ads + 2 + + 13 + 0.33s + 0 + 0s + + + + 0 + USD + $ + + + + + 0 + 1 + + new + + 0 + + 1 + + none + + 0 + 0 + 271 + 4 min 31s + + + Desktop + 0 + Unknown + Unknown + http://piwik.org/faq/general/#faq_52 + direct + Direct Entry + + + + + + + Europe + eur + France + fr + plugins/UserCountry/images/flags/fr.png + + + + France + + + Windows XP + WXP + Win XP + plugins/UserSettings/images/os/WXP.gif + gecko + Gecko (Firefox) + Firefox 3.6 + plugins/UserSettings/images/browsers/FF.gif + FF + 3.6 + normal + 1024x768 + plugins/UserSettings/images/screens/normal.gif + director + + + plugins/UserSettings/images/plugins/director.gif + director + + + 12:34:06 + 12 + 0 + + + + + + + \ No newline at end of file diff --git a/plugins/Contents/tests/System/processed/test_ContentscontentNameOrPieceMatch__Actions.getPageUrls_day.xml b/plugins/Contents/tests/System/processed/test_ContentscontentNameOrPieceMatch__Actions.getPageUrls_day.xml new file mode 100644 index 0000000000..c234bed59e --- /dev/null +++ b/plugins/Contents/tests/System/processed/test_ContentscontentNameOrPieceMatch__Actions.getPageUrls_day.xml @@ -0,0 +1,2 @@ + + \ No newline at end of file diff --git a/plugins/Contents/tests/System/processed/test_ContentscontentNameOrPieceMatch__Contents.getContentNames_day.xml b/plugins/Contents/tests/System/processed/test_ContentscontentNameOrPieceMatch__Contents.getContentNames_day.xml new file mode 100644 index 0000000000..17b781db1c --- /dev/null +++ b/plugins/Contents/tests/System/processed/test_ContentscontentNameOrPieceMatch__Contents.getContentNames_day.xml @@ -0,0 +1,21 @@ + + + + + 8 + 8 + 8 + 2 + 25% + http://www.example.com + + + + 4 + 4 + 4 + 2 + 50% + http://piwik.org/download + + \ No newline at end of file diff --git a/plugins/Contents/tests/System/processed/test_ContentscontentNameOrPieceMatch__Contents.getContentPieces_day.xml b/plugins/Contents/tests/System/processed/test_ContentscontentNameOrPieceMatch__Contents.getContentPieces_day.xml new file mode 100644 index 0000000000..7df6e4f0e1 --- /dev/null +++ b/plugins/Contents/tests/System/processed/test_ContentscontentNameOrPieceMatch__Contents.getContentPieces_day.xml @@ -0,0 +1,48 @@ + + + + + 4 + 4 + 4 + 2 + 50% + http://piwik.org/download + + + + 2 + 2 + 2 + 2 + 100% + http://www.example.com + + + + 2 + 2 + 2 + 0 + 0% + http://www.example.com + + + + 2 + 2 + 2 + 0 + 0% + + + + + 2 + 2 + 2 + 0 + 0% + + + \ No newline at end of file diff --git a/plugins/Contents/tests/System/processed/test_ContentscontentNameOrPieceMatch__Live.getLastVisitsDetails_day.xml b/plugins/Contents/tests/System/processed/test_ContentscontentNameOrPieceMatch__Live.getLastVisitsDetails_day.xml new file mode 100644 index 0000000000..989f816722 --- /dev/null +++ b/plugins/Contents/tests/System/processed/test_ContentscontentNameOrPieceMatch__Live.getLastVisitsDetails_day.xml @@ -0,0 +1,199 @@ + + + + 1 + 1 + 156.5.3.2 + + + + action + http://www.example.org/page + Ads + 2 + + 1 + 0.33s + 0 + 0s + + + + 0 + USD + $ + + + + + 0 + 1 + + new + + 0 + + 1 + + none + + 0 + 0 + 271 + 4 min 31s + + + Desktop + 0 + Unknown + Unknown + http://piwik.org/faq/general/#faq_52 + direct + Direct Entry + + + + + + + Europe + eur + France + fr + plugins/UserCountry/images/flags/fr.png + + + + France + + + Windows XP + WXP + Win XP + plugins/UserSettings/images/os/WXP.gif + gecko + Gecko (Firefox) + Firefox 3.6 + plugins/UserSettings/images/browsers/FF.gif + FF + 3.6 + normal + 1024x768 + plugins/UserSettings/images/screens/normal.gif + flash, java + + + plugins/UserSettings/images/plugins/flash.gif + flash + + + plugins/UserSettings/images/plugins/java.gif + java + + + 12:34:06 + 12 + 0 + + + + + + + + 1 + 2 + 111.1.1.1 + + + + action + http://www.example.org/page + Ads + 2 + + 13 + 0.33s + 0 + 0s + + + + 0 + USD + $ + + + + + 0 + 1 + + new + + 0 + + 1 + + none + + 0 + 0 + 271 + 4 min 31s + + + Desktop + 0 + Unknown + Unknown + http://piwik.org/faq/general/#faq_52 + direct + Direct Entry + + + + + + + Europe + eur + France + fr + plugins/UserCountry/images/flags/fr.png + + + + France + + + Windows XP + WXP + Win XP + plugins/UserSettings/images/os/WXP.gif + gecko + Gecko (Firefox) + Firefox 3.6 + plugins/UserSettings/images/browsers/FF.gif + FF + 3.6 + normal + 1024x768 + plugins/UserSettings/images/screens/normal.gif + director + + + plugins/UserSettings/images/plugins/director.gif + director + + + 12:34:06 + 12 + 0 + + + + + + + \ No newline at end of file diff --git a/plugins/Contents/tests/expected/test_Contents_Contents.getContentNames_lastN__API.getProcessedReport_day.xml b/plugins/Contents/tests/expected/test_Contents_Contents.getContentNames_lastN__API.getProcessedReport_day.xml deleted file mode 100644 index d3e1af1e2e..0000000000 --- a/plugins/Contents/tests/expected/test_Contents_Contents.getContentNames_lastN__API.getProcessedReport_day.xml +++ /dev/null @@ -1,83 +0,0 @@ - - - Piwik test - 3 Jan 10 - 9 Jan 10 - - Actions - Content Name - Contents - getContentNames - Content Name - - Impressions - Interactions - - - Interaction Rate - - getContentNames - index.php?module=API&method=ImageGraph.get&idSite=1&apiModule=Contents&apiAction=getContentNames&period=range&date=2010-01-03,2010-01-09 - index.php?module=API&method=ImageGraph.get&idSite=1&apiModule=Contents&apiAction=getContentNames&period=day&date=2010-01-03,2010-01-09 - Contents_getContentNames - - - - Impressions - Interactions - Interaction Rate - - - - - - 8 - 2 - 25% - - - - 6 - 4 - 66.67% - - - - 2 - 0 - 0% - - - - - - - - - - - - - http://www.example.com - - - - http://piwik.org/ - - - - - - - - - - - - - - - - 16 - 16 - - \ No newline at end of file diff --git a/plugins/Contents/tests/expected/test_Contents_Contents.getContentPieces_lastN__API.getProcessedReport_day.xml b/plugins/Contents/tests/expected/test_Contents_Contents.getContentPieces_lastN__API.getProcessedReport_day.xml deleted file mode 100644 index 402909f7d5..0000000000 --- a/plugins/Contents/tests/expected/test_Contents_Contents.getContentPieces_lastN__API.getProcessedReport_day.xml +++ /dev/null @@ -1,123 +0,0 @@ - - - Piwik test - 3 Jan 10 - 9 Jan 10 - - Actions - Content Piece - Contents - getContentPieces - Content Piece - - Impressions - Interactions - - - Interaction Rate - - getContentPieces - index.php?module=API&method=ImageGraph.get&idSite=1&apiModule=Contents&apiAction=getContentPieces&period=range&date=2010-01-03,2010-01-09 - index.php?module=API&method=ImageGraph.get&idSite=1&apiModule=Contents&apiAction=getContentPieces&period=day&date=2010-01-03,2010-01-09 - Contents_getContentPieces - - - - Impressions - Interactions - Interaction Rate - - - - - - 4 - 2 - 50% - - - - 2 - 2 - 100% - - - - 2 - 0 - 0% - - - - 2 - 2 - 100% - - - - 2 - 0 - 0% - - - - 2 - 0 - 0% - - - - 2 - 0 - 0% - - - - - - - - - - - - - http://piwik.org/download - - - - http://www.example.com - - - - http://www.example.com - - - - http://piwik.org/ - - - - - - - - - - - - - - - - - - - - - - - - 16 - 16 - - \ No newline at end of file diff --git a/plugins/Contents/tests/expected/test_Contents__Actions.getPageUrls_day.xml b/plugins/Contents/tests/expected/test_Contents__Actions.getPageUrls_day.xml deleted file mode 100644 index fde347f2b5..0000000000 --- a/plugins/Contents/tests/expected/test_Contents__Actions.getPageUrls_day.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - - - 2 - 2 - 2 - 540 - 2 - 0.333 - 0.333 - 2 - 2 - 2 - 542 - 2 - 2 - 2 - 270 - 100% - 100% - 0.333 - http://www.example.org/page - - \ No newline at end of file diff --git a/plugins/Contents/tests/expected/test_Contents__Actions.getPageUrls_month.xml b/plugins/Contents/tests/expected/test_Contents__Actions.getPageUrls_month.xml deleted file mode 100644 index 3dc775d40a..0000000000 --- a/plugins/Contents/tests/expected/test_Contents__Actions.getPageUrls_month.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - - - 2 - 2 - 540 - 2 - 0.333 - 0.333 - 2 - 2 - 542 - 2 - 2 - 2 - 2 - 2 - 270 - 100% - 100% - 0.333 - http://www.example.org/page - - \ No newline at end of file diff --git a/plugins/Contents/tests/expected/test_Contents__Actions.get_day.xml b/plugins/Contents/tests/expected/test_Contents__Actions.get_day.xml deleted file mode 100644 index f51cfaf913..0000000000 --- a/plugins/Contents/tests/expected/test_Contents__Actions.get_day.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - 2 - 2 - 0 - 0 - 0 - 0 - 0 - 0 - 0.335 - \ No newline at end of file diff --git a/plugins/Contents/tests/expected/test_Contents__Actions.get_month.xml b/plugins/Contents/tests/expected/test_Contents__Actions.get_month.xml deleted file mode 100644 index f51cfaf913..0000000000 --- a/plugins/Contents/tests/expected/test_Contents__Actions.get_month.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - 2 - 2 - 0 - 0 - 0 - 0 - 0 - 0 - 0.335 - \ No newline at end of file diff --git a/plugins/Contents/tests/expected/test_Contents__Contents.getContentNames_day.xml b/plugins/Contents/tests/expected/test_Contents__Contents.getContentNames_day.xml deleted file mode 100644 index 957c6fa85a..0000000000 --- a/plugins/Contents/tests/expected/test_Contents__Contents.getContentNames_day.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - - 8 - 8 - 8 - 2 - 25% - http://www.example.com - - - - 6 - 6 - 6 - 4 - 66.67% - http://piwik.org/ - - - - 2 - 2 - 2 - 0 - 0% - - - \ No newline at end of file diff --git a/plugins/Contents/tests/expected/test_Contents__Contents.getContentNames_month.xml b/plugins/Contents/tests/expected/test_Contents__Contents.getContentNames_month.xml deleted file mode 100644 index 44bfdfd54e..0000000000 --- a/plugins/Contents/tests/expected/test_Contents__Contents.getContentNames_month.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - - 8 - 8 - 2 - 8 - 25% - http://www.example.com - - - - 6 - 6 - 4 - 6 - 66.67% - http://piwik.org/ - - - - 2 - 2 - 0 - 2 - 0% - - - \ No newline at end of file diff --git a/plugins/Contents/tests/expected/test_Contents__Contents.getContentPieces_day.xml b/plugins/Contents/tests/expected/test_Contents__Contents.getContentPieces_day.xml deleted file mode 100644 index 8927f8a8ec..0000000000 --- a/plugins/Contents/tests/expected/test_Contents__Contents.getContentPieces_day.xml +++ /dev/null @@ -1,66 +0,0 @@ - - - - - 4 - 4 - 4 - 2 - 50% - http://piwik.org/download - - - - 2 - 2 - 2 - 2 - 100% - http://www.example.com - - - - 2 - 2 - 2 - 0 - 0% - http://www.example.com - - - - 2 - 2 - 2 - 2 - 100% - http://piwik.org/ - - - - 2 - 2 - 2 - 0 - 0% - - - - - 2 - 2 - 2 - 0 - 0% - - - - - 2 - 2 - 2 - 0 - 0% - - - \ No newline at end of file diff --git a/plugins/Contents/tests/expected/test_Contents__Contents.getContentPieces_month.xml b/plugins/Contents/tests/expected/test_Contents__Contents.getContentPieces_month.xml deleted file mode 100644 index b604544417..0000000000 --- a/plugins/Contents/tests/expected/test_Contents__Contents.getContentPieces_month.xml +++ /dev/null @@ -1,66 +0,0 @@ - - - - - 4 - 4 - 2 - 4 - 50% - http://piwik.org/download - - - - 2 - 2 - 2 - 2 - 100% - http://www.example.com - - - - 2 - 2 - 0 - 2 - 0% - http://www.example.com - - - - 2 - 2 - 2 - 2 - 100% - http://piwik.org/ - - - - 2 - 2 - 0 - 2 - 0% - - - - - 2 - 2 - 0 - 2 - 0% - - - - - 2 - 2 - 0 - 2 - 0% - - - \ No newline at end of file diff --git a/plugins/Contents/tests/expected/test_Contents__Live.getLastVisitsDetails_day.xml b/plugins/Contents/tests/expected/test_Contents__Live.getLastVisitsDetails_day.xml deleted file mode 100644 index 989f816722..0000000000 --- a/plugins/Contents/tests/expected/test_Contents__Live.getLastVisitsDetails_day.xml +++ /dev/null @@ -1,199 +0,0 @@ - - - - 1 - 1 - 156.5.3.2 - - - - action - http://www.example.org/page - Ads - 2 - - 1 - 0.33s - 0 - 0s - - - - 0 - USD - $ - - - - - 0 - 1 - - new - - 0 - - 1 - - none - - 0 - 0 - 271 - 4 min 31s - - - Desktop - 0 - Unknown - Unknown - http://piwik.org/faq/general/#faq_52 - direct - Direct Entry - - - - - - - Europe - eur - France - fr - plugins/UserCountry/images/flags/fr.png - - - - France - - - Windows XP - WXP - Win XP - plugins/UserSettings/images/os/WXP.gif - gecko - Gecko (Firefox) - Firefox 3.6 - plugins/UserSettings/images/browsers/FF.gif - FF - 3.6 - normal - 1024x768 - plugins/UserSettings/images/screens/normal.gif - flash, java - - - plugins/UserSettings/images/plugins/flash.gif - flash - - - plugins/UserSettings/images/plugins/java.gif - java - - - 12:34:06 - 12 - 0 - - - - - - - - 1 - 2 - 111.1.1.1 - - - - action - http://www.example.org/page - Ads - 2 - - 13 - 0.33s - 0 - 0s - - - - 0 - USD - $ - - - - - 0 - 1 - - new - - 0 - - 1 - - none - - 0 - 0 - 271 - 4 min 31s - - - Desktop - 0 - Unknown - Unknown - http://piwik.org/faq/general/#faq_52 - direct - Direct Entry - - - - - - - Europe - eur - France - fr - plugins/UserCountry/images/flags/fr.png - - - - France - - - Windows XP - WXP - Win XP - plugins/UserSettings/images/os/WXP.gif - gecko - Gecko (Firefox) - Firefox 3.6 - plugins/UserSettings/images/browsers/FF.gif - FF - 3.6 - normal - 1024x768 - plugins/UserSettings/images/screens/normal.gif - director - - - plugins/UserSettings/images/plugins/director.gif - director - - - 12:34:06 - 12 - 0 - - - - - - - \ No newline at end of file diff --git a/plugins/Contents/tests/expected/test_Contents__Live.getLastVisitsDetails_month.xml b/plugins/Contents/tests/expected/test_Contents__Live.getLastVisitsDetails_month.xml deleted file mode 100644 index 989f816722..0000000000 --- a/plugins/Contents/tests/expected/test_Contents__Live.getLastVisitsDetails_month.xml +++ /dev/null @@ -1,199 +0,0 @@ - - - - 1 - 1 - 156.5.3.2 - - - - action - http://www.example.org/page - Ads - 2 - - 1 - 0.33s - 0 - 0s - - - - 0 - USD - $ - - - - - 0 - 1 - - new - - 0 - - 1 - - none - - 0 - 0 - 271 - 4 min 31s - - - Desktop - 0 - Unknown - Unknown - http://piwik.org/faq/general/#faq_52 - direct - Direct Entry - - - - - - - Europe - eur - France - fr - plugins/UserCountry/images/flags/fr.png - - - - France - - - Windows XP - WXP - Win XP - plugins/UserSettings/images/os/WXP.gif - gecko - Gecko (Firefox) - Firefox 3.6 - plugins/UserSettings/images/browsers/FF.gif - FF - 3.6 - normal - 1024x768 - plugins/UserSettings/images/screens/normal.gif - flash, java - - - plugins/UserSettings/images/plugins/flash.gif - flash - - - plugins/UserSettings/images/plugins/java.gif - java - - - 12:34:06 - 12 - 0 - - - - - - - - 1 - 2 - 111.1.1.1 - - - - action - http://www.example.org/page - Ads - 2 - - 13 - 0.33s - 0 - 0s - - - - 0 - USD - $ - - - - - 0 - 1 - - new - - 0 - - 1 - - none - - 0 - 0 - 271 - 4 min 31s - - - Desktop - 0 - Unknown - Unknown - http://piwik.org/faq/general/#faq_52 - direct - Direct Entry - - - - - - - Europe - eur - France - fr - plugins/UserCountry/images/flags/fr.png - - - - France - - - Windows XP - WXP - Win XP - plugins/UserSettings/images/os/WXP.gif - gecko - Gecko (Firefox) - Firefox 3.6 - plugins/UserSettings/images/browsers/FF.gif - FF - 3.6 - normal - 1024x768 - plugins/UserSettings/images/screens/normal.gif - director - - - plugins/UserSettings/images/plugins/director.gif - director - - - 12:34:06 - 12 - 0 - - - - - - - \ No newline at end of file diff --git a/plugins/Contents/tests/expected/test_Contents_contentInteractionMatch__Actions.getPageUrls_day.xml b/plugins/Contents/tests/expected/test_Contents_contentInteractionMatch__Actions.getPageUrls_day.xml deleted file mode 100644 index c234bed59e..0000000000 --- a/plugins/Contents/tests/expected/test_Contents_contentInteractionMatch__Actions.getPageUrls_day.xml +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/plugins/Contents/tests/expected/test_Contents_contentInteractionMatch__Contents.getContentNames_day.xml b/plugins/Contents/tests/expected/test_Contents_contentInteractionMatch__Contents.getContentNames_day.xml deleted file mode 100644 index c234bed59e..0000000000 --- a/plugins/Contents/tests/expected/test_Contents_contentInteractionMatch__Contents.getContentNames_day.xml +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/plugins/Contents/tests/expected/test_Contents_contentInteractionMatch__Contents.getContentPieces_day.xml b/plugins/Contents/tests/expected/test_Contents_contentInteractionMatch__Contents.getContentPieces_day.xml deleted file mode 100644 index c234bed59e..0000000000 --- a/plugins/Contents/tests/expected/test_Contents_contentInteractionMatch__Contents.getContentPieces_day.xml +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/plugins/Contents/tests/expected/test_Contents_contentInteractionMatch__Live.getLastVisitsDetails_day.xml b/plugins/Contents/tests/expected/test_Contents_contentInteractionMatch__Live.getLastVisitsDetails_day.xml deleted file mode 100644 index 989f816722..0000000000 --- a/plugins/Contents/tests/expected/test_Contents_contentInteractionMatch__Live.getLastVisitsDetails_day.xml +++ /dev/null @@ -1,199 +0,0 @@ - - - - 1 - 1 - 156.5.3.2 - - - - action - http://www.example.org/page - Ads - 2 - - 1 - 0.33s - 0 - 0s - - - - 0 - USD - $ - - - - - 0 - 1 - - new - - 0 - - 1 - - none - - 0 - 0 - 271 - 4 min 31s - - - Desktop - 0 - Unknown - Unknown - http://piwik.org/faq/general/#faq_52 - direct - Direct Entry - - - - - - - Europe - eur - France - fr - plugins/UserCountry/images/flags/fr.png - - - - France - - - Windows XP - WXP - Win XP - plugins/UserSettings/images/os/WXP.gif - gecko - Gecko (Firefox) - Firefox 3.6 - plugins/UserSettings/images/browsers/FF.gif - FF - 3.6 - normal - 1024x768 - plugins/UserSettings/images/screens/normal.gif - flash, java - - - plugins/UserSettings/images/plugins/flash.gif - flash - - - plugins/UserSettings/images/plugins/java.gif - java - - - 12:34:06 - 12 - 0 - - - - - - - - 1 - 2 - 111.1.1.1 - - - - action - http://www.example.org/page - Ads - 2 - - 13 - 0.33s - 0 - 0s - - - - 0 - USD - $ - - - - - 0 - 1 - - new - - 0 - - 1 - - none - - 0 - 0 - 271 - 4 min 31s - - - Desktop - 0 - Unknown - Unknown - http://piwik.org/faq/general/#faq_52 - direct - Direct Entry - - - - - - - Europe - eur - France - fr - plugins/UserCountry/images/flags/fr.png - - - - France - - - Windows XP - WXP - Win XP - plugins/UserSettings/images/os/WXP.gif - gecko - Gecko (Firefox) - Firefox 3.6 - plugins/UserSettings/images/browsers/FF.gif - FF - 3.6 - normal - 1024x768 - plugins/UserSettings/images/screens/normal.gif - director - - - plugins/UserSettings/images/plugins/director.gif - director - - - 12:34:06 - 12 - 0 - - - - - - - \ No newline at end of file diff --git a/plugins/Contents/tests/expected/test_Contents_contentTargetMatch__Actions.getPageUrls_day.xml b/plugins/Contents/tests/expected/test_Contents_contentTargetMatch__Actions.getPageUrls_day.xml deleted file mode 100644 index c234bed59e..0000000000 --- a/plugins/Contents/tests/expected/test_Contents_contentTargetMatch__Actions.getPageUrls_day.xml +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/plugins/Contents/tests/expected/test_Contents_contentTargetMatch__Contents.getContentNames_day.xml b/plugins/Contents/tests/expected/test_Contents_contentTargetMatch__Contents.getContentNames_day.xml deleted file mode 100644 index 5212486a1c..0000000000 --- a/plugins/Contents/tests/expected/test_Contents_contentTargetMatch__Contents.getContentNames_day.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - 4 - 4 - 4 - 2 - 50% - http://www.example.com - - \ No newline at end of file diff --git a/plugins/Contents/tests/expected/test_Contents_contentTargetMatch__Contents.getContentPieces_day.xml b/plugins/Contents/tests/expected/test_Contents_contentTargetMatch__Contents.getContentPieces_day.xml deleted file mode 100644 index ac1d39a577..0000000000 --- a/plugins/Contents/tests/expected/test_Contents_contentTargetMatch__Contents.getContentPieces_day.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - - 2 - 2 - 2 - 2 - 100% - http://www.example.com - - - - 2 - 2 - 2 - 0 - 0% - http://www.example.com - - \ No newline at end of file diff --git a/plugins/Contents/tests/expected/test_Contents_contentTargetMatch__Live.getLastVisitsDetails_day.xml b/plugins/Contents/tests/expected/test_Contents_contentTargetMatch__Live.getLastVisitsDetails_day.xml deleted file mode 100644 index 989f816722..0000000000 --- a/plugins/Contents/tests/expected/test_Contents_contentTargetMatch__Live.getLastVisitsDetails_day.xml +++ /dev/null @@ -1,199 +0,0 @@ - - - - 1 - 1 - 156.5.3.2 - - - - action - http://www.example.org/page - Ads - 2 - - 1 - 0.33s - 0 - 0s - - - - 0 - USD - $ - - - - - 0 - 1 - - new - - 0 - - 1 - - none - - 0 - 0 - 271 - 4 min 31s - - - Desktop - 0 - Unknown - Unknown - http://piwik.org/faq/general/#faq_52 - direct - Direct Entry - - - - - - - Europe - eur - France - fr - plugins/UserCountry/images/flags/fr.png - - - - France - - - Windows XP - WXP - Win XP - plugins/UserSettings/images/os/WXP.gif - gecko - Gecko (Firefox) - Firefox 3.6 - plugins/UserSettings/images/browsers/FF.gif - FF - 3.6 - normal - 1024x768 - plugins/UserSettings/images/screens/normal.gif - flash, java - - - plugins/UserSettings/images/plugins/flash.gif - flash - - - plugins/UserSettings/images/plugins/java.gif - java - - - 12:34:06 - 12 - 0 - - - - - - - - 1 - 2 - 111.1.1.1 - - - - action - http://www.example.org/page - Ads - 2 - - 13 - 0.33s - 0 - 0s - - - - 0 - USD - $ - - - - - 0 - 1 - - new - - 0 - - 1 - - none - - 0 - 0 - 271 - 4 min 31s - - - Desktop - 0 - Unknown - Unknown - http://piwik.org/faq/general/#faq_52 - direct - Direct Entry - - - - - - - Europe - eur - France - fr - plugins/UserCountry/images/flags/fr.png - - - - France - - - Windows XP - WXP - Win XP - plugins/UserSettings/images/os/WXP.gif - gecko - Gecko (Firefox) - Firefox 3.6 - plugins/UserSettings/images/browsers/FF.gif - FF - 3.6 - normal - 1024x768 - plugins/UserSettings/images/screens/normal.gif - director - - - plugins/UserSettings/images/plugins/director.gif - director - - - 12:34:06 - 12 - 0 - - - - - - - \ No newline at end of file diff --git a/plugins/Contents/tests/expected/test_ContentscontentNameOrPieceMatch__Actions.getPageUrls_day.xml b/plugins/Contents/tests/expected/test_ContentscontentNameOrPieceMatch__Actions.getPageUrls_day.xml deleted file mode 100644 index c234bed59e..0000000000 --- a/plugins/Contents/tests/expected/test_ContentscontentNameOrPieceMatch__Actions.getPageUrls_day.xml +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/plugins/Contents/tests/expected/test_ContentscontentNameOrPieceMatch__Contents.getContentNames_day.xml b/plugins/Contents/tests/expected/test_ContentscontentNameOrPieceMatch__Contents.getContentNames_day.xml deleted file mode 100644 index 17b781db1c..0000000000 --- a/plugins/Contents/tests/expected/test_ContentscontentNameOrPieceMatch__Contents.getContentNames_day.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - - 8 - 8 - 8 - 2 - 25% - http://www.example.com - - - - 4 - 4 - 4 - 2 - 50% - http://piwik.org/download - - \ No newline at end of file diff --git a/plugins/Contents/tests/expected/test_ContentscontentNameOrPieceMatch__Contents.getContentPieces_day.xml b/plugins/Contents/tests/expected/test_ContentscontentNameOrPieceMatch__Contents.getContentPieces_day.xml deleted file mode 100644 index 7df6e4f0e1..0000000000 --- a/plugins/Contents/tests/expected/test_ContentscontentNameOrPieceMatch__Contents.getContentPieces_day.xml +++ /dev/null @@ -1,48 +0,0 @@ - - - - - 4 - 4 - 4 - 2 - 50% - http://piwik.org/download - - - - 2 - 2 - 2 - 2 - 100% - http://www.example.com - - - - 2 - 2 - 2 - 0 - 0% - http://www.example.com - - - - 2 - 2 - 2 - 0 - 0% - - - - - 2 - 2 - 2 - 0 - 0% - - - \ No newline at end of file diff --git a/plugins/Contents/tests/expected/test_ContentscontentNameOrPieceMatch__Live.getLastVisitsDetails_day.xml b/plugins/Contents/tests/expected/test_ContentscontentNameOrPieceMatch__Live.getLastVisitsDetails_day.xml deleted file mode 100644 index 989f816722..0000000000 --- a/plugins/Contents/tests/expected/test_ContentscontentNameOrPieceMatch__Live.getLastVisitsDetails_day.xml +++ /dev/null @@ -1,199 +0,0 @@ - - - - 1 - 1 - 156.5.3.2 - - - - action - http://www.example.org/page - Ads - 2 - - 1 - 0.33s - 0 - 0s - - - - 0 - USD - $ - - - - - 0 - 1 - - new - - 0 - - 1 - - none - - 0 - 0 - 271 - 4 min 31s - - - Desktop - 0 - Unknown - Unknown - http://piwik.org/faq/general/#faq_52 - direct - Direct Entry - - - - - - - Europe - eur - France - fr - plugins/UserCountry/images/flags/fr.png - - - - France - - - Windows XP - WXP - Win XP - plugins/UserSettings/images/os/WXP.gif - gecko - Gecko (Firefox) - Firefox 3.6 - plugins/UserSettings/images/browsers/FF.gif - FF - 3.6 - normal - 1024x768 - plugins/UserSettings/images/screens/normal.gif - flash, java - - - plugins/UserSettings/images/plugins/flash.gif - flash - - - plugins/UserSettings/images/plugins/java.gif - java - - - 12:34:06 - 12 - 0 - - - - - - - - 1 - 2 - 111.1.1.1 - - - - action - http://www.example.org/page - Ads - 2 - - 13 - 0.33s - 0 - 0s - - - - 0 - USD - $ - - - - - 0 - 1 - - new - - 0 - - 1 - - none - - 0 - 0 - 271 - 4 min 31s - - - Desktop - 0 - Unknown - Unknown - http://piwik.org/faq/general/#faq_52 - direct - Direct Entry - - - - - - - Europe - eur - France - fr - plugins/UserCountry/images/flags/fr.png - - - - France - - - Windows XP - WXP - Win XP - plugins/UserSettings/images/os/WXP.gif - gecko - Gecko (Firefox) - Firefox 3.6 - plugins/UserSettings/images/browsers/FF.gif - FF - 3.6 - normal - 1024x768 - plugins/UserSettings/images/screens/normal.gif - director - - - plugins/UserSettings/images/plugins/director.gif - director - - - 12:34:06 - 12 - 0 - - - - - - - \ No newline at end of file diff --git a/plugins/Contents/tests/processed/.gitkeep b/plugins/Contents/tests/processed/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/plugins/CoreConsole/Commands/GenerateTest.php b/plugins/CoreConsole/Commands/GenerateTest.php index 5b80e389a6..6047f2ddc7 100644 --- a/plugins/CoreConsole/Commands/GenerateTest.php +++ b/plugins/CoreConsole/Commands/GenerateTest.php @@ -37,15 +37,9 @@ class GenerateTest extends GeneratePluginBase $replace = array( 'ExamplePlugin' => $pluginName, 'SimpleTest' => $testName, - 'SimpleSystemTest' => $testName, - '@group Plugins' => '@group ' . $testType + 'SimpleSystemTest' => $testName ); - $testClass = $this->getTestClass($testType); - if (!empty($testClass)) { - $replace['\PHPUnit_Framework_TestCase'] = $testClass; - } - $whitelistFiles = $this->getTestFilesWhitelist($testType); $this->copyTemplateToPlugin($exampleFolder, $pluginName, $replace, $whitelistFiles); @@ -112,23 +106,6 @@ class GenerateTest extends GeneratePluginBase return $this->askPluginNameAndValidate($input, $output, $pluginNames, $invalidName); } - /** - * @param $testType - * @return string - */ - private function getTestClass($testType) - { - if ('Integration' == $testType) { - return '\IntegrationTestCase'; - } - - if ('Unit' == $testType) { - return '\PHPUnit_Framework_TestCase'; - } - - return ''; - } - public function getValidTypes() { return array('unit', 'integration', 'system'); @@ -172,20 +149,31 @@ class GenerateTest extends GeneratePluginBase return array( '/.gitignore', '/tests', - '/tests/SimpleSystemTest.php', - '/tests/expected', - '/tests/expected/test___API.get_day.xml', - '/tests/expected/test___Goals.getItemsSku_day.xml', - '/tests/processed', - '/tests/processed/.gitignore', - '/tests/fixtures', - '/tests/fixtures/SimpleFixtureTrackFewVisits.php' + '/tests/System', + '/tests/System/SimpleSystemTest.php', + '/tests/System/expected', + '/tests/System/expected/test___API.get_day.xml', + '/tests/System/expected/test___Goals.getItemsSku_day.xml', + '/tests/System/processed', + '/tests/System/processed/.gitignore', + '/tests/Fixtures', + '/tests/Fixtures/SimpleFixtureTrackFewVisits.php' + ); + } + + if ('Integration' == $testType) { + + return array( + '/tests', + '/tests/Integration', + '/tests/Integration/SimpleTest.php' ); } return array( '/tests', - '/tests/SimpleTest.php' + '/tests/Unit', + '/tests/Unit/SimpleTest.php' ); } } diff --git a/plugins/CoreConsole/TravisYmlView.php b/plugins/CoreConsole/TravisYmlView.php index 9190f220ad..a89b5f1df5 100644 --- a/plugins/CoreConsole/TravisYmlView.php +++ b/plugins/CoreConsole/TravisYmlView.php @@ -199,16 +199,16 @@ class TravisYmlView extends View $testsToExclude = array(); if ($this->isTargetPluginContainsPluginTests()) { - $testsToRun[] = array('name' => 'IntegrationTests', + $testsToRun[] = array('name' => 'PluginTests', 'vars' => "MYSQL_ADAPTER=PDO_MYSQL"); - $testsToRun[] = array('name' => 'IntegrationTests', + $testsToRun[] = array('name' => 'PluginTests', 'vars' => "MYSQL_ADAPTER=PDO_MYSQL TEST_AGAINST_CORE=latest_stable"); $testsToExclude[] = array('description' => 'execute latest stable tests only w/ PHP 5.5', 'php' => '5.3.3', - 'env' => 'TEST_SUITE=IntegrationTests MYSQL_ADAPTER=PDO_MYSQL TEST_AGAINST_CORE=latest_stable'); + 'env' => 'TEST_SUITE=PluginTests MYSQL_ADAPTER=PDO_MYSQL TEST_AGAINST_CORE=latest_stable'); $testsToExclude[] = array('php' => '5.4', - 'env' => 'TEST_SUITE=IntegrationTests MYSQL_ADAPTER=PDO_MYSQL TEST_AGAINST_CORE=latest_stable'); + 'env' => 'TEST_SUITE=PluginTests MYSQL_ADAPTER=PDO_MYSQL TEST_AGAINST_CORE=latest_stable'); } if ($this->isTargetPluginContainsUITests()) { diff --git a/plugins/CoreConsole/tests/Integration/TravisYmlViewTest.php b/plugins/CoreConsole/tests/Integration/TravisYmlViewTest.php new file mode 100644 index 0000000000..f20e1c6d0f --- /dev/null +++ b/plugins/CoreConsole/tests/Integration/TravisYmlViewTest.php @@ -0,0 +1,165 @@ +loadPlugin('Morpheus'); + PluginManager::getInstance()->loadPlugin('CoreConsole'); + } + + public function testViewGeneratesCorrectLookingYAML() + { + $view = new TravisYmlView(); + $view->setPlugin('ExamplePlugin'); + $view->setExtraGlobalEnvVars(array('secure: artifactspass', 'secure: githubtoken')); + $view->setGenerateYmlCommand('./console generate:travis-yml \'arg1\' arg2'); + $output = $view->render(); + + $yaml = Spyc::YAMLLoadString($output); + + $this->assertNotEmpty($yaml['env']); + $this->assertNotEmpty($yaml['env']['global']); + $this->assertContains("PLUGIN_NAME=ExamplePlugin", $yaml['env']['global']); + $this->assertContains("PIWIK_ROOT_DIR=\$TRAVIS_BUILD_DIR/piwik", $yaml['env']['global']); + $this->assertContains(array('secure' => 'artifactspass'), $yaml['env']['global']); + $this->assertContains(array('secure' => 'githubtoken'), $yaml['env']['global']); + + $this->assertNotEmpty($yaml['env']['matrix']); + $this->assertContains("TEST_SUITE=IntegrationTests MYSQL_ADAPTER=PDO_MYSQL", $yaml['env']['matrix']); + $this->assertContains("TEST_SUITE=IntegrationTests MYSQL_ADAPTER=PDO_MYSQL TEST_AGAINST_CORE=latest_stable", $yaml['env']['matrix']); + $this->assertNotContains("TEST_SUITE=UITests MYSQL_ADAPTER=PDO_MYSQL", $yaml['env']['matrix']); + + $this->assertBuildSectionsNotEmpty($yaml); + + $this->assertContains("export GENERATE_TRAVIS_YML_COMMAND=\"./console generate:travis-yml \\'arg1\\' arg2\"", $yaml['before_script']); + + $this->assertViewUsesPluginSpecifiedTravisCommands($yaml); + } + + public function testViewPreservesCommentsAndEnvVarsIfExistingYml() + { + $view = new TravisYmlView(); + $view->setPlugin('ExamplePlugin'); + $view->setExtraGlobalEnvVars(array('secure: artifactspass', 'secure: githubtoken')); + $view->setGenerateYmlCommand('./console generate:travis-yml arg1 arg2'); + $view->processExistingTravisYml(PIWIK_INCLUDE_PATH . '/plugins/CoreConsole/tests/Integration/resources/test.travis.yml'); + $output = $view->render(); + + $yaml = Spyc::YAMLLoadString($output); + + $this->assertNotEmpty($yaml['env']); + $this->assertNotEmpty($yaml['env']['global']); + + $this->assertContains("PRESERVED_VAR=123", $yaml['env']['global']); + $this->assertContains(array('secure' => 'anotherpreservedvar'), $yaml['env']['global']); + $this->assertNotContains("PLUGIN_NAME=ExamplePlugin", $yaml['env']['global']); + $this->assertNotContains("PIWIK_ROOT_DIR=\$TRAVIS_BUILD_DIR/piwik", $yaml['env']['global']); + + $this->assertBuildSectionsNotEmpty($yaml); + + $this->assertNotEmpty($yaml['custom_section']); + $this->assertContains("custom_section:\n - this will be preserved\n # as should this", $output); + + $this->assertNotEmpty($yaml['notifications']); + $this->assertContains("notifications:\n # another section\n - a\n - b\n - c", $output); + + $this->assertViewUsesPluginSpecifiedTravisCommands($yaml); + } + + public function testViewGeneratesCorrectLookingYAMLForCore() + { + $view = new TravisYmlView(); + // no setPlugin call here signifies generating for core + $view->processExistingTravisYml(PIWIK_INCLUDE_PATH . '/.travis.yml'); + $view->setExtraGlobalEnvVars(array('secure: artifactspass', 'secure: githubtoken')); + $view->setGenerateYmlCommand('./console generate:travis-yml \'arg1\' arg2'); + $output = $view->render(); + + $yaml = Spyc::YAMLLoadString($output); + + $this->assertNotEmpty($yaml['env']); + $this->assertNotEmpty($yaml['env']['global']); + + $this->assertBuildSectionsNotEmpty($yaml); + + $this->assertViewDoesNotUsePluginSpecifiedTravisCommands($yaml); + } + + public function testViewGeneratesCorrectLookingYAMLWhenCustomPhpVersionsUsed() + { + $view = new TravisYmlView(); + $view->setPlugin('ExamplePlugin'); + $view->setPhpVersions(array('5.4', '5.6', 'hhvm')); + $view->setGenerateYmlCommand('./console generate:travis-yml arg1 arg2'); + $output = $view->render(); + + $yaml = Spyc::YAMLLoadString($output); + + $this->assertNotEmpty($yaml['php']); + $this->assertEquals(array('5.4', '5.6', 'hhvm'), $yaml['php']); + } + + private function assertBuildSectionsNotEmpty($yaml) + { + $this->assertNotEmpty($yaml['before_install']); + $this->assertNotEmpty($yaml['install']); + $this->assertNotEmpty($yaml['before_script']); + $this->assertNotEmpty($yaml['after_script']); + $this->assertNotEmpty($yaml['after_success']); + } + + private function assertViewUsesPluginSpecifiedTravisCommands($yaml) + { + $this->assertEquals("before_install hook line 1", reset($yaml['before_install'])); + $this->assertEquals("before_install hook line 2", end($yaml['before_install'])); + + $this->assertEquals("before_script hook line 1", reset($yaml['before_script'])); + $this->assertEquals("before_script hook line 2", end($yaml['before_script'])); + + $this->assertEquals("install hook line 1", reset($yaml['install'])); + $this->assertEquals("install hook line 2", end($yaml['install'])); + + $this->assertEquals("after_success hook line 1", reset($yaml['after_success'])); + $this->assertEquals("after_success hook line 2", end($yaml['after_success'])); + + $this->assertEquals("after_script hook line 1", reset($yaml['after_script'])); + $this->assertEquals("after_script hook line 2", end($yaml['after_script'])); + } + + private function assertViewDoesNotUsePluginSpecifiedTravisCommands($yaml) + { + $this->assertNotEquals("before_install hook line 1", reset($yaml['before_install'])); + $this->assertNotEquals("before_install hook line 2", end($yaml['before_install'])); + + $this->assertNotEquals("before_script hook line 1", reset($yaml['before_script'])); + $this->assertNotEquals("before_script hook line 2", end($yaml['before_script'])); + + $this->assertNotEquals("install hook line 1", reset($yaml['install'])); + $this->assertNotEquals("install hook line 2", end($yaml['install'])); + + $this->assertNotEquals("after_success hook line 1", reset($yaml['after_success'])); + $this->assertNotEquals("after_success hook line 2", end($yaml['after_success'])); + + $this->assertNotEquals("after_script hook line 1", reset($yaml['after_script'])); + $this->assertNotEquals("after_script hook line 2", end($yaml['after_script'])); + } +} \ No newline at end of file diff --git a/plugins/CoreConsole/tests/Integration/resources/test.travis.yml b/plugins/CoreConsole/tests/Integration/resources/test.travis.yml new file mode 100644 index 0000000000..3d469b75ff --- /dev/null +++ b/plugins/CoreConsole/tests/Integration/resources/test.travis.yml @@ -0,0 +1,55 @@ +language: php + +php: + - 5.3 + +env: + global: + - PRESERVED_VAR=123 + - secure: anotherpreservedvar + matrix: + - TEST_SUITE=UnitTests MYSQL_ADAPTER=PDO_MYSQL + - TEST_SUITE=IntegrationTests MYSQL_ADAPTER=PDO_MYSQL + +script: ./travis.sh + +install: + - TEST_PIWIK_VERSION=$(wget builds.piwik.org/LATEST -q -O -) + - TEST_PIWIK_VERSION=`echo $TEST_PIWIK_VERSION | tr -d ' ' | tr -d '\n'` + - mkdir ExamplePlugin + - cp -R !(ExamplePlugin) ExamplePlugin + - cp -R .git/ ExamplePlugin/ + - git clone https://github.com/piwik/piwik.git piwik + - cd piwik + - git checkout "$TEST_PIWIK_VERSION" + - git submodule init + - git submodule update || true + - composer self-update + - composer install + - rm -rf plugins/ExamplePlugin + - cd ../ + - mv ExamplePlugin piwik/plugins + +before_script: + - cd piwik + - uname -a + - date + - mysql -e 'create database piwik_tests;' + - ./tests/travis/prepare.sh + - ./tests/travis/setup_webserver.sh + - wget https://raw.github.com/piwik/piwik-tests-plugins/master/activateplugin.php + - php activateplugin.php ExamplePlugin + - cd tests/PHPUnit + +custom_section: + - this will be preserved + # as should this + +after_script: + - cat /var/log/nginx/error.log + +notifications: + # another section + - a + - b + - c diff --git a/plugins/CoreConsole/tests/Unit/TravisYmlViewTest.php b/plugins/CoreConsole/tests/Unit/TravisYmlViewTest.php deleted file mode 100644 index b35819c7f0..0000000000 --- a/plugins/CoreConsole/tests/Unit/TravisYmlViewTest.php +++ /dev/null @@ -1,165 +0,0 @@ -loadPlugin('Morpheus'); - PluginManager::getInstance()->loadPlugin('CoreConsole'); - } - - public function testViewGeneratesCorrectLookingYAML() - { - $view = new TravisYmlView(); - $view->setPlugin('ExamplePlugin'); - $view->setExtraGlobalEnvVars(array('secure: artifactspass', 'secure: githubtoken')); - $view->setGenerateYmlCommand('./console generate:travis-yml \'arg1\' arg2'); - $output = $view->render(); - - $yaml = Spyc::YAMLLoadString($output); - - $this->assertNotEmpty($yaml['env']); - $this->assertNotEmpty($yaml['env']['global']); - $this->assertContains("PLUGIN_NAME=ExamplePlugin", $yaml['env']['global']); - $this->assertContains("PIWIK_ROOT_DIR=\$TRAVIS_BUILD_DIR/piwik", $yaml['env']['global']); - $this->assertContains(array('secure' => 'artifactspass'), $yaml['env']['global']); - $this->assertContains(array('secure' => 'githubtoken'), $yaml['env']['global']); - - $this->assertNotEmpty($yaml['env']['matrix']); - $this->assertContains("TEST_SUITE=IntegrationTests MYSQL_ADAPTER=PDO_MYSQL", $yaml['env']['matrix']); - $this->assertContains("TEST_SUITE=IntegrationTests MYSQL_ADAPTER=PDO_MYSQL TEST_AGAINST_CORE=latest_stable", $yaml['env']['matrix']); - $this->assertNotContains("TEST_SUITE=UITests MYSQL_ADAPTER=PDO_MYSQL", $yaml['env']['matrix']); - - $this->assertBuildSectionsNotEmpty($yaml); - - $this->assertContains("export GENERATE_TRAVIS_YML_COMMAND=\"./console generate:travis-yml \\'arg1\\' arg2\"", $yaml['before_script']); - - $this->assertViewUsesPluginSpecifiedTravisCommands($yaml); - } - - public function testViewPreservesCommentsAndEnvVarsIfExistingYml() - { - $view = new TravisYmlView(); - $view->setPlugin('ExamplePlugin'); - $view->setExtraGlobalEnvVars(array('secure: artifactspass', 'secure: githubtoken')); - $view->setGenerateYmlCommand('./console generate:travis-yml arg1 arg2'); - $view->processExistingTravisYml(PIWIK_INCLUDE_PATH . '/plugins/CoreConsole/tests/resources/test.travis.yml'); - $output = $view->render(); - - $yaml = Spyc::YAMLLoadString($output); - - $this->assertNotEmpty($yaml['env']); - $this->assertNotEmpty($yaml['env']['global']); - - $this->assertContains("PRESERVED_VAR=123", $yaml['env']['global']); - $this->assertContains(array('secure' => 'anotherpreservedvar'), $yaml['env']['global']); - $this->assertNotContains("PLUGIN_NAME=ExamplePlugin", $yaml['env']['global']); - $this->assertNotContains("PIWIK_ROOT_DIR=\$TRAVIS_BUILD_DIR/piwik", $yaml['env']['global']); - - $this->assertBuildSectionsNotEmpty($yaml); - - $this->assertNotEmpty($yaml['custom_section']); - $this->assertContains("custom_section:\n - this will be preserved\n # as should this", $output); - - $this->assertNotEmpty($yaml['notifications']); - $this->assertContains("notifications:\n # another section\n - a\n - b\n - c", $output); - - $this->assertViewUsesPluginSpecifiedTravisCommands($yaml); - } - - public function testViewGeneratesCorrectLookingYAMLForCore() - { - $view = new TravisYmlView(); - // no setPlugin call here signifies generating for core - $view->processExistingTravisYml(PIWIK_INCLUDE_PATH . '/.travis.yml'); - $view->setExtraGlobalEnvVars(array('secure: artifactspass', 'secure: githubtoken')); - $view->setGenerateYmlCommand('./console generate:travis-yml \'arg1\' arg2'); - $output = $view->render(); - - $yaml = Spyc::YAMLLoadString($output); - - $this->assertNotEmpty($yaml['env']); - $this->assertNotEmpty($yaml['env']['global']); - - $this->assertBuildSectionsNotEmpty($yaml); - - $this->assertViewDoesNotUsePluginSpecifiedTravisCommands($yaml); - } - - public function testViewGeneratesCorrectLookingYAMLWhenCustomPhpVersionsUsed() - { - $view = new TravisYmlView(); - $view->setPlugin('ExamplePlugin'); - $view->setPhpVersions(array('5.4', '5.6', 'hhvm')); - $view->setGenerateYmlCommand('./console generate:travis-yml arg1 arg2'); - $output = $view->render(); - - $yaml = Spyc::YAMLLoadString($output); - - $this->assertNotEmpty($yaml['php']); - $this->assertEquals(array('5.4', '5.6', 'hhvm'), $yaml['php']); - } - - private function assertBuildSectionsNotEmpty($yaml) - { - $this->assertNotEmpty($yaml['before_install']); - $this->assertNotEmpty($yaml['install']); - $this->assertNotEmpty($yaml['before_script']); - $this->assertNotEmpty($yaml['after_script']); - $this->assertNotEmpty($yaml['after_success']); - } - - private function assertViewUsesPluginSpecifiedTravisCommands($yaml) - { - $this->assertEquals("before_install hook line 1", reset($yaml['before_install'])); - $this->assertEquals("before_install hook line 2", end($yaml['before_install'])); - - $this->assertEquals("before_script hook line 1", reset($yaml['before_script'])); - $this->assertEquals("before_script hook line 2", end($yaml['before_script'])); - - $this->assertEquals("install hook line 1", reset($yaml['install'])); - $this->assertEquals("install hook line 2", end($yaml['install'])); - - $this->assertEquals("after_success hook line 1", reset($yaml['after_success'])); - $this->assertEquals("after_success hook line 2", end($yaml['after_success'])); - - $this->assertEquals("after_script hook line 1", reset($yaml['after_script'])); - $this->assertEquals("after_script hook line 2", end($yaml['after_script'])); - } - - private function assertViewDoesNotUsePluginSpecifiedTravisCommands($yaml) - { - $this->assertNotEquals("before_install hook line 1", reset($yaml['before_install'])); - $this->assertNotEquals("before_install hook line 2", end($yaml['before_install'])); - - $this->assertNotEquals("before_script hook line 1", reset($yaml['before_script'])); - $this->assertNotEquals("before_script hook line 2", end($yaml['before_script'])); - - $this->assertNotEquals("install hook line 1", reset($yaml['install'])); - $this->assertNotEquals("install hook line 2", end($yaml['install'])); - - $this->assertNotEquals("after_success hook line 1", reset($yaml['after_success'])); - $this->assertNotEquals("after_success hook line 2", end($yaml['after_success'])); - - $this->assertNotEquals("after_script hook line 1", reset($yaml['after_script'])); - $this->assertNotEquals("after_script hook line 2", end($yaml['after_script'])); - } -} \ No newline at end of file diff --git a/plugins/CoreConsole/tests/resources/test.travis.yml b/plugins/CoreConsole/tests/resources/test.travis.yml deleted file mode 100644 index 3d469b75ff..0000000000 --- a/plugins/CoreConsole/tests/resources/test.travis.yml +++ /dev/null @@ -1,55 +0,0 @@ -language: php - -php: - - 5.3 - -env: - global: - - PRESERVED_VAR=123 - - secure: anotherpreservedvar - matrix: - - TEST_SUITE=UnitTests MYSQL_ADAPTER=PDO_MYSQL - - TEST_SUITE=IntegrationTests MYSQL_ADAPTER=PDO_MYSQL - -script: ./travis.sh - -install: - - TEST_PIWIK_VERSION=$(wget builds.piwik.org/LATEST -q -O -) - - TEST_PIWIK_VERSION=`echo $TEST_PIWIK_VERSION | tr -d ' ' | tr -d '\n'` - - mkdir ExamplePlugin - - cp -R !(ExamplePlugin) ExamplePlugin - - cp -R .git/ ExamplePlugin/ - - git clone https://github.com/piwik/piwik.git piwik - - cd piwik - - git checkout "$TEST_PIWIK_VERSION" - - git submodule init - - git submodule update || true - - composer self-update - - composer install - - rm -rf plugins/ExamplePlugin - - cd ../ - - mv ExamplePlugin piwik/plugins - -before_script: - - cd piwik - - uname -a - - date - - mysql -e 'create database piwik_tests;' - - ./tests/travis/prepare.sh - - ./tests/travis/setup_webserver.sh - - wget https://raw.github.com/piwik/piwik-tests-plugins/master/activateplugin.php - - php activateplugin.php ExamplePlugin - - cd tests/PHPUnit - -custom_section: - - this will be preserved - # as should this - -after_script: - - cat /var/log/nginx/error.log - -notifications: - # another section - - a - - b - - c diff --git a/plugins/CorePluginsAdmin/tests/Integration/UpdateCommunicationTest.php b/plugins/CorePluginsAdmin/tests/Integration/UpdateCommunicationTest.php new file mode 100644 index 0000000000..c57a3e0058 --- /dev/null +++ b/plugins/CorePluginsAdmin/tests/Integration/UpdateCommunicationTest.php @@ -0,0 +1,185 @@ +updateCommunication = new UpdateCommunication(); + $this->updateCommunication->enable(); + } + + public function test_canBeEnabled() + { + $this->assertTrue($this->updateCommunication->canBeEnabled()); + + Config::getInstance()->General['enable_update_communication'] = 0; + $this->assertFalse($this->updateCommunication->canBeEnabled()); + + Config::getInstance()->General['enable_update_communication'] = 1; + $this->assertTrue($this->updateCommunication->canBeEnabled()); + } + + public function test_enable() + { + $this->updateCommunication->enable(); + $this->assertTrue($this->updateCommunication->isEnabled()); + } + + public function test_disable() + { + $this->assertTrue($this->updateCommunication->isEnabled()); + + $this->updateCommunication->disable(); + $this->assertFalse($this->updateCommunication->isEnabled()); + } + + public function test_isEnabled_shouldReturnFalse_IfCannotBeEnabled() + { + $this->assertTrue($this->updateCommunication->isEnabled()); + + Config::getInstance()->General['enable_update_communication'] = 0; + $this->assertFalse($this->updateCommunication->isEnabled()); + } + + public function test_sendNotificationIfUpdatesAvailable_shouldNotSendNotification_IfNoUpdateAvailable() + { + $mock = $this->getCommunicationMock(array()); + $mock->expects($this->never())->method('sendEmailNotification'); + $mock->sendNotificationIfUpdatesAvailable(); + } + + /** + * @dataProvider provideSendNotificationData + */ + public function test_sendNotificationIfUpdatesAvailable($latestVersion, $lastSentVersion, $expects, $expectedLastSentVersion) + { + $pluginsHavingUpdate = array( + array('name' => 'MyTest', 'latestVersion' => $latestVersion, 'isTheme' => false) + ); + $this->setLastSentVersion('MyTest', $lastSentVersion); + + $mock = $this->getCommunicationMock($pluginsHavingUpdate); + $mock->expects($expects)->method('sendEmailNotification'); + $mock->sendNotificationIfUpdatesAvailable(); + + $this->assertEquals($expectedLastSentVersion, $this->getLastSentVersion('MyTest')); + } + + public function provideSendNotificationData() + { + return array( + array('33.0.0', '33.0.0', $this->never(), '33.0.0'), // shouldNotSend_IfAlreadyNotified + array('31.0.0', '33.0.0', $this->never(), '33.0.0'), // shouldNotSend_IfAlreadyNotifiedAboutLaterRelease + array('33.0.0', false, $this->once(), '33.0.0'), // shouldSend_IfUpdateAvailableAndNeverSentAnyBefore + array('33.0.0', '31.0.0', $this->once(), '33.0.0'), // shouldSend_IfUpdateAvailable, + ); + } + + public function test_sendNotificationIfUpdatesAvailable_ShouldSendOnlyOneEmail_IfMultipleUpdatesAreAvailable() + { + $mock = $this->getCommunicationMockHavingManyUpdates(); + $mock->expects($this->once())->method('sendEmailNotification'); + $mock->sendNotificationIfUpdatesAvailable(); + } + + public function test_sendNotificationIfUpdatesAvailable_ShouldUpdateAllSentVersions_IfMultipleUpdatesAreAvailable() + { + $mock = $this->getCommunicationMockHavingManyUpdates(); + $mock->expects($this->once())->method('sendEmailNotification'); + $mock->sendNotificationIfUpdatesAvailable(); + + $this->assertEquals('33.0.0', $this->getLastSentVersion('MyTest1')); + $this->assertEquals('32.0.0', $this->getLastSentVersion('MyTest2')); + $this->assertEquals('31.0.0', $this->getLastSentVersion('MyTest3')); + } + + public function test_sendNotificationIfUpdatesAvailable_ShouldSendCorrectText() + { + $subject = 'CoreUpdater_NotificationSubjectAvailablePluginUpdate'; + $message = 'ScheduledReports_EmailHello + +CoreUpdater_ThereIsNewPluginVersionAvailableForUpdate + + * MyTest1 33.0.0 + * MyTest2 32.0.0 + * MyTest3 31.0.0 + +CoreUpdater_NotificationClickToUpdatePlugins +index.php?module=CorePluginsAdmin&action=plugins + +Installation_HappyAnalysing'; + + $mock = $this->getCommunicationMockHavingManyUpdates(); + + $mock->expects($this->once())->method('sendEmailNotification') + ->with($this->equalTo($subject), $this->equalTo($message)); + + $mock->sendNotificationIfUpdatesAvailable(); + } + + private function setLastSentVersion($pluginName, $version) + { + Option::set('last_update_communication_sent_plugin_' . $pluginName, $version); + } + + private function getLastSentVersion($pluginName) + { + return Option::get('last_update_communication_sent_plugin_' . $pluginName); + } + + /** + * @param array $pluginsHavingUpdate + * @return UpdateCommunication + */ + private function getCommunicationMock($pluginsHavingUpdate) + { + $mock = $this->getMock('\Piwik\Plugins\CorePluginsAdmin\UpdateCommunication', array('getPluginsHavingUpdate', 'sendEmailNotification')); + + $mock->expects($this->any()) + ->method('getPluginsHavingUpdate') + ->will($this->returnValue($pluginsHavingUpdate)); + + return $mock; + } + + private function getCommunicationMockHavingManyUpdates() + { + $pluginsHavingUpdate = array( + array('name' => 'MyTest1', 'latestVersion' => '33.0.0', 'isTheme' => false), + array('name' => 'MyTest2', 'latestVersion' => '32.0.0', 'isTheme' => false), + array('name' => 'MyTest3', 'latestVersion' => '31.0.0', 'isTheme' => false), + ); + + $this->setLastSentVersion('MyTest1', false); + $this->setLastSentVersion('MyTest2', false); + $this->setLastSentVersion('MyTest3', false); + + $mock = $this->getCommunicationMock($pluginsHavingUpdate); + + return $mock; + } +} diff --git a/plugins/CorePluginsAdmin/tests/UpdateCommunicationTest.php b/plugins/CorePluginsAdmin/tests/UpdateCommunicationTest.php deleted file mode 100644 index 8da5e00928..0000000000 --- a/plugins/CorePluginsAdmin/tests/UpdateCommunicationTest.php +++ /dev/null @@ -1,185 +0,0 @@ -updateCommunication = new UpdateCommunication(); - $this->updateCommunication->enable(); - } - - public function test_canBeEnabled() - { - $this->assertTrue($this->updateCommunication->canBeEnabled()); - - Config::getInstance()->General['enable_update_communication'] = 0; - $this->assertFalse($this->updateCommunication->canBeEnabled()); - - Config::getInstance()->General['enable_update_communication'] = 1; - $this->assertTrue($this->updateCommunication->canBeEnabled()); - } - - public function test_enable() - { - $this->updateCommunication->enable(); - $this->assertTrue($this->updateCommunication->isEnabled()); - } - - public function test_disable() - { - $this->assertTrue($this->updateCommunication->isEnabled()); - - $this->updateCommunication->disable(); - $this->assertFalse($this->updateCommunication->isEnabled()); - } - - public function test_isEnabled_shouldReturnFalse_IfCannotBeEnabled() - { - $this->assertTrue($this->updateCommunication->isEnabled()); - - Config::getInstance()->General['enable_update_communication'] = 0; - $this->assertFalse($this->updateCommunication->isEnabled()); - } - - public function test_sendNotificationIfUpdatesAvailable_shouldNotSendNotification_IfNoUpdateAvailable() - { - $mock = $this->getCommunicationMock(array()); - $mock->expects($this->never())->method('sendEmailNotification'); - $mock->sendNotificationIfUpdatesAvailable(); - } - - /** - * @dataProvider provideSendNotificationData - */ - public function test_sendNotificationIfUpdatesAvailable($latestVersion, $lastSentVersion, $expects, $expectedLastSentVersion) - { - $pluginsHavingUpdate = array( - array('name' => 'MyTest', 'latestVersion' => $latestVersion, 'isTheme' => false) - ); - $this->setLastSentVersion('MyTest', $lastSentVersion); - - $mock = $this->getCommunicationMock($pluginsHavingUpdate); - $mock->expects($expects)->method('sendEmailNotification'); - $mock->sendNotificationIfUpdatesAvailable(); - - $this->assertEquals($expectedLastSentVersion, $this->getLastSentVersion('MyTest')); - } - - public function provideSendNotificationData() - { - return array( - array('33.0.0', '33.0.0', $this->never(), '33.0.0'), // shouldNotSend_IfAlreadyNotified - array('31.0.0', '33.0.0', $this->never(), '33.0.0'), // shouldNotSend_IfAlreadyNotifiedAboutLaterRelease - array('33.0.0', false, $this->once(), '33.0.0'), // shouldSend_IfUpdateAvailableAndNeverSentAnyBefore - array('33.0.0', '31.0.0', $this->once(), '33.0.0'), // shouldSend_IfUpdateAvailable, - ); - } - - public function test_sendNotificationIfUpdatesAvailable_ShouldSendOnlyOneEmail_IfMultipleUpdatesAreAvailable() - { - $mock = $this->getCommunicationMockHavingManyUpdates(); - $mock->expects($this->once())->method('sendEmailNotification'); - $mock->sendNotificationIfUpdatesAvailable(); - } - - public function test_sendNotificationIfUpdatesAvailable_ShouldUpdateAllSentVersions_IfMultipleUpdatesAreAvailable() - { - $mock = $this->getCommunicationMockHavingManyUpdates(); - $mock->expects($this->once())->method('sendEmailNotification'); - $mock->sendNotificationIfUpdatesAvailable(); - - $this->assertEquals('33.0.0', $this->getLastSentVersion('MyTest1')); - $this->assertEquals('32.0.0', $this->getLastSentVersion('MyTest2')); - $this->assertEquals('31.0.0', $this->getLastSentVersion('MyTest3')); - } - - public function test_sendNotificationIfUpdatesAvailable_ShouldSendCorrectText() - { - $subject = 'CoreUpdater_NotificationSubjectAvailablePluginUpdate'; - $message = 'ScheduledReports_EmailHello - -CoreUpdater_ThereIsNewPluginVersionAvailableForUpdate - - * MyTest1 33.0.0 - * MyTest2 32.0.0 - * MyTest3 31.0.0 - -CoreUpdater_NotificationClickToUpdatePlugins -index.php?module=CorePluginsAdmin&action=plugins - -Installation_HappyAnalysing'; - - $mock = $this->getCommunicationMockHavingManyUpdates(); - - $mock->expects($this->once())->method('sendEmailNotification') - ->with($this->equalTo($subject), $this->equalTo($message)); - - $mock->sendNotificationIfUpdatesAvailable(); - } - - private function setLastSentVersion($pluginName, $version) - { - Option::set('last_update_communication_sent_plugin_' . $pluginName, $version); - } - - private function getLastSentVersion($pluginName) - { - return Option::get('last_update_communication_sent_plugin_' . $pluginName); - } - - /** - * @param array $pluginsHavingUpdate - * @return UpdateCommunication - */ - private function getCommunicationMock($pluginsHavingUpdate) - { - $mock = $this->getMock('\Piwik\Plugins\CorePluginsAdmin\UpdateCommunication', array('getPluginsHavingUpdate', 'sendEmailNotification')); - - $mock->expects($this->any()) - ->method('getPluginsHavingUpdate') - ->will($this->returnValue($pluginsHavingUpdate)); - - return $mock; - } - - private function getCommunicationMockHavingManyUpdates() - { - $pluginsHavingUpdate = array( - array('name' => 'MyTest1', 'latestVersion' => '33.0.0', 'isTheme' => false), - array('name' => 'MyTest2', 'latestVersion' => '32.0.0', 'isTheme' => false), - array('name' => 'MyTest3', 'latestVersion' => '31.0.0', 'isTheme' => false), - ); - - $this->setLastSentVersion('MyTest1', false); - $this->setLastSentVersion('MyTest2', false); - $this->setLastSentVersion('MyTest3', false); - - $mock = $this->getCommunicationMock($pluginsHavingUpdate); - - return $mock; - } -} diff --git a/plugins/CoreUpdater/tests/Integration/UpdateCommunicationTest.php b/plugins/CoreUpdater/tests/Integration/UpdateCommunicationTest.php new file mode 100644 index 0000000000..d4ee8932c9 --- /dev/null +++ b/plugins/CoreUpdater/tests/Integration/UpdateCommunicationTest.php @@ -0,0 +1,121 @@ +assertTrue($updateCommunication->isEnabled()); + + Config::getInstance()->General['enable_update_communication'] = 0; + $this->assertFalse($updateCommunication->isEnabled()); + + Config::getInstance()->General['enable_update_communication'] = 1; + $this->assertTrue($updateCommunication->isEnabled()); + } + + /** + * @dataProvider provideSendNotificationData + */ + public function test_sendNotificationIfUpdateAvailable($latestVersion, $lastSentVersion, $expects, $expectedLastSentVersion) + { + $this->setLatestVersion($latestVersion); + $this->setLastSentVersion($lastSentVersion); + + $mock = $this->getCommunicationMock(array('sendNotifications')); + $mock->expects($expects)->method('sendNotifications'); + $mock->sendNotificationIfUpdateAvailable(); + + $this->assertEquals($expectedLastSentVersion, $this->getLastSentVersion()); + } + + public function provideSendNotificationData() + { + return array( + array(Version::VERSION, false, $this->never(), false), // shouldNotSend_IfNoUpdateAvailable + array('33.0.0', '33.0.0', $this->never(), '33.0.0'), // shouldNotSend_IfAlreadyNotified + array('31.0.0', '33.0.0', $this->never(), '33.0.0'), // shouldNotSend_IfAlreadyNotifiedAboutLaterRelease + array('3333.3333.3333-beta10', '31.0.0', $this->never(), '31.0.0'), // shouldNotSend_IfLatestVersionIsNotVersionLike, + array('33.0.0', false, $this->once(), '33.0.0'), // shouldSend_IfUpdateAvailableAndNeverSentAnyBefore + array('33.0.0', '31.0.0', $this->once(), '33.0.0'), // shouldSend_IfUpdateAvailable + ); + } + + public function test_sendNotifications_shouldSentCorrectEmail() + { + $this->setLatestVersion('33.0.0'); + + $subject = 'CoreUpdater_NotificationSubjectAvailableCoreUpdate'; + $message = 'ScheduledReports_EmailHello + +CoreUpdater_ThereIsNewVersionAvailableForUpdate + +CoreUpdater_YouCanUpgradeAutomaticallyOrDownloadPackage + +index.php?module=CoreUpdater&action=newVersionAvailable + +CoreUpdater_FeedbackRequest +http://piwik.org/contact/'; + + $mock = $this->getCommunicationMock(array('sendEmailNotification')); + $mock->expects($this->once()) + ->method('sendEmailNotification') + ->with($this->equalTo($subject), $this->equalTo($message)); + $mock->sendNotificationIfUpdateAvailable(); + } + + private function setLastSentVersion($value) + { + Option::set('last_update_communication_sent_core', $value); + } + + private function getLastSentVersion() + { + return Option::get('last_update_communication_sent_core'); + } + + private function setLatestVersion($value) + { + $this->preventVersionIsOverwrittenByActualVersionCheck(); + Option::set(UpdateCheck::LATEST_VERSION, $value); + } + + private function preventVersionIsOverwrittenByActualVersionCheck() + { + Config::getInstance()->General['enable_auto_update'] = false; + } + + /** + * @param array $methodsToOverwrite + * @return UpdateCommunication + */ + private function getCommunicationMock($methodsToOverwrite) + { + return $this->getMock('\Piwik\Plugins\CoreUpdater\UpdateCommunication', $methodsToOverwrite); + } +} diff --git a/plugins/CoreUpdater/tests/ModelTest.php b/plugins/CoreUpdater/tests/ModelTest.php deleted file mode 100644 index 3098595b77..0000000000 --- a/plugins/CoreUpdater/tests/ModelTest.php +++ /dev/null @@ -1,60 +0,0 @@ -model = new Model(); - } - - public function test_getPluginsFromDirectoy_shouldReturnEmptyArray_IfNoPluginsExist() - { - $plugins = $this->model->getPluginsFromDirectoy(PIWIK_INCLUDE_PATH . '/config'); - - $this->assertEquals(array(), $plugins); - } - - public function test_getPluginsFromDirectoy_shouldReturnAllDirectoriesWithinPlugins() - { - $plugins = $this->model->getPluginsFromDirectoy(PIWIK_INCLUDE_PATH); - - $this->assertGreaterThan(40, count($plugins)); - $this->assertContains('/plugins/API', $plugins); - $this->assertContains('/plugins/Actions', $plugins); - $this->assertContains('/plugins/Annotations', $plugins); - - $this->assertNotContains('/plugins/.', $plugins); - $this->assertNotContains('/plugins/..', $plugins); - $this->assertNotContains('/plugins', $plugins); - $this->assertNotContains('/plugins/', $plugins); - - foreach ($plugins as $plugin) { - $this->assertTrue(is_dir(PIWIK_INCLUDE_PATH . $plugin)); - $this->assertStringStartsWith('/plugins/', $plugin); - $this->assertTrue(12 <= strlen($plugin)); // make sure it does not return something like '/plugins'. - } - } - -} diff --git a/plugins/CoreUpdater/tests/Unit/ModelTest.php b/plugins/CoreUpdater/tests/Unit/ModelTest.php new file mode 100644 index 0000000000..3098595b77 --- /dev/null +++ b/plugins/CoreUpdater/tests/Unit/ModelTest.php @@ -0,0 +1,60 @@ +model = new Model(); + } + + public function test_getPluginsFromDirectoy_shouldReturnEmptyArray_IfNoPluginsExist() + { + $plugins = $this->model->getPluginsFromDirectoy(PIWIK_INCLUDE_PATH . '/config'); + + $this->assertEquals(array(), $plugins); + } + + public function test_getPluginsFromDirectoy_shouldReturnAllDirectoriesWithinPlugins() + { + $plugins = $this->model->getPluginsFromDirectoy(PIWIK_INCLUDE_PATH); + + $this->assertGreaterThan(40, count($plugins)); + $this->assertContains('/plugins/API', $plugins); + $this->assertContains('/plugins/Actions', $plugins); + $this->assertContains('/plugins/Annotations', $plugins); + + $this->assertNotContains('/plugins/.', $plugins); + $this->assertNotContains('/plugins/..', $plugins); + $this->assertNotContains('/plugins', $plugins); + $this->assertNotContains('/plugins/', $plugins); + + foreach ($plugins as $plugin) { + $this->assertTrue(is_dir(PIWIK_INCLUDE_PATH . $plugin)); + $this->assertStringStartsWith('/plugins/', $plugin); + $this->assertTrue(12 <= strlen($plugin)); // make sure it does not return something like '/plugins'. + } + } + +} diff --git a/plugins/CoreUpdater/tests/UpdateCommunicationTest.php b/plugins/CoreUpdater/tests/UpdateCommunicationTest.php deleted file mode 100644 index d4ee8932c9..0000000000 --- a/plugins/CoreUpdater/tests/UpdateCommunicationTest.php +++ /dev/null @@ -1,121 +0,0 @@ -assertTrue($updateCommunication->isEnabled()); - - Config::getInstance()->General['enable_update_communication'] = 0; - $this->assertFalse($updateCommunication->isEnabled()); - - Config::getInstance()->General['enable_update_communication'] = 1; - $this->assertTrue($updateCommunication->isEnabled()); - } - - /** - * @dataProvider provideSendNotificationData - */ - public function test_sendNotificationIfUpdateAvailable($latestVersion, $lastSentVersion, $expects, $expectedLastSentVersion) - { - $this->setLatestVersion($latestVersion); - $this->setLastSentVersion($lastSentVersion); - - $mock = $this->getCommunicationMock(array('sendNotifications')); - $mock->expects($expects)->method('sendNotifications'); - $mock->sendNotificationIfUpdateAvailable(); - - $this->assertEquals($expectedLastSentVersion, $this->getLastSentVersion()); - } - - public function provideSendNotificationData() - { - return array( - array(Version::VERSION, false, $this->never(), false), // shouldNotSend_IfNoUpdateAvailable - array('33.0.0', '33.0.0', $this->never(), '33.0.0'), // shouldNotSend_IfAlreadyNotified - array('31.0.0', '33.0.0', $this->never(), '33.0.0'), // shouldNotSend_IfAlreadyNotifiedAboutLaterRelease - array('3333.3333.3333-beta10', '31.0.0', $this->never(), '31.0.0'), // shouldNotSend_IfLatestVersionIsNotVersionLike, - array('33.0.0', false, $this->once(), '33.0.0'), // shouldSend_IfUpdateAvailableAndNeverSentAnyBefore - array('33.0.0', '31.0.0', $this->once(), '33.0.0'), // shouldSend_IfUpdateAvailable - ); - } - - public function test_sendNotifications_shouldSentCorrectEmail() - { - $this->setLatestVersion('33.0.0'); - - $subject = 'CoreUpdater_NotificationSubjectAvailableCoreUpdate'; - $message = 'ScheduledReports_EmailHello - -CoreUpdater_ThereIsNewVersionAvailableForUpdate - -CoreUpdater_YouCanUpgradeAutomaticallyOrDownloadPackage - -index.php?module=CoreUpdater&action=newVersionAvailable - -CoreUpdater_FeedbackRequest -http://piwik.org/contact/'; - - $mock = $this->getCommunicationMock(array('sendEmailNotification')); - $mock->expects($this->once()) - ->method('sendEmailNotification') - ->with($this->equalTo($subject), $this->equalTo($message)); - $mock->sendNotificationIfUpdateAvailable(); - } - - private function setLastSentVersion($value) - { - Option::set('last_update_communication_sent_core', $value); - } - - private function getLastSentVersion() - { - return Option::get('last_update_communication_sent_core'); - } - - private function setLatestVersion($value) - { - $this->preventVersionIsOverwrittenByActualVersionCheck(); - Option::set(UpdateCheck::LATEST_VERSION, $value); - } - - private function preventVersionIsOverwrittenByActualVersionCheck() - { - Config::getInstance()->General['enable_auto_update'] = false; - } - - /** - * @param array $methodsToOverwrite - * @return UpdateCommunication - */ - private function getCommunicationMock($methodsToOverwrite) - { - return $this->getMock('\Piwik\Plugins\CoreUpdater\UpdateCommunication', $methodsToOverwrite); - } -} diff --git a/plugins/CustomVariables/.gitignore b/plugins/CustomVariables/.gitignore new file mode 100644 index 0000000000..c8c9480010 --- /dev/null +++ b/plugins/CustomVariables/.gitignore @@ -0,0 +1 @@ +tests/System/processed/*xml \ No newline at end of file diff --git a/plugins/CustomVariables/tests/CustomVariablesSystemTest.php b/plugins/CustomVariables/tests/CustomVariablesSystemTest.php deleted file mode 100644 index 1bcdf9f838..0000000000 --- a/plugins/CustomVariables/tests/CustomVariablesSystemTest.php +++ /dev/null @@ -1,60 +0,0 @@ -runApiTests($api, $params); - } - - public function getApiForTesting() - { - $apiToCall = array('CustomVariables.getCustomVariables', 'Live.getLastVisitsDetails'); - - return array( - array($apiToCall, array( - 'idSite' => self::$fixture->idSite, - 'date' => self::$fixture->dateTime, - 'periods' => array('day')) - ) - ); - } - - /** - * Path where expected/processed output files are stored. - */ - public static function getPathToTestDirectory() - { - return __DIR__; - } -} - -CustomVariablesSystemTest::$fixture = new Fixtures\VisitWithManyCustomVariables(); \ No newline at end of file diff --git a/plugins/CustomVariables/tests/CustomVariablesTest.php b/plugins/CustomVariables/tests/CustomVariablesTest.php deleted file mode 100644 index 25a158589e..0000000000 --- a/plugins/CustomVariables/tests/CustomVariablesTest.php +++ /dev/null @@ -1,43 +0,0 @@ -assertSame(5, CustomVariables::getMaxCustomVariables()); - } - - public function testGetMaxCustomVariables_ShouldCacheTheResult() - { - CustomVariables::getMaxCustomVariables(); - $cache = Cache::getCacheGeneral(); - - $this->assertSame(5, $cache['CustomVariables.MaxNumCustomVariables']); - } - - public function testGetMaxCustomVariables_ShouldReadFromCacheIfPossible() - { - $cache = Cache::getCacheGeneral(); - $cache['CustomVariables.MaxNumCustomVariables'] = 10; - Cache::setCacheGeneral($cache); - - $this->assertSame(10, CustomVariables::getMaxCustomVariables()); - } - -} diff --git a/plugins/CustomVariables/tests/Integration/CustomVariablesTest.php b/plugins/CustomVariables/tests/Integration/CustomVariablesTest.php new file mode 100644 index 0000000000..25a158589e --- /dev/null +++ b/plugins/CustomVariables/tests/Integration/CustomVariablesTest.php @@ -0,0 +1,43 @@ +assertSame(5, CustomVariables::getMaxCustomVariables()); + } + + public function testGetMaxCustomVariables_ShouldCacheTheResult() + { + CustomVariables::getMaxCustomVariables(); + $cache = Cache::getCacheGeneral(); + + $this->assertSame(5, $cache['CustomVariables.MaxNumCustomVariables']); + } + + public function testGetMaxCustomVariables_ShouldReadFromCacheIfPossible() + { + $cache = Cache::getCacheGeneral(); + $cache['CustomVariables.MaxNumCustomVariables'] = 10; + Cache::setCacheGeneral($cache); + + $this->assertSame(10, CustomVariables::getMaxCustomVariables()); + } + +} diff --git a/plugins/CustomVariables/tests/Integration/ModelTest.php b/plugins/CustomVariables/tests/Integration/ModelTest.php new file mode 100644 index 0000000000..11d444b748 --- /dev/null +++ b/plugins/CustomVariables/tests/Integration/ModelTest.php @@ -0,0 +1,198 @@ +performSetUp(); + } + + public function tearDown() + { + parent::tearDown(); + + self::$fixture->performTearDown(); + } + + /** + * @expectedException \Exception + */ + public function test_construct_shouldFailInCaseOfEmptyScope() + { + new Model(null); + } + + /** + * @expectedException \Exception + */ + public function test_construct_shouldFailInCaseOfInvalidScope() + { + new Model('inValId'); + } + + public function testGetAllScopes() + { + $this->assertEquals(self::$cvarScopes, Model::getScopes()); + } + + public function test_Install_Uninstall() + { + $this->assertEquals(5, $this->getPageScope()->getCurrentNumCustomVars()); + $this->assertEquals(5, $this->getVisitScope()->getCurrentNumCustomVars()); + $this->assertEquals(5, $this->getConversionScope()->getCurrentNumCustomVars()); + + Model::uninstall(); + + $this->assertEquals(0, $this->getPageScope()->getCurrentNumCustomVars()); + $this->assertEquals(0, $this->getVisitScope()->getCurrentNumCustomVars()); + $this->assertEquals(0, $this->getConversionScope()->getCurrentNumCustomVars()); + + $this->getPageScope()->addCustomVariable(); + $this->getPageScope()->addCustomVariable(); + $this->getVisitScope()->addCustomVariable(); + + $this->assertEquals(2, $this->getPageScope()->getCurrentNumCustomVars()); + $this->assertEquals(1, $this->getVisitScope()->getCurrentNumCustomVars()); + $this->assertEquals(0, $this->getConversionScope()->getCurrentNumCustomVars()); + + Model::install(); + + $this->assertEquals(5, $this->getPageScope()->getCurrentNumCustomVars()); + $this->assertEquals(5, $this->getVisitScope()->getCurrentNumCustomVars()); + $this->assertEquals(5, $this->getConversionScope()->getCurrentNumCustomVars()); + } + + public function testGetCustomVariableIndexFromFieldName() + { + $this->assertSame(0, Model::getCustomVariableIndexFromFieldName('custom_var_k0')); + $this->assertSame(0, Model::getCustomVariableIndexFromFieldName('custom_var_v0')); + $this->assertSame(5, Model::getCustomVariableIndexFromFieldName('custom_var_k5')); + $this->assertSame(5, Model::getCustomVariableIndexFromFieldName('custom_var_v5')); + $this->assertSame(938, Model::getCustomVariableIndexFromFieldName('custom_var_k938')); + $this->assertSame(938, Model::getCustomVariableIndexFromFieldName('custom_var_v938')); + $this->assertSame(null, Model::getCustomVariableIndexFromFieldName('otherfield')); + } + + public function testGetScopeName() + { + $this->assertEquals('Page', $this->getPageScope()->getScopeName()); + $this->assertEquals('Visit', $this->getVisitScope()->getScopeName()); + $this->assertEquals('Conversion', $this->getConversionScope()->getScopeName()); + } + + public function test_getCurrentNumCustomVars() + { + $this->assertEquals(5, $this->getPageScope()->getCurrentNumCustomVars()); + $this->assertEquals(5, $this->getVisitScope()->getCurrentNumCustomVars()); + $this->assertEquals(5, $this->getConversionScope()->getCurrentNumCustomVars()); + + $this->getPageScope()->addCustomVariable(); + $this->getConversionScope()->removeCustomVariable(); + + $this->assertEquals(6, $this->getPageScope()->getCurrentNumCustomVars()); + $this->assertEquals(5, $this->getVisitScope()->getCurrentNumCustomVars()); + $this->assertEquals(4, $this->getConversionScope()->getCurrentNumCustomVars()); + } + + public function test_getCustomVarIndexes() + { + $this->assertEquals(array(1,2,3,4,5), $this->getPageScope()->getCustomVarIndexes()); + $this->assertEquals(array(1,2,3,4,5), $this->getVisitScope()->getCustomVarIndexes()); + $this->assertEquals(array(1,2,3,4,5), $this->getConversionScope()->getCustomVarIndexes()); + + $this->getPageScope()->addCustomVariable(); + $this->getConversionScope()->removeCustomVariable(); + + $this->assertEquals(array(1,2,3,4,5,6), $this->getPageScope()->getCustomVarIndexes()); + $this->assertEquals(array(1,2,3,4,5), $this->getVisitScope()->getCustomVarIndexes()); + $this->assertEquals(array(1,2,3,4), $this->getConversionScope()->getCustomVarIndexes()); + } + + public function test_getHighestCustomVarIndex_addCustomVariable_removeCustomVariable() + { + $this->assertEquals(5, $this->getPageScope()->getHighestCustomVarIndex()); + $this->assertEquals(5, $this->getVisitScope()->getHighestCustomVarIndex()); + $this->assertEquals(5, $this->getConversionScope()->getHighestCustomVarIndex()); + + $this->getPageScope()->addCustomVariable(); + $this->getConversionScope()->removeCustomVariable(); + + $this->assertEquals(6, $this->getPageScope()->getHighestCustomVarIndex()); + $this->assertEquals(5, $this->getVisitScope()->getHighestCustomVarIndex()); + $this->assertEquals(4, $this->getConversionScope()->getHighestCustomVarIndex()); + + $this->getConversionScope()->removeCustomVariable(); + $this->getPageScope()->addCustomVariable(); + $this->getVisitScope()->addCustomVariable(); + $this->getPageScope()->addCustomVariable(); + $this->getConversionScope()->removeCustomVariable(); + + $this->assertEquals(8, $this->getPageScope()->getHighestCustomVarIndex()); + $this->assertEquals(6, $this->getVisitScope()->getHighestCustomVarIndex()); + $this->assertEquals(2, $this->getConversionScope()->getHighestCustomVarIndex()); + } + + public function test_removeCustomVariable_shouldNotFailIfRemovesMoreThanExist() + { + $scope = $this->getPageScope(); + + $this->assertEquals(5, $scope->getHighestCustomVarIndex()); + + for ($index = 0; $index < 5; $index++) { + $scope->removeCustomVariable(); + $this->assertEquals(4 - $index, $scope->getHighestCustomVarIndex()); + } + + $this->assertNull($scope->removeCustomVariable()); + $this->assertEquals(0, $scope->getHighestCustomVarIndex()); + $this->assertEquals(0, $scope->getCurrentNumCustomVars()); + } + + public function test_removeCustomVariable_addCustomVariable_ReturnsIndex() + { + $scopeToAdd = $this->getPageScope(); + $scopeToRemove = $this->getVisitScope(); + + for ($index = 0; $index < 5; $index++) { + $this->assertEquals(5 - $index, $scopeToRemove->removeCustomVariable()); + $this->assertEquals(6 + $index, $scopeToAdd->addCustomVariable()); + } + } + + private function getPageScope() + { + return new Model(Model::SCOPE_PAGE); + } + + private function getVisitScope() + { + return new Model(Model::SCOPE_VISIT); + } + + private function getConversionScope() + { + return new Model(Model::SCOPE_CONVERSION); + } + +} diff --git a/plugins/CustomVariables/tests/ModelTest.php b/plugins/CustomVariables/tests/ModelTest.php deleted file mode 100644 index db0afbbba9..0000000000 --- a/plugins/CustomVariables/tests/ModelTest.php +++ /dev/null @@ -1,200 +0,0 @@ -performSetUp(); - } - - public function tearDown() - { - parent::tearDown(); - - self::$fixture->performTearDown(); - } - - /** - * @expectedException \Exception - */ - public function test_construct_shouldFailInCaseOfEmptyScope() - { - new Model(null); - } - - /** - * @expectedException \Exception - */ - public function test_construct_shouldFailInCaseOfInvalidScope() - { - new Model('inValId'); - } - - public function testGetAllScopes() - { - $this->assertEquals(self::$cvarScopes, Model::getScopes()); - } - - public function test_Install_Uninstall() - { - $this->assertEquals(5, $this->getPageScope()->getCurrentNumCustomVars()); - $this->assertEquals(5, $this->getVisitScope()->getCurrentNumCustomVars()); - $this->assertEquals(5, $this->getConversionScope()->getCurrentNumCustomVars()); - - Model::uninstall(); - - $this->assertEquals(0, $this->getPageScope()->getCurrentNumCustomVars()); - $this->assertEquals(0, $this->getVisitScope()->getCurrentNumCustomVars()); - $this->assertEquals(0, $this->getConversionScope()->getCurrentNumCustomVars()); - - $this->getPageScope()->addCustomVariable(); - $this->getPageScope()->addCustomVariable(); - $this->getVisitScope()->addCustomVariable(); - - $this->assertEquals(2, $this->getPageScope()->getCurrentNumCustomVars()); - $this->assertEquals(1, $this->getVisitScope()->getCurrentNumCustomVars()); - $this->assertEquals(0, $this->getConversionScope()->getCurrentNumCustomVars()); - - Model::install(); - - $this->assertEquals(5, $this->getPageScope()->getCurrentNumCustomVars()); - $this->assertEquals(5, $this->getVisitScope()->getCurrentNumCustomVars()); - $this->assertEquals(5, $this->getConversionScope()->getCurrentNumCustomVars()); - } - - public function testGetCustomVariableIndexFromFieldName() - { - $this->assertSame(0, Model::getCustomVariableIndexFromFieldName('custom_var_k0')); - $this->assertSame(0, Model::getCustomVariableIndexFromFieldName('custom_var_v0')); - $this->assertSame(5, Model::getCustomVariableIndexFromFieldName('custom_var_k5')); - $this->assertSame(5, Model::getCustomVariableIndexFromFieldName('custom_var_v5')); - $this->assertSame(938, Model::getCustomVariableIndexFromFieldName('custom_var_k938')); - $this->assertSame(938, Model::getCustomVariableIndexFromFieldName('custom_var_v938')); - $this->assertSame(null, Model::getCustomVariableIndexFromFieldName('otherfield')); - } - - public function testGetScopeName() - { - $this->assertEquals('Page', $this->getPageScope()->getScopeName()); - $this->assertEquals('Visit', $this->getVisitScope()->getScopeName()); - $this->assertEquals('Conversion', $this->getConversionScope()->getScopeName()); - } - - public function test_getCurrentNumCustomVars() - { - $this->assertEquals(5, $this->getPageScope()->getCurrentNumCustomVars()); - $this->assertEquals(5, $this->getVisitScope()->getCurrentNumCustomVars()); - $this->assertEquals(5, $this->getConversionScope()->getCurrentNumCustomVars()); - - $this->getPageScope()->addCustomVariable(); - $this->getConversionScope()->removeCustomVariable(); - - $this->assertEquals(6, $this->getPageScope()->getCurrentNumCustomVars()); - $this->assertEquals(5, $this->getVisitScope()->getCurrentNumCustomVars()); - $this->assertEquals(4, $this->getConversionScope()->getCurrentNumCustomVars()); - } - - public function test_getCustomVarIndexes() - { - $this->assertEquals(array(1,2,3,4,5), $this->getPageScope()->getCustomVarIndexes()); - $this->assertEquals(array(1,2,3,4,5), $this->getVisitScope()->getCustomVarIndexes()); - $this->assertEquals(array(1,2,3,4,5), $this->getConversionScope()->getCustomVarIndexes()); - - $this->getPageScope()->addCustomVariable(); - $this->getConversionScope()->removeCustomVariable(); - - $this->assertEquals(array(1,2,3,4,5,6), $this->getPageScope()->getCustomVarIndexes()); - $this->assertEquals(array(1,2,3,4,5), $this->getVisitScope()->getCustomVarIndexes()); - $this->assertEquals(array(1,2,3,4), $this->getConversionScope()->getCustomVarIndexes()); - } - - public function test_getHighestCustomVarIndex_addCustomVariable_removeCustomVariable() - { - $this->assertEquals(5, $this->getPageScope()->getHighestCustomVarIndex()); - $this->assertEquals(5, $this->getVisitScope()->getHighestCustomVarIndex()); - $this->assertEquals(5, $this->getConversionScope()->getHighestCustomVarIndex()); - - $this->getPageScope()->addCustomVariable(); - $this->getConversionScope()->removeCustomVariable(); - - $this->assertEquals(6, $this->getPageScope()->getHighestCustomVarIndex()); - $this->assertEquals(5, $this->getVisitScope()->getHighestCustomVarIndex()); - $this->assertEquals(4, $this->getConversionScope()->getHighestCustomVarIndex()); - - $this->getConversionScope()->removeCustomVariable(); - $this->getPageScope()->addCustomVariable(); - $this->getVisitScope()->addCustomVariable(); - $this->getPageScope()->addCustomVariable(); - $this->getConversionScope()->removeCustomVariable(); - - $this->assertEquals(8, $this->getPageScope()->getHighestCustomVarIndex()); - $this->assertEquals(6, $this->getVisitScope()->getHighestCustomVarIndex()); - $this->assertEquals(2, $this->getConversionScope()->getHighestCustomVarIndex()); - } - - public function test_removeCustomVariable_shouldNotFailIfRemovesMoreThanExist() - { - $scope = $this->getPageScope(); - - $this->assertEquals(5, $scope->getHighestCustomVarIndex()); - - for ($index = 0; $index < 5; $index++) { - $scope->removeCustomVariable(); - $this->assertEquals(4 - $index, $scope->getHighestCustomVarIndex()); - } - - $this->assertNull($scope->removeCustomVariable()); - $this->assertEquals(0, $scope->getHighestCustomVarIndex()); - $this->assertEquals(0, $scope->getCurrentNumCustomVars()); - } - - public function test_removeCustomVariable_addCustomVariable_ReturnsIndex() - { - $scopeToAdd = $this->getPageScope(); - $scopeToRemove = $this->getVisitScope(); - - for ($index = 0; $index < 5; $index++) { - $this->assertEquals(5 - $index, $scopeToRemove->removeCustomVariable()); - $this->assertEquals(6 + $index, $scopeToAdd->addCustomVariable()); - } - } - - private function getPageScope() - { - return new Model(Model::SCOPE_PAGE); - } - - private function getVisitScope() - { - return new Model(Model::SCOPE_VISIT); - } - - private function getConversionScope() - { - return new Model(Model::SCOPE_CONVERSION); - } - -} diff --git a/plugins/CustomVariables/tests/System/CustomVariablesSystemTest.php b/plugins/CustomVariables/tests/System/CustomVariablesSystemTest.php new file mode 100644 index 0000000000..1bcdf9f838 --- /dev/null +++ b/plugins/CustomVariables/tests/System/CustomVariablesSystemTest.php @@ -0,0 +1,60 @@ +runApiTests($api, $params); + } + + public function getApiForTesting() + { + $apiToCall = array('CustomVariables.getCustomVariables', 'Live.getLastVisitsDetails'); + + return array( + array($apiToCall, array( + 'idSite' => self::$fixture->idSite, + 'date' => self::$fixture->dateTime, + 'periods' => array('day')) + ) + ); + } + + /** + * Path where expected/processed output files are stored. + */ + public static function getPathToTestDirectory() + { + return __DIR__; + } +} + +CustomVariablesSystemTest::$fixture = new Fixtures\VisitWithManyCustomVariables(); \ No newline at end of file diff --git a/plugins/CustomVariables/tests/System/expected/test_CustomVariablesSystemTest__CustomVariables.getCustomVariables_day.xml b/plugins/CustomVariables/tests/System/expected/test_CustomVariablesSystemTest__CustomVariables.getCustomVariables_day.xml new file mode 100644 index 0000000000..1ecaf61b08 --- /dev/null +++ b/plugins/CustomVariables/tests/System/expected/test_CustomVariablesSystemTest__CustomVariables.getCustomVariables_day.xml @@ -0,0 +1,395 @@ + + + + + 1 + + + + 1 + 1 + + + + + + 1 + + + + 1 + 1 + + + + + + 1 + + + + 1 + 1 + + + + + + 1 + + + + 1 + 1 + + + + + + 1 + + + + 1 + 1 + + + + + + 1 + + + + 1 + 1 + + + + + + 1 + + + + 1 + 1 + + + + + + 1 + + + + 1 + 1 + + + + + + 1 + 1 + 0 + 1 + 4 + 1 + + + 1 + 1 + 0 + + + 1 + 0 + + + + 1 + 1 + 0 + 1 + 4 + 1 + + + 1 + 1 + 0 + + + 1 + 0 + + + + + + 1 + 1 + 0 + 1 + 4 + 1 + + + 1 + 1 + 0 + + + 1 + 0 + + + + 1 + 1 + 0 + 1 + 4 + 1 + + + 1 + 1 + 0 + + + 1 + 0 + + + + + + 1 + 1 + 0 + 1 + 4 + 1 + + + 1 + 1 + 0 + + + 1 + 0 + + + + 1 + 1 + 0 + 1 + 4 + 1 + + + 1 + 1 + 0 + + + 1 + 0 + + + + + + 1 + 1 + 0 + 1 + 4 + 1 + + + 1 + 1 + 0 + + + 1 + 0 + + + + 1 + 1 + 0 + 1 + 4 + 1 + + + 1 + 1 + 0 + + + 1 + 0 + + + + + + 1 + 1 + 0 + 1 + 4 + 1 + + + 1 + 1 + 0 + + + 1 + 0 + + + + 1 + 1 + 0 + 1 + 4 + 1 + + + 1 + 1 + 0 + + + 1 + 0 + + + + + + 1 + 1 + 0 + 1 + 4 + 1 + + + 1 + 1 + 0 + + + 1 + 0 + + + + 1 + 1 + 0 + 1 + 4 + 1 + + + 1 + 1 + 0 + + + 1 + 0 + + + + + + 1 + 1 + 0 + 1 + 4 + 1 + + + 1 + 1 + 0 + + + 1 + 0 + + + + 1 + 1 + 0 + 1 + 4 + 1 + + + 1 + 1 + 0 + + + 1 + 0 + + + + + + 1 + 1 + 0 + 1 + 4 + 1 + + + 1 + 1 + 0 + + + 1 + 0 + + + + 1 + 1 + 0 + 1 + 4 + 1 + + + 1 + 1 + 0 + + + 1 + 0 + + + + \ No newline at end of file diff --git a/plugins/CustomVariables/tests/System/expected/test_CustomVariablesSystemTest__Live.getLastVisitsDetails_day.xml b/plugins/CustomVariables/tests/System/expected/test_CustomVariablesSystemTest__Live.getLastVisitsDetails_day.xml new file mode 100644 index 0000000000..a61cb11554 --- /dev/null +++ b/plugins/CustomVariables/tests/System/expected/test_CustomVariablesSystemTest__Live.getLastVisitsDetails_day.xml @@ -0,0 +1,176 @@ + + + + 1 + 1 + 156.5.3.2 + + + + goal + triggered js + 1 + 0 + + + http://localhost + plugins/Morpheus/images/goal.png + + + action + http://localhost + Profile page + 2 + + 1 + + + Name_PAGE_1 + Val_PAGE1 + + + Name_PAGE_2 + Val_PAGE2 + + + Name_PAGE_3 + Val_PAGE3 + + + Name_PAGE_4 + Val_PAGE4 + + + Name_PAGE_5 + Val_PAGE5 + + + Name_PAGE_6 + Val_PAGE6 + + + Name_PAGE_7 + Val_PAGE7 + + + Name_PAGE_8 + Val_PAGE8 + + + + + + 1 + USD + $ + + + + + 0 + 1 + + new + + 1 + plugins/Morpheus/images/goal.png + 1 + + none + + 0 + 0 + 4 + 4s + + + Name_VISIT_1 + Val_VISIT1 + + + Name_VISIT_2 + Val_VISIT2 + + + Name_VISIT_3 + Val_VISIT3 + + + Name_VISIT_4 + Val_VISIT4 + + + Name_VISIT_5 + Val_VISIT5 + + + Name_VISIT_6 + Val_VISIT6 + + + Name_VISIT_7 + Val_VISIT7 + + + Name_VISIT_8 + Val_VISIT8 + + + Desktop + 0 + Unknown + Unknown + http://piwik.org/faq/general/#faq_52 + search + Search Engines + Google + this keyword should be ranked + 1 + http://www.google.com/search?q=this+keyword+should+be+ranked + http://google.com + plugins/Referrers/images/searchEngines/google.com.png + Europe + eur + France + fr + plugins/UserCountry/images/flags/fr.png + + + + France + + + Windows XP + WXP + Win XP + plugins/UserSettings/images/os/WXP.gif + gecko + Gecko (Firefox) + Firefox 3.6 + plugins/UserSettings/images/browsers/FF.gif + FF + 3.6 + normal + 1024x768 + plugins/UserSettings/images/screens/normal.gif + flash, java + + + plugins/UserSettings/images/plugins/flash.gif + flash + + + plugins/UserSettings/images/plugins/java.gif + java + + + 12:34:06 + 12 + 0 + + + + + + + \ No newline at end of file diff --git a/plugins/CustomVariables/tests/System/processed/test_CustomVariablesIntegrationTest__CustomVariables.getCustomVariables_day.xml b/plugins/CustomVariables/tests/System/processed/test_CustomVariablesIntegrationTest__CustomVariables.getCustomVariables_day.xml new file mode 100644 index 0000000000..1ecaf61b08 --- /dev/null +++ b/plugins/CustomVariables/tests/System/processed/test_CustomVariablesIntegrationTest__CustomVariables.getCustomVariables_day.xml @@ -0,0 +1,395 @@ + + + + + 1 + + + + 1 + 1 + + + + + + 1 + + + + 1 + 1 + + + + + + 1 + + + + 1 + 1 + + + + + + 1 + + + + 1 + 1 + + + + + + 1 + + + + 1 + 1 + + + + + + 1 + + + + 1 + 1 + + + + + + 1 + + + + 1 + 1 + + + + + + 1 + + + + 1 + 1 + + + + + + 1 + 1 + 0 + 1 + 4 + 1 + + + 1 + 1 + 0 + + + 1 + 0 + + + + 1 + 1 + 0 + 1 + 4 + 1 + + + 1 + 1 + 0 + + + 1 + 0 + + + + + + 1 + 1 + 0 + 1 + 4 + 1 + + + 1 + 1 + 0 + + + 1 + 0 + + + + 1 + 1 + 0 + 1 + 4 + 1 + + + 1 + 1 + 0 + + + 1 + 0 + + + + + + 1 + 1 + 0 + 1 + 4 + 1 + + + 1 + 1 + 0 + + + 1 + 0 + + + + 1 + 1 + 0 + 1 + 4 + 1 + + + 1 + 1 + 0 + + + 1 + 0 + + + + + + 1 + 1 + 0 + 1 + 4 + 1 + + + 1 + 1 + 0 + + + 1 + 0 + + + + 1 + 1 + 0 + 1 + 4 + 1 + + + 1 + 1 + 0 + + + 1 + 0 + + + + + + 1 + 1 + 0 + 1 + 4 + 1 + + + 1 + 1 + 0 + + + 1 + 0 + + + + 1 + 1 + 0 + 1 + 4 + 1 + + + 1 + 1 + 0 + + + 1 + 0 + + + + + + 1 + 1 + 0 + 1 + 4 + 1 + + + 1 + 1 + 0 + + + 1 + 0 + + + + 1 + 1 + 0 + 1 + 4 + 1 + + + 1 + 1 + 0 + + + 1 + 0 + + + + + + 1 + 1 + 0 + 1 + 4 + 1 + + + 1 + 1 + 0 + + + 1 + 0 + + + + 1 + 1 + 0 + 1 + 4 + 1 + + + 1 + 1 + 0 + + + 1 + 0 + + + + + + 1 + 1 + 0 + 1 + 4 + 1 + + + 1 + 1 + 0 + + + 1 + 0 + + + + 1 + 1 + 0 + 1 + 4 + 1 + + + 1 + 1 + 0 + + + 1 + 0 + + + + \ No newline at end of file diff --git a/plugins/CustomVariables/tests/System/processed/test_CustomVariablesIntegrationTest__Live.getLastVisitsDetails_day.xml b/plugins/CustomVariables/tests/System/processed/test_CustomVariablesIntegrationTest__Live.getLastVisitsDetails_day.xml new file mode 100644 index 0000000000..a61cb11554 --- /dev/null +++ b/plugins/CustomVariables/tests/System/processed/test_CustomVariablesIntegrationTest__Live.getLastVisitsDetails_day.xml @@ -0,0 +1,176 @@ + + + + 1 + 1 + 156.5.3.2 + + + + goal + triggered js + 1 + 0 + + + http://localhost + plugins/Morpheus/images/goal.png + + + action + http://localhost + Profile page + 2 + + 1 + + + Name_PAGE_1 + Val_PAGE1 + + + Name_PAGE_2 + Val_PAGE2 + + + Name_PAGE_3 + Val_PAGE3 + + + Name_PAGE_4 + Val_PAGE4 + + + Name_PAGE_5 + Val_PAGE5 + + + Name_PAGE_6 + Val_PAGE6 + + + Name_PAGE_7 + Val_PAGE7 + + + Name_PAGE_8 + Val_PAGE8 + + + + + + 1 + USD + $ + + + + + 0 + 1 + + new + + 1 + plugins/Morpheus/images/goal.png + 1 + + none + + 0 + 0 + 4 + 4s + + + Name_VISIT_1 + Val_VISIT1 + + + Name_VISIT_2 + Val_VISIT2 + + + Name_VISIT_3 + Val_VISIT3 + + + Name_VISIT_4 + Val_VISIT4 + + + Name_VISIT_5 + Val_VISIT5 + + + Name_VISIT_6 + Val_VISIT6 + + + Name_VISIT_7 + Val_VISIT7 + + + Name_VISIT_8 + Val_VISIT8 + + + Desktop + 0 + Unknown + Unknown + http://piwik.org/faq/general/#faq_52 + search + Search Engines + Google + this keyword should be ranked + 1 + http://www.google.com/search?q=this+keyword+should+be+ranked + http://google.com + plugins/Referrers/images/searchEngines/google.com.png + Europe + eur + France + fr + plugins/UserCountry/images/flags/fr.png + + + + France + + + Windows XP + WXP + Win XP + plugins/UserSettings/images/os/WXP.gif + gecko + Gecko (Firefox) + Firefox 3.6 + plugins/UserSettings/images/browsers/FF.gif + FF + 3.6 + normal + 1024x768 + plugins/UserSettings/images/screens/normal.gif + flash, java + + + plugins/UserSettings/images/plugins/flash.gif + flash + + + plugins/UserSettings/images/plugins/java.gif + java + + + 12:34:06 + 12 + 0 + + + + + + + \ No newline at end of file diff --git a/plugins/CustomVariables/tests/System/processed/test_CustomVariablesSystemTest__CustomVariables.getCustomVariables_day.xml b/plugins/CustomVariables/tests/System/processed/test_CustomVariablesSystemTest__CustomVariables.getCustomVariables_day.xml new file mode 100644 index 0000000000..1ecaf61b08 --- /dev/null +++ b/plugins/CustomVariables/tests/System/processed/test_CustomVariablesSystemTest__CustomVariables.getCustomVariables_day.xml @@ -0,0 +1,395 @@ + + + + + 1 + + + + 1 + 1 + + + + + + 1 + + + + 1 + 1 + + + + + + 1 + + + + 1 + 1 + + + + + + 1 + + + + 1 + 1 + + + + + + 1 + + + + 1 + 1 + + + + + + 1 + + + + 1 + 1 + + + + + + 1 + + + + 1 + 1 + + + + + + 1 + + + + 1 + 1 + + + + + + 1 + 1 + 0 + 1 + 4 + 1 + + + 1 + 1 + 0 + + + 1 + 0 + + + + 1 + 1 + 0 + 1 + 4 + 1 + + + 1 + 1 + 0 + + + 1 + 0 + + + + + + 1 + 1 + 0 + 1 + 4 + 1 + + + 1 + 1 + 0 + + + 1 + 0 + + + + 1 + 1 + 0 + 1 + 4 + 1 + + + 1 + 1 + 0 + + + 1 + 0 + + + + + + 1 + 1 + 0 + 1 + 4 + 1 + + + 1 + 1 + 0 + + + 1 + 0 + + + + 1 + 1 + 0 + 1 + 4 + 1 + + + 1 + 1 + 0 + + + 1 + 0 + + + + + + 1 + 1 + 0 + 1 + 4 + 1 + + + 1 + 1 + 0 + + + 1 + 0 + + + + 1 + 1 + 0 + 1 + 4 + 1 + + + 1 + 1 + 0 + + + 1 + 0 + + + + + + 1 + 1 + 0 + 1 + 4 + 1 + + + 1 + 1 + 0 + + + 1 + 0 + + + + 1 + 1 + 0 + 1 + 4 + 1 + + + 1 + 1 + 0 + + + 1 + 0 + + + + + + 1 + 1 + 0 + 1 + 4 + 1 + + + 1 + 1 + 0 + + + 1 + 0 + + + + 1 + 1 + 0 + 1 + 4 + 1 + + + 1 + 1 + 0 + + + 1 + 0 + + + + + + 1 + 1 + 0 + 1 + 4 + 1 + + + 1 + 1 + 0 + + + 1 + 0 + + + + 1 + 1 + 0 + 1 + 4 + 1 + + + 1 + 1 + 0 + + + 1 + 0 + + + + + + 1 + 1 + 0 + 1 + 4 + 1 + + + 1 + 1 + 0 + + + 1 + 0 + + + + 1 + 1 + 0 + 1 + 4 + 1 + + + 1 + 1 + 0 + + + 1 + 0 + + + + \ No newline at end of file diff --git a/plugins/CustomVariables/tests/System/processed/test_CustomVariablesSystemTest__Live.getLastVisitsDetails_day.xml b/plugins/CustomVariables/tests/System/processed/test_CustomVariablesSystemTest__Live.getLastVisitsDetails_day.xml new file mode 100644 index 0000000000..a61cb11554 --- /dev/null +++ b/plugins/CustomVariables/tests/System/processed/test_CustomVariablesSystemTest__Live.getLastVisitsDetails_day.xml @@ -0,0 +1,176 @@ + + + + 1 + 1 + 156.5.3.2 + + + + goal + triggered js + 1 + 0 + + + http://localhost + plugins/Morpheus/images/goal.png + + + action + http://localhost + Profile page + 2 + + 1 + + + Name_PAGE_1 + Val_PAGE1 + + + Name_PAGE_2 + Val_PAGE2 + + + Name_PAGE_3 + Val_PAGE3 + + + Name_PAGE_4 + Val_PAGE4 + + + Name_PAGE_5 + Val_PAGE5 + + + Name_PAGE_6 + Val_PAGE6 + + + Name_PAGE_7 + Val_PAGE7 + + + Name_PAGE_8 + Val_PAGE8 + + + + + + 1 + USD + $ + + + + + 0 + 1 + + new + + 1 + plugins/Morpheus/images/goal.png + 1 + + none + + 0 + 0 + 4 + 4s + + + Name_VISIT_1 + Val_VISIT1 + + + Name_VISIT_2 + Val_VISIT2 + + + Name_VISIT_3 + Val_VISIT3 + + + Name_VISIT_4 + Val_VISIT4 + + + Name_VISIT_5 + Val_VISIT5 + + + Name_VISIT_6 + Val_VISIT6 + + + Name_VISIT_7 + Val_VISIT7 + + + Name_VISIT_8 + Val_VISIT8 + + + Desktop + 0 + Unknown + Unknown + http://piwik.org/faq/general/#faq_52 + search + Search Engines + Google + this keyword should be ranked + 1 + http://www.google.com/search?q=this+keyword+should+be+ranked + http://google.com + plugins/Referrers/images/searchEngines/google.com.png + Europe + eur + France + fr + plugins/UserCountry/images/flags/fr.png + + + + France + + + Windows XP + WXP + Win XP + plugins/UserSettings/images/os/WXP.gif + gecko + Gecko (Firefox) + Firefox 3.6 + plugins/UserSettings/images/browsers/FF.gif + FF + 3.6 + normal + 1024x768 + plugins/UserSettings/images/screens/normal.gif + flash, java + + + plugins/UserSettings/images/plugins/flash.gif + flash + + + plugins/UserSettings/images/plugins/java.gif + java + + + 12:34:06 + 12 + 0 + + + + + + + \ No newline at end of file diff --git a/plugins/CustomVariables/tests/expected/test_CustomVariablesSystemTest__CustomVariables.getCustomVariables_day.xml b/plugins/CustomVariables/tests/expected/test_CustomVariablesSystemTest__CustomVariables.getCustomVariables_day.xml deleted file mode 100644 index 1ecaf61b08..0000000000 --- a/plugins/CustomVariables/tests/expected/test_CustomVariablesSystemTest__CustomVariables.getCustomVariables_day.xml +++ /dev/null @@ -1,395 +0,0 @@ - - - - - 1 - - - - 1 - 1 - - - - - - 1 - - - - 1 - 1 - - - - - - 1 - - - - 1 - 1 - - - - - - 1 - - - - 1 - 1 - - - - - - 1 - - - - 1 - 1 - - - - - - 1 - - - - 1 - 1 - - - - - - 1 - - - - 1 - 1 - - - - - - 1 - - - - 1 - 1 - - - - - - 1 - 1 - 0 - 1 - 4 - 1 - - - 1 - 1 - 0 - - - 1 - 0 - - - - 1 - 1 - 0 - 1 - 4 - 1 - - - 1 - 1 - 0 - - - 1 - 0 - - - - - - 1 - 1 - 0 - 1 - 4 - 1 - - - 1 - 1 - 0 - - - 1 - 0 - - - - 1 - 1 - 0 - 1 - 4 - 1 - - - 1 - 1 - 0 - - - 1 - 0 - - - - - - 1 - 1 - 0 - 1 - 4 - 1 - - - 1 - 1 - 0 - - - 1 - 0 - - - - 1 - 1 - 0 - 1 - 4 - 1 - - - 1 - 1 - 0 - - - 1 - 0 - - - - - - 1 - 1 - 0 - 1 - 4 - 1 - - - 1 - 1 - 0 - - - 1 - 0 - - - - 1 - 1 - 0 - 1 - 4 - 1 - - - 1 - 1 - 0 - - - 1 - 0 - - - - - - 1 - 1 - 0 - 1 - 4 - 1 - - - 1 - 1 - 0 - - - 1 - 0 - - - - 1 - 1 - 0 - 1 - 4 - 1 - - - 1 - 1 - 0 - - - 1 - 0 - - - - - - 1 - 1 - 0 - 1 - 4 - 1 - - - 1 - 1 - 0 - - - 1 - 0 - - - - 1 - 1 - 0 - 1 - 4 - 1 - - - 1 - 1 - 0 - - - 1 - 0 - - - - - - 1 - 1 - 0 - 1 - 4 - 1 - - - 1 - 1 - 0 - - - 1 - 0 - - - - 1 - 1 - 0 - 1 - 4 - 1 - - - 1 - 1 - 0 - - - 1 - 0 - - - - - - 1 - 1 - 0 - 1 - 4 - 1 - - - 1 - 1 - 0 - - - 1 - 0 - - - - 1 - 1 - 0 - 1 - 4 - 1 - - - 1 - 1 - 0 - - - 1 - 0 - - - - \ No newline at end of file diff --git a/plugins/CustomVariables/tests/expected/test_CustomVariablesSystemTest__Live.getLastVisitsDetails_day.xml b/plugins/CustomVariables/tests/expected/test_CustomVariablesSystemTest__Live.getLastVisitsDetails_day.xml deleted file mode 100644 index a61cb11554..0000000000 --- a/plugins/CustomVariables/tests/expected/test_CustomVariablesSystemTest__Live.getLastVisitsDetails_day.xml +++ /dev/null @@ -1,176 +0,0 @@ - - - - 1 - 1 - 156.5.3.2 - - - - goal - triggered js - 1 - 0 - - - http://localhost - plugins/Morpheus/images/goal.png - - - action - http://localhost - Profile page - 2 - - 1 - - - Name_PAGE_1 - Val_PAGE1 - - - Name_PAGE_2 - Val_PAGE2 - - - Name_PAGE_3 - Val_PAGE3 - - - Name_PAGE_4 - Val_PAGE4 - - - Name_PAGE_5 - Val_PAGE5 - - - Name_PAGE_6 - Val_PAGE6 - - - Name_PAGE_7 - Val_PAGE7 - - - Name_PAGE_8 - Val_PAGE8 - - - - - - 1 - USD - $ - - - - - 0 - 1 - - new - - 1 - plugins/Morpheus/images/goal.png - 1 - - none - - 0 - 0 - 4 - 4s - - - Name_VISIT_1 - Val_VISIT1 - - - Name_VISIT_2 - Val_VISIT2 - - - Name_VISIT_3 - Val_VISIT3 - - - Name_VISIT_4 - Val_VISIT4 - - - Name_VISIT_5 - Val_VISIT5 - - - Name_VISIT_6 - Val_VISIT6 - - - Name_VISIT_7 - Val_VISIT7 - - - Name_VISIT_8 - Val_VISIT8 - - - Desktop - 0 - Unknown - Unknown - http://piwik.org/faq/general/#faq_52 - search - Search Engines - Google - this keyword should be ranked - 1 - http://www.google.com/search?q=this+keyword+should+be+ranked - http://google.com - plugins/Referrers/images/searchEngines/google.com.png - Europe - eur - France - fr - plugins/UserCountry/images/flags/fr.png - - - - France - - - Windows XP - WXP - Win XP - plugins/UserSettings/images/os/WXP.gif - gecko - Gecko (Firefox) - Firefox 3.6 - plugins/UserSettings/images/browsers/FF.gif - FF - 3.6 - normal - 1024x768 - plugins/UserSettings/images/screens/normal.gif - flash, java - - - plugins/UserSettings/images/plugins/flash.gif - flash - - - plugins/UserSettings/images/plugins/java.gif - java - - - 12:34:06 - 12 - 0 - - - - - - - \ No newline at end of file diff --git a/plugins/CustomVariables/tests/processed/test_CustomVariablesIntegrationTest__CustomVariables.getCustomVariables_day.xml b/plugins/CustomVariables/tests/processed/test_CustomVariablesIntegrationTest__CustomVariables.getCustomVariables_day.xml deleted file mode 100644 index 1ecaf61b08..0000000000 --- a/plugins/CustomVariables/tests/processed/test_CustomVariablesIntegrationTest__CustomVariables.getCustomVariables_day.xml +++ /dev/null @@ -1,395 +0,0 @@ - - - - - 1 - - - - 1 - 1 - - - - - - 1 - - - - 1 - 1 - - - - - - 1 - - - - 1 - 1 - - - - - - 1 - - - - 1 - 1 - - - - - - 1 - - - - 1 - 1 - - - - - - 1 - - - - 1 - 1 - - - - - - 1 - - - - 1 - 1 - - - - - - 1 - - - - 1 - 1 - - - - - - 1 - 1 - 0 - 1 - 4 - 1 - - - 1 - 1 - 0 - - - 1 - 0 - - - - 1 - 1 - 0 - 1 - 4 - 1 - - - 1 - 1 - 0 - - - 1 - 0 - - - - - - 1 - 1 - 0 - 1 - 4 - 1 - - - 1 - 1 - 0 - - - 1 - 0 - - - - 1 - 1 - 0 - 1 - 4 - 1 - - - 1 - 1 - 0 - - - 1 - 0 - - - - - - 1 - 1 - 0 - 1 - 4 - 1 - - - 1 - 1 - 0 - - - 1 - 0 - - - - 1 - 1 - 0 - 1 - 4 - 1 - - - 1 - 1 - 0 - - - 1 - 0 - - - - - - 1 - 1 - 0 - 1 - 4 - 1 - - - 1 - 1 - 0 - - - 1 - 0 - - - - 1 - 1 - 0 - 1 - 4 - 1 - - - 1 - 1 - 0 - - - 1 - 0 - - - - - - 1 - 1 - 0 - 1 - 4 - 1 - - - 1 - 1 - 0 - - - 1 - 0 - - - - 1 - 1 - 0 - 1 - 4 - 1 - - - 1 - 1 - 0 - - - 1 - 0 - - - - - - 1 - 1 - 0 - 1 - 4 - 1 - - - 1 - 1 - 0 - - - 1 - 0 - - - - 1 - 1 - 0 - 1 - 4 - 1 - - - 1 - 1 - 0 - - - 1 - 0 - - - - - - 1 - 1 - 0 - 1 - 4 - 1 - - - 1 - 1 - 0 - - - 1 - 0 - - - - 1 - 1 - 0 - 1 - 4 - 1 - - - 1 - 1 - 0 - - - 1 - 0 - - - - - - 1 - 1 - 0 - 1 - 4 - 1 - - - 1 - 1 - 0 - - - 1 - 0 - - - - 1 - 1 - 0 - 1 - 4 - 1 - - - 1 - 1 - 0 - - - 1 - 0 - - - - \ No newline at end of file diff --git a/plugins/CustomVariables/tests/processed/test_CustomVariablesIntegrationTest__Live.getLastVisitsDetails_day.xml b/plugins/CustomVariables/tests/processed/test_CustomVariablesIntegrationTest__Live.getLastVisitsDetails_day.xml deleted file mode 100644 index a61cb11554..0000000000 --- a/plugins/CustomVariables/tests/processed/test_CustomVariablesIntegrationTest__Live.getLastVisitsDetails_day.xml +++ /dev/null @@ -1,176 +0,0 @@ - - - - 1 - 1 - 156.5.3.2 - - - - goal - triggered js - 1 - 0 - - - http://localhost - plugins/Morpheus/images/goal.png - - - action - http://localhost - Profile page - 2 - - 1 - - - Name_PAGE_1 - Val_PAGE1 - - - Name_PAGE_2 - Val_PAGE2 - - - Name_PAGE_3 - Val_PAGE3 - - - Name_PAGE_4 - Val_PAGE4 - - - Name_PAGE_5 - Val_PAGE5 - - - Name_PAGE_6 - Val_PAGE6 - - - Name_PAGE_7 - Val_PAGE7 - - - Name_PAGE_8 - Val_PAGE8 - - - - - - 1 - USD - $ - - - - - 0 - 1 - - new - - 1 - plugins/Morpheus/images/goal.png - 1 - - none - - 0 - 0 - 4 - 4s - - - Name_VISIT_1 - Val_VISIT1 - - - Name_VISIT_2 - Val_VISIT2 - - - Name_VISIT_3 - Val_VISIT3 - - - Name_VISIT_4 - Val_VISIT4 - - - Name_VISIT_5 - Val_VISIT5 - - - Name_VISIT_6 - Val_VISIT6 - - - Name_VISIT_7 - Val_VISIT7 - - - Name_VISIT_8 - Val_VISIT8 - - - Desktop - 0 - Unknown - Unknown - http://piwik.org/faq/general/#faq_52 - search - Search Engines - Google - this keyword should be ranked - 1 - http://www.google.com/search?q=this+keyword+should+be+ranked - http://google.com - plugins/Referrers/images/searchEngines/google.com.png - Europe - eur - France - fr - plugins/UserCountry/images/flags/fr.png - - - - France - - - Windows XP - WXP - Win XP - plugins/UserSettings/images/os/WXP.gif - gecko - Gecko (Firefox) - Firefox 3.6 - plugins/UserSettings/images/browsers/FF.gif - FF - 3.6 - normal - 1024x768 - plugins/UserSettings/images/screens/normal.gif - flash, java - - - plugins/UserSettings/images/plugins/flash.gif - flash - - - plugins/UserSettings/images/plugins/java.gif - java - - - 12:34:06 - 12 - 0 - - - - - - - \ No newline at end of file diff --git a/plugins/CustomVariables/tests/processed/test_CustomVariablesSystemTest__CustomVariables.getCustomVariables_day.xml b/plugins/CustomVariables/tests/processed/test_CustomVariablesSystemTest__CustomVariables.getCustomVariables_day.xml deleted file mode 100644 index 1ecaf61b08..0000000000 --- a/plugins/CustomVariables/tests/processed/test_CustomVariablesSystemTest__CustomVariables.getCustomVariables_day.xml +++ /dev/null @@ -1,395 +0,0 @@ - - - - - 1 - - - - 1 - 1 - - - - - - 1 - - - - 1 - 1 - - - - - - 1 - - - - 1 - 1 - - - - - - 1 - - - - 1 - 1 - - - - - - 1 - - - - 1 - 1 - - - - - - 1 - - - - 1 - 1 - - - - - - 1 - - - - 1 - 1 - - - - - - 1 - - - - 1 - 1 - - - - - - 1 - 1 - 0 - 1 - 4 - 1 - - - 1 - 1 - 0 - - - 1 - 0 - - - - 1 - 1 - 0 - 1 - 4 - 1 - - - 1 - 1 - 0 - - - 1 - 0 - - - - - - 1 - 1 - 0 - 1 - 4 - 1 - - - 1 - 1 - 0 - - - 1 - 0 - - - - 1 - 1 - 0 - 1 - 4 - 1 - - - 1 - 1 - 0 - - - 1 - 0 - - - - - - 1 - 1 - 0 - 1 - 4 - 1 - - - 1 - 1 - 0 - - - 1 - 0 - - - - 1 - 1 - 0 - 1 - 4 - 1 - - - 1 - 1 - 0 - - - 1 - 0 - - - - - - 1 - 1 - 0 - 1 - 4 - 1 - - - 1 - 1 - 0 - - - 1 - 0 - - - - 1 - 1 - 0 - 1 - 4 - 1 - - - 1 - 1 - 0 - - - 1 - 0 - - - - - - 1 - 1 - 0 - 1 - 4 - 1 - - - 1 - 1 - 0 - - - 1 - 0 - - - - 1 - 1 - 0 - 1 - 4 - 1 - - - 1 - 1 - 0 - - - 1 - 0 - - - - - - 1 - 1 - 0 - 1 - 4 - 1 - - - 1 - 1 - 0 - - - 1 - 0 - - - - 1 - 1 - 0 - 1 - 4 - 1 - - - 1 - 1 - 0 - - - 1 - 0 - - - - - - 1 - 1 - 0 - 1 - 4 - 1 - - - 1 - 1 - 0 - - - 1 - 0 - - - - 1 - 1 - 0 - 1 - 4 - 1 - - - 1 - 1 - 0 - - - 1 - 0 - - - - - - 1 - 1 - 0 - 1 - 4 - 1 - - - 1 - 1 - 0 - - - 1 - 0 - - - - 1 - 1 - 0 - 1 - 4 - 1 - - - 1 - 1 - 0 - - - 1 - 0 - - - - \ No newline at end of file diff --git a/plugins/CustomVariables/tests/processed/test_CustomVariablesSystemTest__Live.getLastVisitsDetails_day.xml b/plugins/CustomVariables/tests/processed/test_CustomVariablesSystemTest__Live.getLastVisitsDetails_day.xml deleted file mode 100644 index a61cb11554..0000000000 --- a/plugins/CustomVariables/tests/processed/test_CustomVariablesSystemTest__Live.getLastVisitsDetails_day.xml +++ /dev/null @@ -1,176 +0,0 @@ - - - - 1 - 1 - 156.5.3.2 - - - - goal - triggered js - 1 - 0 - - - http://localhost - plugins/Morpheus/images/goal.png - - - action - http://localhost - Profile page - 2 - - 1 - - - Name_PAGE_1 - Val_PAGE1 - - - Name_PAGE_2 - Val_PAGE2 - - - Name_PAGE_3 - Val_PAGE3 - - - Name_PAGE_4 - Val_PAGE4 - - - Name_PAGE_5 - Val_PAGE5 - - - Name_PAGE_6 - Val_PAGE6 - - - Name_PAGE_7 - Val_PAGE7 - - - Name_PAGE_8 - Val_PAGE8 - - - - - - 1 - USD - $ - - - - - 0 - 1 - - new - - 1 - plugins/Morpheus/images/goal.png - 1 - - none - - 0 - 0 - 4 - 4s - - - Name_VISIT_1 - Val_VISIT1 - - - Name_VISIT_2 - Val_VISIT2 - - - Name_VISIT_3 - Val_VISIT3 - - - Name_VISIT_4 - Val_VISIT4 - - - Name_VISIT_5 - Val_VISIT5 - - - Name_VISIT_6 - Val_VISIT6 - - - Name_VISIT_7 - Val_VISIT7 - - - Name_VISIT_8 - Val_VISIT8 - - - Desktop - 0 - Unknown - Unknown - http://piwik.org/faq/general/#faq_52 - search - Search Engines - Google - this keyword should be ranked - 1 - http://www.google.com/search?q=this+keyword+should+be+ranked - http://google.com - plugins/Referrers/images/searchEngines/google.com.png - Europe - eur - France - fr - plugins/UserCountry/images/flags/fr.png - - - - France - - - Windows XP - WXP - Win XP - plugins/UserSettings/images/os/WXP.gif - gecko - Gecko (Firefox) - Firefox 3.6 - plugins/UserSettings/images/browsers/FF.gif - FF - 3.6 - normal - 1024x768 - plugins/UserSettings/images/screens/normal.gif - flash, java - - - plugins/UserSettings/images/plugins/flash.gif - flash - - - plugins/UserSettings/images/plugins/java.gif - java - - - 12:34:06 - 12 - 0 - - - - - - - \ No newline at end of file diff --git a/plugins/ExamplePlugin/.gitignore b/plugins/ExamplePlugin/.gitignore index b141f4501f..c8c9480010 100644 --- a/plugins/ExamplePlugin/.gitignore +++ b/plugins/ExamplePlugin/.gitignore @@ -1 +1 @@ -tests/processed/*xml \ No newline at end of file +tests/System/processed/*xml \ No newline at end of file diff --git a/plugins/ExamplePlugin/tests/Fixtures/SimpleFixtureTrackFewVisits.php b/plugins/ExamplePlugin/tests/Fixtures/SimpleFixtureTrackFewVisits.php new file mode 100644 index 0000000000..2d455ce70a --- /dev/null +++ b/plugins/ExamplePlugin/tests/Fixtures/SimpleFixtureTrackFewVisits.php @@ -0,0 +1,77 @@ +setUpWebsite(); + $this->trackFirstVisit(); + $this->trackSecondVisit(); + } + + public function tearDown() + { + // empty + } + + private function setUpWebsite() + { + if (!self::siteCreated($this->idSite)) { + $idSite = self::createWebsite($this->dateTime, $ecommerce = 1); + $this->assertSame($this->idSite, $idSite); + } + } + + protected function trackFirstVisit() + { + $t = self::getTracker($this->idSite, $this->dateTime, $defaultInit = true); + + $t->setForceVisitDateTime(Date::factory($this->dateTime)->addHour(0.1)->getDatetime()); + $t->setUrl('http://example.com/'); + self::checkResponse($t->doTrackPageView('Viewing homepage')); + + $t->setForceVisitDateTime(Date::factory($this->dateTime)->addHour(0.2)->getDatetime()); + $t->setUrl('http://example.com/sub/page'); + self::checkResponse($t->doTrackPageView('Second page view')); + + $t->setForceVisitDateTime(Date::factory($this->dateTime)->addHour(0.25)->getDatetime()); + $t->addEcommerceItem($sku = 'SKU_ID', $name = 'Test item!', $category = 'Test & Category', $price = 777, $quantity = 33); + self::checkResponse($t->doTrackEcommerceOrder('TestingOrder', $grandTotal = 33 * 77)); + } + + protected function trackSecondVisit() + { + $t = self::getTracker($this->idSite, $this->dateTime, $defaultInit = true); + $t->setIp('56.11.55.73'); + + $t->setForceVisitDateTime(Date::factory($this->dateTime)->addHour(0.1)->getDatetime()); + $t->setUrl('http://example.com/sub/page'); + self::checkResponse($t->doTrackPageView('Viewing homepage')); + + $t->setForceVisitDateTime(Date::factory($this->dateTime)->addHour(0.2)->getDatetime()); + $t->setUrl('http://example.com/?search=this is a site search query'); + self::checkResponse($t->doTrackPageView('Site search query')); + + $t->setForceVisitDateTime(Date::factory($this->dateTime)->addHour(0.3)->getDatetime()); + $t->addEcommerceItem($sku = 'SKU_ID2', $name = 'A durable item', $category = 'Best seller', $price = 321); + self::checkResponse($t->doTrackEcommerceCartUpdate($grandTotal = 33 * 77)); + } +} \ No newline at end of file diff --git a/plugins/ExamplePlugin/tests/Integration/SimpleTest.php b/plugins/ExamplePlugin/tests/Integration/SimpleTest.php new file mode 100644 index 0000000000..c096b2946b --- /dev/null +++ b/plugins/ExamplePlugin/tests/Integration/SimpleTest.php @@ -0,0 +1,24 @@ +assertEquals(2, 1+1); + } + +} diff --git a/plugins/ExamplePlugin/tests/SimpleSystemTest.php b/plugins/ExamplePlugin/tests/SimpleSystemTest.php deleted file mode 100644 index ec36ab8e31..0000000000 --- a/plugins/ExamplePlugin/tests/SimpleSystemTest.php +++ /dev/null @@ -1,66 +0,0 @@ -runApiTests($api, $params); - } - - public function getApiForTesting() - { - $api = array( - 'API.get', - 'Goals.getItemsSku' - ); - - $apiToTest = array(); - $apiToTest[] = array($api, - array( - 'idSite' => 1, - 'date' => self::$fixture->dateTime, - 'periods' => array('day'), - 'testSuffix' => '' - ) - ); - - return $apiToTest; - } - - public static function getOutputPrefix() - { - return ''; - } - - public static function getPathToTestDirectory() - { - return dirname(__FILE__); - } - -} - -SimpleSystemTest::$fixture = new SimpleFixtureTrackFewVisits(); \ No newline at end of file diff --git a/plugins/ExamplePlugin/tests/SimpleTest.php b/plugins/ExamplePlugin/tests/SimpleTest.php deleted file mode 100644 index 0fdc86062c..0000000000 --- a/plugins/ExamplePlugin/tests/SimpleTest.php +++ /dev/null @@ -1,24 +0,0 @@ -assertEquals(2, 1+1); - } - -} diff --git a/plugins/ExamplePlugin/tests/System/SimpleSystemTest.php b/plugins/ExamplePlugin/tests/System/SimpleSystemTest.php new file mode 100644 index 0000000000..574e6b5a79 --- /dev/null +++ b/plugins/ExamplePlugin/tests/System/SimpleSystemTest.php @@ -0,0 +1,66 @@ +runApiTests($api, $params); + } + + public function getApiForTesting() + { + $api = array( + 'API.get', + 'Goals.getItemsSku' + ); + + $apiToTest = array(); + $apiToTest[] = array($api, + array( + 'idSite' => 1, + 'date' => self::$fixture->dateTime, + 'periods' => array('day'), + 'testSuffix' => '' + ) + ); + + return $apiToTest; + } + + public static function getOutputPrefix() + { + return ''; + } + + public static function getPathToTestDirectory() + { + return dirname(__FILE__); + } + +} + +SimpleSystemTest::$fixture = new SimpleFixtureTrackFewVisits(); \ No newline at end of file diff --git a/plugins/ExamplePlugin/tests/System/expected/test___API.get_day.xml b/plugins/ExamplePlugin/tests/System/expected/test___API.get_day.xml new file mode 100644 index 0000000000..58296797c0 --- /dev/null +++ b/plugins/ExamplePlugin/tests/System/expected/test___API.get_day.xml @@ -0,0 +1,30 @@ + + + 2 + 2 + 0 + 4 + 2 + 0% + 2 + 632 + 0 + 0 + 0 + 0% + 0 + 0 + 1 + 1 + 50 + 2541 + 3 + 3 + 0 + 0 + 0 + 0 + 1 + 1 + 0 + \ No newline at end of file diff --git a/plugins/ExamplePlugin/tests/System/expected/test___Goals.getItemsSku_day.xml b/plugins/ExamplePlugin/tests/System/expected/test___Goals.getItemsSku_day.xml new file mode 100644 index 0000000000..ba820ed649 --- /dev/null +++ b/plugins/ExamplePlugin/tests/System/expected/test___Goals.getItemsSku_day.xml @@ -0,0 +1,12 @@ + + + + + 25641 + 33 + 1 + 777 + 33 + 0% + + \ No newline at end of file diff --git a/plugins/ExamplePlugin/tests/System/processed/.gitkeep b/plugins/ExamplePlugin/tests/System/processed/.gitkeep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/plugins/ExamplePlugin/tests/System/processed/test___API.get_day.xml b/plugins/ExamplePlugin/tests/System/processed/test___API.get_day.xml new file mode 100644 index 0000000000..1cfef75f4b --- /dev/null +++ b/plugins/ExamplePlugin/tests/System/processed/test___API.get_day.xml @@ -0,0 +1,30 @@ + + + 2 + 2 + 0 + 4 + 2 + 0% + 2 + 632 + 0 + 0 + 0 + 0% + 0 + 0 + 1 + 1 + 50 + 2541 + 3 + 3 + 0 + 0 + 0 + 0 + 1 + 1 + 0 + \ No newline at end of file diff --git a/plugins/ExamplePlugin/tests/System/processed/test___Goals.getItemsSku_day.xml b/plugins/ExamplePlugin/tests/System/processed/test___Goals.getItemsSku_day.xml new file mode 100644 index 0000000000..ba820ed649 --- /dev/null +++ b/plugins/ExamplePlugin/tests/System/processed/test___Goals.getItemsSku_day.xml @@ -0,0 +1,12 @@ + + + + + 25641 + 33 + 1 + 777 + 33 + 0% + + \ No newline at end of file diff --git a/plugins/ExamplePlugin/tests/Unit/SimpleTest.php b/plugins/ExamplePlugin/tests/Unit/SimpleTest.php new file mode 100644 index 0000000000..396ee20785 --- /dev/null +++ b/plugins/ExamplePlugin/tests/Unit/SimpleTest.php @@ -0,0 +1,24 @@ +assertEquals(2, 1+1); + } + +} diff --git a/plugins/ExamplePlugin/tests/expected/test___API.get_day.xml b/plugins/ExamplePlugin/tests/expected/test___API.get_day.xml deleted file mode 100644 index 58296797c0..0000000000 --- a/plugins/ExamplePlugin/tests/expected/test___API.get_day.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - 2 - 2 - 0 - 4 - 2 - 0% - 2 - 632 - 0 - 0 - 0 - 0% - 0 - 0 - 1 - 1 - 50 - 2541 - 3 - 3 - 0 - 0 - 0 - 0 - 1 - 1 - 0 - \ No newline at end of file diff --git a/plugins/ExamplePlugin/tests/expected/test___Goals.getItemsSku_day.xml b/plugins/ExamplePlugin/tests/expected/test___Goals.getItemsSku_day.xml deleted file mode 100644 index ba820ed649..0000000000 --- a/plugins/ExamplePlugin/tests/expected/test___Goals.getItemsSku_day.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - 25641 - 33 - 1 - 777 - 33 - 0% - - \ No newline at end of file diff --git a/plugins/ExamplePlugin/tests/fixtures/SimpleFixtureTrackFewVisits.php b/plugins/ExamplePlugin/tests/fixtures/SimpleFixtureTrackFewVisits.php deleted file mode 100644 index ea9755f6a1..0000000000 --- a/plugins/ExamplePlugin/tests/fixtures/SimpleFixtureTrackFewVisits.php +++ /dev/null @@ -1,77 +0,0 @@ -setUpWebsite(); - $this->trackFirstVisit(); - $this->trackSecondVisit(); - } - - public function tearDown() - { - // empty - } - - private function setUpWebsite() - { - if (!self::siteCreated($this->idSite)) { - $idSite = self::createWebsite($this->dateTime, $ecommerce = 1); - $this->assertSame($this->idSite, $idSite); - } - } - - protected function trackFirstVisit() - { - $t = self::getTracker($this->idSite, $this->dateTime, $defaultInit = true); - - $t->setForceVisitDateTime(Date::factory($this->dateTime)->addHour(0.1)->getDatetime()); - $t->setUrl('http://example.com/'); - self::checkResponse($t->doTrackPageView('Viewing homepage')); - - $t->setForceVisitDateTime(Date::factory($this->dateTime)->addHour(0.2)->getDatetime()); - $t->setUrl('http://example.com/sub/page'); - self::checkResponse($t->doTrackPageView('Second page view')); - - $t->setForceVisitDateTime(Date::factory($this->dateTime)->addHour(0.25)->getDatetime()); - $t->addEcommerceItem($sku = 'SKU_ID', $name = 'Test item!', $category = 'Test & Category', $price = 777, $quantity = 33); - self::checkResponse($t->doTrackEcommerceOrder('TestingOrder', $grandTotal = 33 * 77)); - } - - protected function trackSecondVisit() - { - $t = self::getTracker($this->idSite, $this->dateTime, $defaultInit = true); - $t->setIp('56.11.55.73'); - - $t->setForceVisitDateTime(Date::factory($this->dateTime)->addHour(0.1)->getDatetime()); - $t->setUrl('http://example.com/sub/page'); - self::checkResponse($t->doTrackPageView('Viewing homepage')); - - $t->setForceVisitDateTime(Date::factory($this->dateTime)->addHour(0.2)->getDatetime()); - $t->setUrl('http://example.com/?search=this is a site search query'); - self::checkResponse($t->doTrackPageView('Site search query')); - - $t->setForceVisitDateTime(Date::factory($this->dateTime)->addHour(0.3)->getDatetime()); - $t->addEcommerceItem($sku = 'SKU_ID2', $name = 'A durable item', $category = 'Best seller', $price = 321); - self::checkResponse($t->doTrackEcommerceCartUpdate($grandTotal = 33 * 77)); - } -} \ No newline at end of file diff --git a/plugins/ExamplePlugin/tests/processed/.gitkeep b/plugins/ExamplePlugin/tests/processed/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/plugins/Goals/tests/APITest.php b/plugins/Goals/tests/APITest.php deleted file mode 100644 index 39672b722d..0000000000 --- a/plugins/Goals/tests/APITest.php +++ /dev/null @@ -1,232 +0,0 @@ -api = API::getInstance(); - - Fixture::createAccessInstance(); - Piwik::setUserHasSuperUserAccess(); - - Fixture::createWebsite('2014-01-01 00:00:00'); - Fixture::createWebsite('2014-01-01 00:00:00'); - } - - public function test_addGoal_shouldReturnGoalId_IfCreationIsSuccessful() - { - $idGoal = $this->createAnyGoal(); - - $this->assertSame(1, $idGoal); - } - - public function test_addGoal_shouldSucceed_IfOnlyMinimumFieldsGiven() - { - $idGoal = $this->api->addGoal($this->idSite, 'MyName', 'url', 'http://www.test.de', 'exact'); - - $this->assertGoal($idGoal, 'MyName', 'url', 'http://www.test.de', 'exact', 0, 0, 0); - } - - public function test_addGoal_ShouldSucceed_IfAllFieldsGiven() - { - $idGoal = $this->api->addGoal($this->idSite, 'MyName', 'url', 'http://www.test.de', 'exact', true, 50, true); - - $this->assertGoal($idGoal, 'MyName', 'url', 'http://www.test.de', 'exact', 1, 50, 1); - } - - /** - * @expectedException \Exception - * @expectedExceptionMessage Goals_ExceptionInvalidMatchingString - */ - public function test_addGoal_shouldThrowException_IfPatternTypeIsExactAndMatchAttributeNotEvent() - { - $this->api->addGoal($this->idSite, 'MyName', 'url', 'www.test.de', 'exact'); - } - - /** - * @expectedException \Exception - * @expectedExceptionMessage Goals_ExceptionInvalidMatchingString - */ - public function test_addGoal_shouldThrowException_IfPatternTypeIsExactAndMatchAttributeNotEvent2() - { - $this->api->addGoal($this->idSite, 'MyName', 'external_website', 'www.test.de', 'exact'); - } - - public function test_addGoal_shouldNotThrowException_IfPatternTypeIsExactAndMatchAttributeIsEvent() - { - $this->api->addGoal($this->idSite, 'MyName1', 'event_action', 'test', 'exact'); - $this->api->addGoal($this->idSite, 'MyName2', 'event_name', 'test', 'exact'); - $idGoal = $this->api->addGoal($this->idSite, 'MyName3', 'event_category', 'test', 'exact'); - - $this->assertSame('3', (string)$idGoal); - } - - /** - * @expectedException \Exception - * @expectedExceptionMessage checkUserHasAdminAccess Fake exception - */ - public function test_addGoal_shouldThrowException_IfNotEnoughPermission() - { - $this->setNonAdminUser(); - $this->createAnyGoal(); - } - - /** - * @expectedException \Exception - * @expectedExceptionMessage checkUserHasAdminAccess Fake exception - */ - public function test_updateGoal_shouldThrowException_IfNotEnoughPermission() - { - $idGoal = $this->createAnyGoal(); - $this->assertSame(1, $idGoal); // make sure goal is created and does not already fail here - $this->setNonAdminUser(); - $this->api->updateGoal($this->idSite, $idGoal, 'MyName', 'url', 'www.test.de', 'exact'); - } - - /** - * @expectedException \Exception - * @expectedExceptionMessage Goals_ExceptionInvalidMatchingString - */ - public function test_updateGoal_shouldThrowException_IfPatternTypeIsExactAndMatchAttributeNotEvent() - { - $idGoal = $this->createAnyGoal(); - $this->api->updateGoal($this->idSite, $idGoal, 'MyName', 'url', 'www.test.de', 'exact'); - } - - public function test_updateGoal_shouldNotThrowException_IfPatternTypeIsExactAndMatchAttributeIsEvent() - { - $idGoal = $this->createAnyGoal(); - $this->api->updateGoal($this->idSite, $idGoal, 'MyName', 'event_action', 'www.test.de', 'exact'); - $this->api->updateGoal($this->idSite, $idGoal, 'MyName', 'event_category', 'www.test.de', 'exact'); - $this->api->updateGoal($this->idSite, $idGoal, 'MyName', 'event_name', 'www.test.de', 'exact'); - - $this->assertSame(1, $idGoal); - } - - public function test_updateGoal_shouldUpdateAllGivenFields() - { - $idGoal = $this->createAnyGoal(); - $this->api->updateGoal($this->idSite, $idGoal, 'UpdatedName', 'file', 'http://www.updatetest.de', 'contains', true, 999, true); - - $this->assertGoal($idGoal, 'UpdatedName', 'file', 'http://www.updatetest.de', 'contains', 1, 999, 1); - } - - public function test_updateGoal_shouldUpdateMinimalFields_ShouldLeaveOtherFieldsUntouched() - { - $idGoal = $this->createAnyGoal(); - $this->api->updateGoal($this->idSite, $idGoal, 'UpdatedName', 'file', 'http://www.updatetest.de', 'contains'); - - $this->assertGoal($idGoal, 'UpdatedName', 'file', 'http://www.updatetest.de', 'contains', 0, 0, 0); - } - - public function test_deleteGoal_shouldNotDeleteAGoal_IfGoalIdDoesNotExist() - { - $this->assertHasNoGoals(); - - $this->createAnyGoal(); - $this->assertHasGoals(); - - $this->api->deleteGoal($this->idSite, 999); - $this->assertHasGoals(); - } - - public function test_deleteGoal_shouldNotDeleteAGoal_IfSiteDoesNotMatchGoalId() - { - $this->assertHasNoGoals(); - - $idGoal = $this->createAnyGoal(); - $this->assertHasGoals(); - - $this->api->deleteGoal($idSite = 2, $idGoal); - $this->assertHasGoals(); - } - - public function test_deleteGoal_shouldDeleteAGoal_IfGoalAndSiteMatches() - { - $this->assertHasNoGoals(); - - $idGoal = $this->createAnyGoal(); - $this->assertHasGoals(); - - $this->api->deleteGoal($this->idSite, $idGoal); - $this->assertHasNoGoals(); - } - - private function assertHasGoals() - { - $goals = $this->getGoals(); - $this->assertNotEmpty($goals); - } - - private function assertHasNoGoals() - { - $goals = $this->getGoals(); - $this->assertEmpty($goals); - } - - private function assertGoal($idGoal, $name, $url, $pattern, $patternType, $caseSenstive = 0, $revenue = 0, $allowMultiple = 0) - { - $expected = array($idGoal => array( - 'idsite' => $this->idSite, - 'idgoal' => $idGoal, - 'name' => $name, - 'match_attribute' => $url, - 'pattern' => $pattern, - 'pattern_type' => $patternType, - 'case_sensitive' => $caseSenstive, - 'allow_multiple' => $allowMultiple, - 'revenue' => $revenue, - 'deleted' => 0 - )); - - $goals = $this->getGoals(); - - $this->assertEquals($expected, $goals); - } - - private function getGoals() - { - return $this->api->getGoals($this->idSite); - } - - private function createAnyGoal() - { - return $this->api->addGoal($this->idSite, 'MyName1', 'event_action', 'test', 'exact'); - } - - protected function setNonAdminUser() - { - $pseudoMockAccess = new \FakeAccess; - \FakeAccess::setSuperUserAccess(false); - \FakeAccess::$idSitesView = array(99); - \FakeAccess::$identity = 'aUser'; - Access::setSingletonInstance($pseudoMockAccess); - } - -} diff --git a/plugins/Goals/tests/Integration/APITest.php b/plugins/Goals/tests/Integration/APITest.php new file mode 100644 index 0000000000..6251628430 --- /dev/null +++ b/plugins/Goals/tests/Integration/APITest.php @@ -0,0 +1,232 @@ +api = API::getInstance(); + + Fixture::createAccessInstance(); + Piwik::setUserHasSuperUserAccess(); + + Fixture::createWebsite('2014-01-01 00:00:00'); + Fixture::createWebsite('2014-01-01 00:00:00'); + } + + public function test_addGoal_shouldReturnGoalId_IfCreationIsSuccessful() + { + $idGoal = $this->createAnyGoal(); + + $this->assertSame(1, $idGoal); + } + + public function test_addGoal_shouldSucceed_IfOnlyMinimumFieldsGiven() + { + $idGoal = $this->api->addGoal($this->idSite, 'MyName', 'url', 'http://www.test.de', 'exact'); + + $this->assertGoal($idGoal, 'MyName', 'url', 'http://www.test.de', 'exact', 0, 0, 0); + } + + public function test_addGoal_ShouldSucceed_IfAllFieldsGiven() + { + $idGoal = $this->api->addGoal($this->idSite, 'MyName', 'url', 'http://www.test.de', 'exact', true, 50, true); + + $this->assertGoal($idGoal, 'MyName', 'url', 'http://www.test.de', 'exact', 1, 50, 1); + } + + /** + * @expectedException \Exception + * @expectedExceptionMessage Goals_ExceptionInvalidMatchingString + */ + public function test_addGoal_shouldThrowException_IfPatternTypeIsExactAndMatchAttributeNotEvent() + { + $this->api->addGoal($this->idSite, 'MyName', 'url', 'www.test.de', 'exact'); + } + + /** + * @expectedException \Exception + * @expectedExceptionMessage Goals_ExceptionInvalidMatchingString + */ + public function test_addGoal_shouldThrowException_IfPatternTypeIsExactAndMatchAttributeNotEvent2() + { + $this->api->addGoal($this->idSite, 'MyName', 'external_website', 'www.test.de', 'exact'); + } + + public function test_addGoal_shouldNotThrowException_IfPatternTypeIsExactAndMatchAttributeIsEvent() + { + $this->api->addGoal($this->idSite, 'MyName1', 'event_action', 'test', 'exact'); + $this->api->addGoal($this->idSite, 'MyName2', 'event_name', 'test', 'exact'); + $idGoal = $this->api->addGoal($this->idSite, 'MyName3', 'event_category', 'test', 'exact'); + + $this->assertSame('3', (string)$idGoal); + } + + /** + * @expectedException \Exception + * @expectedExceptionMessage checkUserHasAdminAccess Fake exception + */ + public function test_addGoal_shouldThrowException_IfNotEnoughPermission() + { + $this->setNonAdminUser(); + $this->createAnyGoal(); + } + + /** + * @expectedException \Exception + * @expectedExceptionMessage checkUserHasAdminAccess Fake exception + */ + public function test_updateGoal_shouldThrowException_IfNotEnoughPermission() + { + $idGoal = $this->createAnyGoal(); + $this->assertSame(1, $idGoal); // make sure goal is created and does not already fail here + $this->setNonAdminUser(); + $this->api->updateGoal($this->idSite, $idGoal, 'MyName', 'url', 'www.test.de', 'exact'); + } + + /** + * @expectedException \Exception + * @expectedExceptionMessage Goals_ExceptionInvalidMatchingString + */ + public function test_updateGoal_shouldThrowException_IfPatternTypeIsExactAndMatchAttributeNotEvent() + { + $idGoal = $this->createAnyGoal(); + $this->api->updateGoal($this->idSite, $idGoal, 'MyName', 'url', 'www.test.de', 'exact'); + } + + public function test_updateGoal_shouldNotThrowException_IfPatternTypeIsExactAndMatchAttributeIsEvent() + { + $idGoal = $this->createAnyGoal(); + $this->api->updateGoal($this->idSite, $idGoal, 'MyName', 'event_action', 'www.test.de', 'exact'); + $this->api->updateGoal($this->idSite, $idGoal, 'MyName', 'event_category', 'www.test.de', 'exact'); + $this->api->updateGoal($this->idSite, $idGoal, 'MyName', 'event_name', 'www.test.de', 'exact'); + + $this->assertSame(1, $idGoal); + } + + public function test_updateGoal_shouldUpdateAllGivenFields() + { + $idGoal = $this->createAnyGoal(); + $this->api->updateGoal($this->idSite, $idGoal, 'UpdatedName', 'file', 'http://www.updatetest.de', 'contains', true, 999, true); + + $this->assertGoal($idGoal, 'UpdatedName', 'file', 'http://www.updatetest.de', 'contains', 1, 999, 1); + } + + public function test_updateGoal_shouldUpdateMinimalFields_ShouldLeaveOtherFieldsUntouched() + { + $idGoal = $this->createAnyGoal(); + $this->api->updateGoal($this->idSite, $idGoal, 'UpdatedName', 'file', 'http://www.updatetest.de', 'contains'); + + $this->assertGoal($idGoal, 'UpdatedName', 'file', 'http://www.updatetest.de', 'contains', 0, 0, 0); + } + + public function test_deleteGoal_shouldNotDeleteAGoal_IfGoalIdDoesNotExist() + { + $this->assertHasNoGoals(); + + $this->createAnyGoal(); + $this->assertHasGoals(); + + $this->api->deleteGoal($this->idSite, 999); + $this->assertHasGoals(); + } + + public function test_deleteGoal_shouldNotDeleteAGoal_IfSiteDoesNotMatchGoalId() + { + $this->assertHasNoGoals(); + + $idGoal = $this->createAnyGoal(); + $this->assertHasGoals(); + + $this->api->deleteGoal($idSite = 2, $idGoal); + $this->assertHasGoals(); + } + + public function test_deleteGoal_shouldDeleteAGoal_IfGoalAndSiteMatches() + { + $this->assertHasNoGoals(); + + $idGoal = $this->createAnyGoal(); + $this->assertHasGoals(); + + $this->api->deleteGoal($this->idSite, $idGoal); + $this->assertHasNoGoals(); + } + + private function assertHasGoals() + { + $goals = $this->getGoals(); + $this->assertNotEmpty($goals); + } + + private function assertHasNoGoals() + { + $goals = $this->getGoals(); + $this->assertEmpty($goals); + } + + private function assertGoal($idGoal, $name, $url, $pattern, $patternType, $caseSenstive = 0, $revenue = 0, $allowMultiple = 0) + { + $expected = array($idGoal => array( + 'idsite' => $this->idSite, + 'idgoal' => $idGoal, + 'name' => $name, + 'match_attribute' => $url, + 'pattern' => $pattern, + 'pattern_type' => $patternType, + 'case_sensitive' => $caseSenstive, + 'allow_multiple' => $allowMultiple, + 'revenue' => $revenue, + 'deleted' => 0 + )); + + $goals = $this->getGoals(); + + $this->assertEquals($expected, $goals); + } + + private function getGoals() + { + return $this->api->getGoals($this->idSite); + } + + private function createAnyGoal() + { + return $this->api->addGoal($this->idSite, 'MyName1', 'event_action', 'test', 'exact'); + } + + protected function setNonAdminUser() + { + $pseudoMockAccess = new \FakeAccess; + \FakeAccess::setSuperUserAccess(false); + \FakeAccess::$idSitesView = array(99); + \FakeAccess::$identity = 'aUser'; + Access::setSingletonInstance($pseudoMockAccess); + } + +} diff --git a/plugins/Insights/tests/ApiTest.php b/plugins/Insights/tests/ApiTest.php deleted file mode 100644 index 356bc769de..0000000000 --- a/plugins/Insights/tests/ApiTest.php +++ /dev/null @@ -1,269 +0,0 @@ -api = API::getInstance(); - } - - /** - * '/Mover1' => 2, +8 // 400% - * '/Old1' => 9, -9 // -100% - * '/Mover2' => 24, -11 // -50% - * '/Mover3' => 21, -1 // -5% - * '/Old2' => 3 -3 // -100% - * '/New1', +5 // 100% - * '/New2' +2 // 100% - */ - public function test_getInsights_ShouldReturnCorrectMetadata() - { - $insights = $this->requestInsights(array()); - $metadata = $insights->getAllTableMetadata(); - - $expectedMetadata = array( - 'reportName' => 'Page URLs', - 'metricName' => 'Unique Pageviews', - 'date' => self::$fixture->date1, - 'lastDate' => self::$fixture->date2, - 'period' => 'day', - 'orderBy' => 'absolute', - 'metric' => 'nb_visits', - 'totalValue' => 50, - 'minChangeMovers' => 1, - 'minIncreaseNew' => 1, - 'minDecreaseDisappeared' => 1, - 'minGrowthPercentPositive' => 20, - 'minGrowthPercentNegative' => -20, - 'minMoversPercent' => 2, - 'minNewPercent' => 2, - 'minDisappearedPercent' => 2, - 'lastTotalValue' => 59, - 'evolutionTotal' => -15.3, - 'evolutionDifference' => -9 - ); - - $this->assertInternalType('array', $metadata['report']); - $this->assertEquals('Actions', $metadata['report']['module']); - $this->assertEquals('getPageUrls', $metadata['report']['action']); - unset($metadata['report']); - unset($metadata['totals']); - - $this->assertEquals($expectedMetadata, $metadata); - } - - public function test_getInsights_ShouldGoBackInPastDependingOnComparedToParameter() - { - $insights = $this->requestInsights(array('comparedToXPeriods' => 3)); - - $metadata = $insights->getAllTableMetadata(); - - $this->assertEquals('2010-12-11', $metadata['lastDate']); - } - - public function test_getInsights_ShouldGoBackInPastDependingOnPeriod() - { - $insights = $this->requestInsights(array('period' => 'month')); - - $metadata = $insights->getAllTableMetadata(); - - $this->assertEquals('2010-11-14', $metadata['lastDate']); - } - - public function test_getInsights_ShouldReturnAllRowsIfMinValuesArelow() - { - $insights = $this->requestInsights(array('minImpactPercent' => 0, 'minGrowthPercent' => 1)); - - $expectedLabels = array( - '/Mover1', - '/New1', - '/New2', - '/Mover2', - '/Old1', - '/Old2', - '/Mover3' - ); - $this->assertRows($expectedLabels, $insights); - } - - public function test_getInsights_ShouldReturnReturnNothingIfminImpactPercentIsTooHigh() - { - $insights = $this->requestInsights(array('minImpactPercent' => 10000, 'minGrowthPercent' => 0)); - - $this->assertRows(array(), $insights); - } - - public function test_getInsights_ShouldReturnReturnNothingIfMinGrowthIsHigh() - { - $insights = $this->requestInsights(array('minImpactPercent' => 0, 'minGrowthPercent' => 10000)); - - $this->assertRows(array(), $insights); - } - - public function test_getInsights_ShouldOrderAbsoluteByDefault() - { - $insights = $this->requestInsights(array('minImpactPercent' => 0, 'minGrowthPercent' => 0)); - - $expectedLabels = array( - '/Mover1', - '/New1', - '/New2', - '/Mover2', - '/Old1', - '/Old2', - '/Mover3' - ); - $this->assertRows($expectedLabels, $insights); - } - - public function test_getInsights_ShouldBeAbleToOrderRelative() - { - $insights = $this->requestInsights(array('minImpactPercent' => 0, 'minGrowthPercent' => 0, 'orderBy' => 'relative')); - - $expectedLabels = array( - '/Mover1', - '/New1', - '/New2', - '/Old1', - '/Old2', - '/Mover2', - '/Mover3' - ); - $this->assertRows($expectedLabels, $insights); - } - - public function test_getInsights_ShouldBeAbleToOrderByImportance() - { - $insights = $this->requestInsights(array('minImpactPercent' => 0, 'minGrowthPercent' => 0, 'orderBy' => 'importance')); - - $expectedLabels = array( - '/Mover2', - '/Old1', - '/Mover1', - '/New1', - '/Old2', - '/New2', - '/Mover3' - ); - $this->assertRows($expectedLabels, $insights); - } - - public function test_getInsights_ShouldApplyTheLimit() - { - $insights = $this->requestInsights(array('limitIncreaser' => 1, 'limitDecreaser' => 1)); - - $expectedLabels = array( - '/Mover1', - '/Mover2' - ); - $this->assertRows($expectedLabels, $insights); - } - - public function test_getInsights_ShouldBeAbleToShowOnlyMovers() - { - $insights = $this->requestInsights(array('minImpactPercent' => 0, 'minGrowthPercent' => 0, 'filterBy' => 'movers')); - - $expectedLabels = array( - '/Mover1', - '/Mover2', - '/Mover3' - ); - $this->assertRows($expectedLabels, $insights); - } - - public function test_getInsights_ShouldBeAbleToShowOnlyNew() - { - $insights = $this->requestInsights(array('minImpactPercent' => 0, 'minGrowthPercent' => 0, 'filterBy' => 'new')); - - $expectedLabels = array( - '/New1', - '/New2' - ); - $this->assertRows($expectedLabels, $insights); - } - - public function test_getInsights_ShouldBeAbleToShowOnlyDisappeared() - { - $insights = $this->requestInsights(array('minImpactPercent' => 0, 'minGrowthPercent' => 0, 'filterBy' => 'disappeared')); - - $expectedLabels = array( - '/Old1', - '/Old2' - ); - $this->assertRows($expectedLabels, $insights); - } - - public function test_canGenerateInsights() - { - $this->assertTrue($this->api->canGenerateInsights('2012-12-12', 'day')); - $this->assertTrue($this->api->canGenerateInsights('2012-12-12', 'week')); - $this->assertTrue($this->api->canGenerateInsights('2012-12-12', 'month')); - - $this->assertFalse($this->api->canGenerateInsights('last10', 'day')); - $this->assertFalse($this->api->canGenerateInsights('2012-11-11,2012-12-12', 'range')); - } - - private function requestInsights($requestParams) - { - $params = array( - 'method' => 'Insights.getInsights', - 'idSite' => self::$fixture->idSite, - 'date' => self::$fixture->date1, - 'period' => 'day', - 'format' => 'original', - 'reportUniqueId' => 'Actions_getPageUrls', - ); - - if (!empty($requestParams)) { - foreach ($requestParams as $key => $value) { - $params[$key] = $value; - } - } - - $request = new ApiRequest($params); - return $request->process(); - } - - private function assertRows($expectedLabels, DataTable $dataTable) - { - $this->assertEquals($expectedLabels, $dataTable->getColumn('label')); - $this->assertEquals(count($expectedLabels), $dataTable->getRowsCount()); - } -} - -ApiTest::$fixture = new SomeVisitsDifferentPathsOnTwoDays(); \ No newline at end of file diff --git a/plugins/Insights/tests/BaseUnitTest.php b/plugins/Insights/tests/BaseUnitTest.php deleted file mode 100644 index 97c2c78580..0000000000 --- a/plugins/Insights/tests/BaseUnitTest.php +++ /dev/null @@ -1,50 +0,0 @@ -assertEquals($expectedOrder, $this->table->getColumn('label')); - $this->assertEquals(count($expectedOrder), $this->table->getRowsCount()); - } - - protected function assertColumnValues($rowsWithValues) - { - $index = 0; - foreach ($this->table->getRows() as $row) { - $rowToCheck = $rowsWithValues[$index]; - foreach ($rowToCheck as $columnToCheck => $expectedValue) { - $actualValue = $row->getColumn($columnToCheck); - $this->assertEquals($expectedValue, $actualValue, "$columnToCheck in row $index does not match assumed $actualValue is $expectedValue"); - } - $index++; - } - - $this->assertEquals(count($rowsWithValues), $this->table->getRowsCount()); - } - -} diff --git a/plugins/Insights/tests/FilterExcludeLowValueTest.php b/plugins/Insights/tests/FilterExcludeLowValueTest.php deleted file mode 100644 index 51c0192ef6..0000000000 --- a/plugins/Insights/tests/FilterExcludeLowValueTest.php +++ /dev/null @@ -1,85 +0,0 @@ -table = new DataTable(); - $this->table->addRowsFromArray(array( - array(Row::COLUMNS => array('label' => 'val1', 'growth' => 22, 'isFooBar' => false)), - array(Row::COLUMNS => array('label' => 'val2', 'growth' => 14, 'isFooBar' => true)), - array(Row::COLUMNS => array('label' => 'val3', 'growth' => 18, 'isFooBar' => false)), - array(Row::COLUMNS => array('label' => 'val4', 'growth' => 20, 'isFooBar' => true)), - array(Row::COLUMNS => array('label' => 'val5', 'growth' => 22, 'isFooBar' => true)), - array(Row::COLUMNS => array('label' => 'val6', 'growth' => 25, 'isFooBar' => true)), - array(Row::COLUMNS => array('label' => 'val7', 'growth' => 17, 'isFooBar' => false)), - array(Row::COLUMNS => array('label' => 'val8', 'growth' => 20, 'isFooBar' => false)), - array(Row::COLUMNS => array('label' => 'val9', 'growth' => 0, 'isFooBar' => false)), - array(Row::COLUMNS => array('label' => 'val10', 'growth' => 15, 'isFooBar' => false)), - array(Row::COLUMNS => array('label' => 'val11', 'growth' => 16, 'isFooBar' => true)) - )); - } - - public function testShouldNotRemoveAnyIfMinValueIsZero() - { - $rowsCountBefore = $this->table->getRowsCount(); - $this->assertGreaterThan(0, $rowsCountBefore); - - $this->excludeLowValues(0); - - $this->assertSame($rowsCountBefore, $this->table->getRowsCount()); - } - - public function testShouldKeepAllRowsHavingHigherGrowth() - { - $this->excludeLowValues(15); - - $this->assertOrder(array('val1', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8', 'val10', 'val11')); - } - - public function testShouldKeepRowsIfTheyHaveGivenMinGrowth() - { - $this->excludeLowValues(22); - - $this->assertOrder(array('val1', 'val5', 'val6')); - } - - public function testShouldRemoveAllIfMinValueIsTooHigh() - { - $this->excludeLowValues(99); - - $this->assertOrder(array()); - } - - public function testShouldRemoveValuesOnlyIfColumnToCheckIsTrue() - { - $this->excludeLowValues(21, 'isFooBar'); - - $this->assertOrder(array('val1', 'val3', 'val5', 'val6', 'val7', 'val8', 'val9', 'val10')); - } - - private function excludeLowValues($minimumValue, $columnToCheck = null) - { - $filter = new ExcludeLowValue($this->table, 'growth', $minimumValue, $columnToCheck); - $filter->filter($this->table); - } - -} diff --git a/plugins/Insights/tests/FilterInsightTest.php b/plugins/Insights/tests/FilterInsightTest.php deleted file mode 100644 index 67c216b192..0000000000 --- a/plugins/Insights/tests/FilterInsightTest.php +++ /dev/null @@ -1,226 +0,0 @@ -currentTable = new DataTable(); - $this->currentTable->addRowsFromArray(array( - array(Row::COLUMNS => array('label' => 'val1', 'nb_visits' => 120)), - array(Row::COLUMNS => array('label' => 'val2', 'nb_visits' => 70)), - array(Row::COLUMNS => array('label' => 'val3', 'nb_visits' => 90)), - array(Row::COLUMNS => array('label' => 'val4', 'nb_visits' => 99)), - array(Row::COLUMNS => array('label' => 'val5', 'nb_visits' => 0)), - array(Row::COLUMNS => array('label' => 'val6', 'nb_visits' => 0)), - array(Row::COLUMNS => array('label' => 'val7', 'nb_visits' => 134)), - array(Row::COLUMNS => array('label' => 'val8', 'nb_visits' => 100)), - array(Row::COLUMNS => array('label' => 'val9', 'nb_visits' => 7)), - array(Row::COLUMNS => array('label' => 'val10', 'nb_visits' => 89)) - )); - - $this->pastTable = new DataTable(); - $this->pastTable->addRowsFromArray(array( - array(Row::COLUMNS => array('label' => 'val1', 'nb_visits' => 102)), - array(Row::COLUMNS => array('label' => 'val102', 'nb_visits' => 29)), - array(Row::COLUMNS => array('label' => 'val4', 'nb_visits' => 120)), - array(Row::COLUMNS => array('label' => 'val6', 'nb_visits' => 313)), - array(Row::COLUMNS => array('label' => 'val109', 'nb_visits' => 0)), - array(Row::COLUMNS => array('label' => 'val8', 'nb_visits' => 140)), - array(Row::COLUMNS => array('label' => 'val9', 'nb_visits' => 72)), - array(Row::COLUMNS => array('label' => 'val107', 'nb_visits' => 415)), - array(Row::COLUMNS => array('label' => 'val10', 'nb_visits' => 0)) - )); - - $this->table = new DataTable(); - } - - public function testConsiderOnlyMovers() - { - $this->applyInsight($considerMovers = true, $considerNew = false, $considerDisappeared = false); - - $this->assertOrder(array('val1', 'val4', 'val6', 'val8', 'val9', 'val10')); - } - - public function testConsiderOnlyNew() - { - $this->applyInsight($considerMovers = false, $considerNew = true, $considerDisappeared = false); - - $this->assertOrder(array('val2', 'val3', 'val5', 'val7')); - } - - public function testConsiderOnlyDisappeared() - { - $this->applyInsight($considerMovers = false, $considerNew = false, $considerDisappeared = true); - - $this->assertOrder(array('val102', 'val109', 'val107')); - } - - public function testConsiderOnlyNewAndDisappeared() - { - $this->applyInsight($considerMovers = false, $considerNew = true, $considerDisappeared = true); - - $this->assertOrder(array('val2', 'val3', 'val5', 'val7', 'val102', 'val109', 'val107')); - } - - public function testConsiderAll() - { - $this->applyInsightConsiderAll(); - - $this->assertSame(13, $this->table->getRowsCount()); - } - - public function testShouldDetectCorrectOldAndNewValue() - { - $this->applyInsightConsiderAll(); - - $values = array( - array('label' => 'val1', 'value_old' => 102, 'value_new' => 120), - array('label' => 'val2', 'value_old' => 0, 'value_new' => 70), - array('label' => 'val3', 'value_old' => 0, 'value_new' => 90), - array('label' => 'val4', 'value_old' => 120, 'value_new' => 99), - array('label' => 'val5', 'value_old' => 0, 'value_new' => 0), - array('label' => 'val6', 'value_old' => 313, 'value_new' => 0), - array('label' => 'val7', 'value_old' => 0, 'value_new' => 134), - array('label' => 'val8', 'value_old' => 140, 'value_new' => 100), - array('label' => 'val9', 'value_old' => 72, 'value_new' => 7), - array('label' => 'val10', 'value_old' => 0, 'value_new' => 89), - array('label' => 'val102', 'value_old' => 29, 'value_new' => 0), - array('label' => 'val109', 'value_old' => 0, 'value_new' => 0), - array('label' => 'val107', 'value_old' => 415, 'value_new' => 0), - ); - - $this->assertColumnValues($values); - } - - public function testShouldDetectWhetherColumGrownOrNot() - { - $this->applyInsightConsiderAll(); - - $values = array( - array('label' => 'val1', 'grown' => true), - array('label' => 'val2', 'grown' => true), - array('label' => 'val3', 'grown' => true), - array('label' => 'val4', 'grown' => false), - array('label' => 'val5', 'grown' => true), - array('label' => 'val6', 'grown' => false), - array('label' => 'val7', 'grown' => true), - array('label' => 'val8', 'grown' => false), - array('label' => 'val9', 'grown' => false), - array('label' => 'val10', 'grown' => true), - array('label' => 'val102', 'grown' => false), - array('label' => 'val109', 'grown' => true), - array('label' => 'val107', 'grown' => false), - ); - - $this->assertColumnValues($values); - } - - public function testShouldDetectWhetherRowIsNewMoverOrDisappeared() - { - $this->applyInsightConsiderAll(); - - $values = array( - array('label' => 'val1', 'isNew' => false, 'isMover' => true, 'isDisappeared' => false), - array('label' => 'val2', 'isNew' => true, 'isMover' => false, 'isDisappeared' => false), - array('label' => 'val3', 'isNew' => true, 'isMover' => false, 'isDisappeared' => false), - array('label' => 'val4', 'isNew' => false, 'isMover' => true, 'isDisappeared' => false), - array('label' => 'val5', 'isNew' => true, 'isMover' => false, 'isDisappeared' => false), - array('label' => 'val6', 'isNew' => false, 'isMover' => true, 'isDisappeared' => false), - array('label' => 'val7', 'isNew' => true, 'isMover' => false, 'isDisappeared' => false), - array('label' => 'val8', 'isNew' => false, 'isMover' => true, 'isDisappeared' => false), - array('label' => 'val9', 'isNew' => false, 'isMover' => true, 'isDisappeared' => false), - array('label' => 'val10', 'isNew' => false, 'isMover' => true, 'isDisappeared' => false), - array('label' => 'val102', 'isNew' => false, 'isMover' => false, 'isDisappeared' => true), - array('label' => 'val109', 'isNew' => false, 'isMover' => false, 'isDisappeared' => true), - array('label' => 'val107', 'isNew' => false, 'isMover' => false, 'isDisappeared' => true) - ); - - $this->assertColumnValues($values); - } - - public function testShouldCalculateDifferenceAndGrowthPercentage() - { - $this->applyInsightConsiderAll(); - - $values = array( - array('label' => 'val1', 'growth_percent' => '17.6%', 'growth_percent_numeric' => '17.6', 'difference' => 18), - array('label' => 'val2', 'growth_percent' => '100%', 'growth_percent_numeric' => '100', 'difference' => 70), - array('label' => 'val3', 'growth_percent' => '100%', 'growth_percent_numeric' => '100', 'difference' => 90), - array('label' => 'val4', 'growth_percent' => '-17.5%', 'growth_percent_numeric' => '-17.5', 'difference' => -21), - array('label' => 'val5', 'growth_percent' => '0%', 'growth_percent_numeric' => '0', 'difference' => 0), - array('label' => 'val6', 'growth_percent' => '-100%', 'growth_percent_numeric' => '-100', 'difference' => -313), - array('label' => 'val7', 'growth_percent' => '100%', 'growth_percent_numeric' => '100', 'difference' => 134), - array('label' => 'val8', 'growth_percent' => '-28.6%', 'growth_percent_numeric' => '-28.6', 'difference' => -40), - array('label' => 'val9', 'growth_percent' => '-90.3%', 'growth_percent_numeric' => '-90.3', 'difference' => -65), - array('label' => 'val10', 'growth_percent' => '100%', 'growth_percent_numeric' => '100', 'difference' => 89), - array('label' => 'val102', 'growth_percent' => '-100%', 'growth_percent_numeric' => '-100', 'difference' => -29), - array('label' => 'val109', 'growth_percent' => '0%', 'growth_percent_numeric' => '0', 'difference' => 0), - array('label' => 'val107', 'growth_percent' => '-100%', 'growth_percent_numeric' => '-100', 'difference' => -415), - ); - - $this->assertColumnValues($values); - } - - public function testShouldCalculateImporance() - { - $this->applyInsightConsiderAll(); - - $values = array( - array('label' => 'val1', 'importance' => 18), - array('label' => 'val2', 'importance' => 70), - array('label' => 'val3', 'importance' => 90), - array('label' => 'val4', 'importance' => 21), - array('label' => 'val5', 'importance' => 0), - array('label' => 'val6', 'importance' => 313), - array('label' => 'val7', 'importance' => 134), - array('label' => 'val8', 'importance' => 40), - array('label' => 'val9', 'importance' => 65), - array('label' => 'val10', 'importance' => 89), - array('label' => 'val102', 'importance' => 29), - array('label' => 'val109', 'importance' => 0), - array('label' => 'val107', 'importance' => 415), - ); - - $this->assertColumnValues($values); - } - - private function applyInsight($considerMovers, $considerNew, $considerDisappeared) - { - $filter = new Insight($this->table, $this->currentTable, $this->pastTable, 'nb_visits', $considerMovers, $considerNew, $considerDisappeared); - $filter->filter($this->table); - } - - private function applyInsightConsiderAll() - { - $this->applyInsight($considerMovers = true, $considerNew = true, $considerDisappeared = true); - } - -} diff --git a/plugins/Insights/tests/FilterLimitTest.php b/plugins/Insights/tests/FilterLimitTest.php deleted file mode 100644 index 6f6d703b0a..0000000000 --- a/plugins/Insights/tests/FilterLimitTest.php +++ /dev/null @@ -1,81 +0,0 @@ -table = new DataTable(); - $this->table->addRowsFromArray(array( - array(Row::COLUMNS => array('label' => 'pos1', 'growth' => 12)), - array(Row::COLUMNS => array('label' => 'pos2', 'growth' => 7)), - array(Row::COLUMNS => array('label' => 'neg1', 'growth' => -9)), - array(Row::COLUMNS => array('label' => 'pos3', 'growth' => 10)), - array(Row::COLUMNS => array('label' => 'neg2', 'growth' => -11)), - array(Row::COLUMNS => array('label' => 'neg3', 'growth' => -13)), - array(Row::COLUMNS => array('label' => 'pos4', 'growth' => 9)), - array(Row::COLUMNS => array('label' => 'pos5', 'growth' => 10)), - array(Row::COLUMNS => array('label' => 'neg4', 'growth' => -7)), - array(Row::COLUMNS => array('label' => 'neg5', 'growth' => -8)) - )); - } - - public function testFilterAll() - { - $this->applyLimit($limitIncreaser = 0, $limitDecreaser = 0); - - $this->assertOrder(array()); - } - - public function testNoDescreaser() - { - $this->applyLimit($limitIncreaser = 4, $limitDecreaser = 0); - - $this->assertOrder(array('pos1', 'pos2', 'pos3', 'pos4')); - } - - public function testNoIncreaser() - { - $this->applyLimit($limitIncreaser = 0, $limitDecreaser = 4); - - $this->assertOrder(array('neg1', 'neg2', 'neg3', 'neg4')); - } - - public function testShouldKeepOrderOfRows() - { - $this->applyLimit($limitIncreaser = 3, $limitDecreaser = 2); - - $this->assertOrder(array('pos1', 'pos2', 'neg1', 'pos3', 'neg2')); - } - - public function testShouldReturnAllRowsIfLimitIsHighEnough() - { - $this->applyLimit($limitIncreaser = 99, $limitDecreaser = 99); - - $this->assertOrder(array('pos1', 'pos2', 'neg1', 'pos3', 'neg2', 'neg3', 'pos4', 'pos5', 'neg4', 'neg5')); - } - - private function applyLimit($limitIncrease, $limitDecrease) - { - $filter = new Limit($this->table, 'growth', $limitIncrease, $limitDecrease); - $filter->filter($this->table); - } - -} diff --git a/plugins/Insights/tests/FilterMinGrowthTest.php b/plugins/Insights/tests/FilterMinGrowthTest.php deleted file mode 100644 index a53245b891..0000000000 --- a/plugins/Insights/tests/FilterMinGrowthTest.php +++ /dev/null @@ -1,91 +0,0 @@ -table = new DataTable(); - $this->table->addRowsFromArray(array( - array(Row::COLUMNS => array('label' => 'pos1', 'growth' => 22)), - array(Row::COLUMNS => array('label' => 'pos2', 'growth' => 14)), - array(Row::COLUMNS => array('label' => 'neg1', 'growth' => -18)), - array(Row::COLUMNS => array('label' => 'pos3', 'growth' => 20)), - array(Row::COLUMNS => array('label' => 'neg2', 'growth' => -22)), - array(Row::COLUMNS => array('label' => 'neg3', 'growth' => -25)), - array(Row::COLUMNS => array('label' => 'pos4', 'growth' => 17)), - array(Row::COLUMNS => array('label' => 'pos5', 'growth' => 20)), - array(Row::COLUMNS => array('label' => 'pos6', 'growth' => 0)), - array(Row::COLUMNS => array('label' => 'neg4', 'growth' => -15)), - array(Row::COLUMNS => array('label' => 'neg5', 'growth' => -16)) - )); - } - - public function testShouldNotRemoveAnyIfMinGrowthIsZero() - { - $rowsCountBefore = $this->table->getRowsCount(); - $this->assertGreaterThan(0, $rowsCountBefore); - - $this->applyMinGrowthFilter(0, 0); - - $this->assertSame($rowsCountBefore, $this->table->getRowsCount()); - } - - public function testShouldKeepAllRowsHavingHigherGrowth() - { - $this->applyMinGrowthFilter(15, -15); - - $this->assertOrder(array('pos1', 'neg1', 'pos3', 'neg2', 'neg3', 'pos4', 'pos5', 'neg4', 'neg5')); - } - - public function testShouldKeepRowsIfTheyHaveGivenMinGrowth() - { - $this->applyMinGrowthFilter(22, -22); - - $this->assertOrder(array('pos1', 'neg2', 'neg3')); - } - - public function testDifferentGrowth() - { - $this->applyMinGrowthFilter(22, -16); - $this->assertOrder(array('pos1', 'neg1', 'neg2', 'neg3', 'neg5')); - } - - public function testDifferentGrowth2() - { - $this->applyMinGrowthFilter(15, -24); - $this->assertOrder(array('pos1', 'pos3', 'neg3', 'pos4', 'pos5')); - } - - public function testShouldRemoveAllIfMinGrowthIsTooHigh() - { - $this->applyMinGrowthFilter(999, -999); - - $this->assertOrder(array()); - } - - private function applyMinGrowthFilter($minGrowthPercentPositive, $minGrowthPercentNegative) - { - $filter = new MinGrowth($this->table, 'growth', $minGrowthPercentPositive, $minGrowthPercentNegative); - $filter->filter($this->table); - } - -} diff --git a/plugins/Insights/tests/FilterOrderByTest.php b/plugins/Insights/tests/FilterOrderByTest.php deleted file mode 100644 index 8239204a2f..0000000000 --- a/plugins/Insights/tests/FilterOrderByTest.php +++ /dev/null @@ -1,95 +0,0 @@ -table = new DataTable(); - } - - public function testOrderByShouldListAllHighestPositiveValuesFirstThenAllNegativeValuesLowestFirst() - { - $this->table->addRowsFromArray(array( - array(Row::COLUMNS => array('label' => 'pos1', 'growth' => 12)), - array(Row::COLUMNS => array('label' => 'pos2', 'growth' => 7)), - array(Row::COLUMNS => array('label' => 'neg1', 'growth' => -9)), - array(Row::COLUMNS => array('label' => 'pos3', 'growth' => 10)), - array(Row::COLUMNS => array('label' => 'neg2', 'growth' => -11)), - array(Row::COLUMNS => array('label' => 'neg3', 'growth' => -13)), - array(Row::COLUMNS => array('label' => 'pos4', 'growth' => 9)), - array(Row::COLUMNS => array('label' => 'pos5', 'growth' => 10)), - array(Row::COLUMNS => array('label' => 'pos6', 'growth' => 0)), - array(Row::COLUMNS => array('label' => 'neg4', 'growth' => -7)), - array(Row::COLUMNS => array('label' => 'neg5', 'growth' => -8)) - )); - - $this->applyOrderByFilter(); - - $this->assertOrder(array('pos1', 'pos5', 'pos3', 'pos4', 'pos2', 'pos6', 'neg3', 'neg2', 'neg1', 'neg5', 'neg4')); - } - - public function testOrderByShouldSortDependingOnNbVisitsIfColumnsHaveSameValue() - { - $this->table->addRowsFromArray(array( - array(Row::COLUMNS => array('label' => 'pos1', 'nb_visits' => 40, 'growth' => 7)), - array(Row::COLUMNS => array('label' => 'pos2', 'nb_visits' => 55, 'growth' => 7)), - array(Row::COLUMNS => array('label' => 'pos3', 'nb_visits' => 35, 'growth' => 7)), - array(Row::COLUMNS => array('label' => 'pos4', 'nb_visits' => 60, 'growth' => 7)), - array(Row::COLUMNS => array('label' => 'pos5', 'nb_visits' => 7, 'growth' => 7)), - array(Row::COLUMNS => array('label' => 'pos6', 'nb_visits' => 35, 'growth' => 7)), - array(Row::COLUMNS => array('label' => 'neg1', 'nb_visits' => 33, 'growth' => -5)), - array(Row::COLUMNS => array('label' => 'neg2', 'nb_visits' => 34, 'growth' => -5)), - array(Row::COLUMNS => array('label' => 'neg3', 'nb_visits' => 99, 'growth' => -5)), - array(Row::COLUMNS => array('label' => 'neg4', 'nb_visits' => 20, 'growth' => -5)) - )); - - $this->applyOrderByFilter(); - - $this->assertOrder(array('pos4', 'pos2', 'pos1', 'pos3', 'pos6', 'pos5', 'neg3', 'neg2', 'neg1', 'neg4')); - } - - public function testOrderByShouldSortDependingOnNbVisitsIfColumnsHaveSameValueAndNbVisitsIsNegative() - { - $this->table->addRowsFromArray(array( - array(Row::COLUMNS => array('label' => 'pos1', 'nb_visits' => -40, 'growth' => 7)), - array(Row::COLUMNS => array('label' => 'pos2', 'nb_visits' => -55, 'growth' => 7)), - array(Row::COLUMNS => array('label' => 'pos3', 'nb_visits' => -35, 'growth' => 7)), - array(Row::COLUMNS => array('label' => 'pos4', 'nb_visits' => -60, 'growth' => 7)), - array(Row::COLUMNS => array('label' => 'pos5', 'nb_visits' => -7, 'growth' => 7)), - array(Row::COLUMNS => array('label' => 'pos6', 'nb_visits' => -35, 'growth' => 7)), - array(Row::COLUMNS => array('label' => 'neg1', 'nb_visits' => -33, 'growth' => -5)), - array(Row::COLUMNS => array('label' => 'neg2', 'nb_visits' => -34, 'growth' => -5)), - array(Row::COLUMNS => array('label' => 'neg3', 'nb_visits' => -99, 'growth' => -5)), - array(Row::COLUMNS => array('label' => 'neg4', 'nb_visits' => -20, 'growth' => -5)) - )); - - $this->applyOrderByFilter(); - - $this->assertOrder(array('pos4', 'pos2', 'pos1', 'pos3', 'pos6', 'pos5', 'neg3', 'neg2', 'neg1', 'neg4')); - } - - private function applyOrderByFilter() - { - $filter = new OrderBy($this->table, 'growth', 'nb_visits'); - $filter->filter($this->table); - } - -} diff --git a/plugins/Insights/tests/InsightReportTest.php b/plugins/Insights/tests/InsightReportTest.php deleted file mode 100644 index 32901409ac..0000000000 --- a/plugins/Insights/tests/InsightReportTest.php +++ /dev/null @@ -1,471 +0,0 @@ -currentTable = new DataTable(); - $this->currentTable->addRowsFromArray(array( - array(Row::COLUMNS => array('label' => 'val1', 'nb_visits' => 120)), - array(Row::COLUMNS => array('label' => 'val2', 'nb_visits' => 70)), - array(Row::COLUMNS => array('label' => 'val3', 'nb_visits' => 90)), - array(Row::COLUMNS => array('label' => 'val4', 'nb_visits' => 99)), - array(Row::COLUMNS => array('label' => 'val5', 'nb_visits' => 0)), - array(Row::COLUMNS => array('label' => 'val6', 'nb_visits' => 0)), - array(Row::COLUMNS => array('label' => 'val7', 'nb_visits' => 134)), - array(Row::COLUMNS => array('label' => 'val8', 'nb_visits' => 100)), - array(Row::COLUMNS => array('label' => 'val9', 'nb_visits' => 7)), - array(Row::COLUMNS => array('label' => 'val10', 'nb_visits' => 89)), - array(Row::COLUMNS => array('label' => 'val11', 'nb_visits' => 170)), - array(Row::COLUMNS => array('label' => 'val12', 'nb_visits' => 14)) - )); - - $this->pastTable = new DataTable(); - $this->pastTable->addRowsFromArray(array( - array(Row::COLUMNS => array('label' => 'val1', 'nb_visits' => 102)), - array(Row::COLUMNS => array('label' => 'val102', 'nb_visits' => 29)), - array(Row::COLUMNS => array('label' => 'val4', 'nb_visits' => 120)), - array(Row::COLUMNS => array('label' => 'val6', 'nb_visits' => 180)), - array(Row::COLUMNS => array('label' => 'val109', 'nb_visits' => 0)), - array(Row::COLUMNS => array('label' => 'val8', 'nb_visits' => 140)), - array(Row::COLUMNS => array('label' => 'val9', 'nb_visits' => 72)), - array(Row::COLUMNS => array('label' => 'val107', 'nb_visits' => 150)), - array(Row::COLUMNS => array('label' => 'val10', 'nb_visits' => 0)), - array(Row::COLUMNS => array('label' => 'val11', 'nb_visits' => 5)), - array(Row::COLUMNS => array('label' => 'val12', 'nb_visits' => 5)) - )); - - $this->insightReport = new InsightReport(); - } - - /** - * @dataProvider provideOrderTestData - */ - public function test_generateInsight_Order($orderBy, $expectedOrder) - { - $report = $this->generateInsight(2, 2, 2, 17, -17, $orderBy); - - $this->assertOrder($report, $expectedOrder); - } - - public function provideOrderTestData() - { - return array( - array(InsightReport::ORDER_BY_IMPORTANCE, array('val6', 'val11', 'val107', 'val7', 'val3', 'val10', 'val2', 'val9', 'val8', 'val102', 'val4', 'val1', 'val12')), - array(InsightReport::ORDER_BY_RELATIVE, array('val11', 'val12', 'val7', 'val3', 'val10', 'val2', 'val1', 'val6', 'val107', 'val102', 'val9', 'val8', 'val4')), - array(InsightReport::ORDER_BY_ABSOLUTE, array('val11', 'val7', 'val3', 'val10', 'val2', 'val1', 'val12', 'val6', 'val107', 'val9', 'val8', 'val102', 'val4')), - ); - } - - /** - * @expectedException \Exception - * @expectedExceptionMessage Unsupported orderBy - */ - public function test_generateInsight_Order_ShouldThrowException_IfInvalid() - { - $this->generateInsight(2, 2, 2, 17, -17, 'InvalidOrDeRbY'); - } - - /** - * @dataProvider provideMinGrowthTestData - */ - public function test_generateInsight_MinGrowth($minGrowthPositive, $minGrowthNegative, $expectedOrder) - { - $report = $this->generateInsight(2, 2, 2, $minGrowthPositive, $minGrowthNegative, InsightReport::ORDER_BY_ABSOLUTE); - $this->assertOrder($report, $expectedOrder); - } - - public function provideMinGrowthTestData() - { - return array( - array(4000, -4000, array()), - array(1000, -1000, array('val11')), - array(120, -120, array('val11', 'val12')), - array(80, -80, array('val11', 'val7', 'val3', 'val10', 'val2', 'val12', 'val6', 'val107', 'val9', 'val102')), - array(19, -19, array('val11', 'val7', 'val3', 'val10', 'val2', 'val12', 'val6', 'val107', 'val9', 'val8', 'val102')), - array(17, -17, array('val11', 'val7', 'val3', 'val10', 'val2', 'val1', 'val12', 'val6', 'val107', 'val9', 'val8', 'val102', 'val4')), - array(17, -80, array('val11', 'val7', 'val3', 'val10', 'val2', 'val1', 'val12', 'val6', 'val107', 'val9', 'val102')), - array(17, -4000, array('val11', 'val7', 'val3', 'val10', 'val2', 'val1', 'val12')), - array(4000, -17, array('val6', 'val107', 'val9', 'val8', 'val102', 'val4')), - ); - } - - /** - * @dataProvider provideLimitTestData - */ - public function test_generateInsight_Limit($limitIncrease, $limitDecrease, $expectedOrder) - { - $report = $this->generateInsight(2, 2, 2, 20, -20, InsightReport::ORDER_BY_ABSOLUTE, $limitIncrease, $limitDecrease); - - $this->assertOrder($report, $expectedOrder); - } - - public function provideLimitTestData() - { - return array( - array(1, 1, array('val11', 'val6')), - array(1, 0, array('val11')), // only increase - array(0, 1, array('val6')), // only decrease - array(0, 0, array()), // neither increase nor decrease - ); - } - - public function test_generateInsight_NoMovers() - { - $report = $this->generateInsight(-1, 2, 2, 20, -20); - - $this->assertOrder($report, array('val7', 'val3', 'val2', 'val107', 'val102')); - } - - /** - * @dataProvider provideMinImpactMoversTestData - */ - public function test_generateInsight_MinImpactMovers($minMoversPercent, $expectedOrder) - { - $report = $this->generateInsight($minMoversPercent, -1, -1, 17, -17); - - $this->assertOrder($report, $expectedOrder); - } - - public function provideMinImpactMoversTestData() - { - return array( - array(2, array('val11', 'val10', 'val1', 'val12', 'val6', 'val9', 'val8', 'val4')), - array(20, array('val11', 'val10', 'val6', 'val9', 'val8')), - array(80, array('val11', 'val6')), - array(10000, array()) - ); - } - - public function test_generateInsight_NoNew() - { - $report = $this->generateInsight(2, -1, 2, 17, -17); - - $this->assertOrder($report, array('val11', 'val10', 'val1', 'val12', 'val6', 'val107', 'val9', 'val8', 'val102', 'val4')); - } - - /** - * @dataProvider provideMinImpactNewTestData - */ - public function test_generateInsight_MinImpactNew($minNewPercent, $expectedOrder) - { - $report = $this->generateInsight(-1, $minNewPercent, -1, 17, -17); - - $this->assertOrder($report, $expectedOrder); - } - - public function provideMinImpactNewTestData() - { - return array( - array(2, array('val7', 'val3', 'val2')), - array(22, array('val7', 'val3', 'val2')), - array(36, array('val7', 'val3')), - array(66, array('val7')), - array(10000, array()) - ); - } - - public function test_generateInsight_NoDisappeared() - { - $report = $this->generateInsight(2, 2, -1, 17, -17); - - $this->assertOrder($report, array('val11', 'val7', 'val3', 'val10', 'val2', 'val1', 'val12', 'val6', 'val9', 'val8', 'val4')); - } - - /** - * @dataProvider provideMinImpactDisappearedData - */ - public function test_generateInsight_MinDisappeared($minDisappearedPercent, $expectedOrder) - { - $report = $this->generateInsight(-1, -1, $minDisappearedPercent, 17, -17); - $this->assertOrder($report, $expectedOrder); - } - - public function provideMinImpactDisappearedData() - { - return array( - array(2, array('val107', 'val102')), - array(14, array('val107', 'val102')), - array(15, array('val107')), - array(75, array('val107')), - array(76, array()), - array(10000, array()) - ); - } - - public function test_generateInsights_ShouldSetCorrectMetadata() - { - $report = $this->generateInsight(2, 4, 8, 17, -21); - $metadata = $report->getAllTableMetadata(); - - $expectedMetadata = array( - 'reportName' => 'TestReport', - 'metricName' => 'Visits', - 'date' => '2012-12-12', - 'lastDate' => '2012-12-11', - 'period' => 'day', - 'orderBy' => 'absolute', - 'metric' => 'nb_visits', - 'totalValue' => 200, - 'minChangeMovers' => 4, - 'minIncreaseNew' => 8, - 'minDecreaseDisappeared' => 16, - 'minGrowthPercentPositive' => 17, - 'minGrowthPercentNegative' => -21, - 'minMoversPercent' => 2, - 'minNewPercent' => 4, - 'minDisappearedPercent' => 8, - ); - - $this->assertInternalType('array', $metadata['report']); - $this->assertEquals('TestReport', $metadata['report']['name']); - unset($metadata['report']); - unset($metadata['totals']); - - $this->assertEquals($expectedMetadata, $metadata); - } - - public function test_markMoversAndShakers() - { - $report = $this->generateInsight(2, 2, 2, 5, -5); - $this->insightReport->markMoversAndShakers($report, $this->currentTable, $this->pastTable, 160, 100); - - // increase by 60% --> minGrowth 80% - $movers = array('val11', 'val12', 'val7', 'val9', 'val3', 'val10', 'val2', 'val6', 'val107', 'val102'); - $nonMovers = array('val1', 'val8', 'val4'); - - $this->assertMoversAndShakers($report, $movers, $nonMovers); - } - - public function test_markMoversAndShakers_shouldAddMetadata() - { - $report = $this->generateInsight(2, 2, 2, 5, -5); - $this->insightReport->markMoversAndShakers($report, $this->currentTable, $this->pastTable, 200, 100); - - $metadata = $report->getAllTableMetadata(); - - $this->assertEquals(100, $metadata['lastTotalValue']); - $this->assertEquals(200, $metadata['totalValue']); - $this->assertEquals(100, $metadata['evolutionDifference']); - $this->assertEquals(100, $metadata['evolutionTotal']); - } - - public function test_generateMoversAndShakers() - { - // increase by 60% --> minGrowth 80% - $report = $this->generateMoverAndShaker(160, 100); - $this->assertOrder($report, array('val11', 'val7', 'val3', 'val10', 'val2', 'val12', 'val6', 'val107', 'val9', 'val102')); - - // increase by 1600% --> minGrowth 1640% - $report = $this->generateMoverAndShaker(1600, 100); - $this->assertOrder($report, array('val11', 'val6', 'val107', 'val9')); - - } - - private function assertMoversAndShakers(DataTable $report, $movers, $nonMovers) - { - foreach ($movers as $mover) { - $row = $report->getRowFromLabel($mover); - if (!$row) { - $this->fail("$mover is not a valid label"); - continue; - } - $this->assertTrue($row->getColumn('isMoverAndShaker'), "$mover is not a mover but should be"); - } - - foreach ($nonMovers as $nonMover) { - $row = $report->getRowFromLabel($nonMover); - if (!$row) { - $this->fail("$nonMover is not a valid label"); - continue; - } - $this->assertFalse($row->getColumn('isMoverAndShaker'), "$nonMover is a mover but should be not"); - } - } - - public function test_generateMoversAndShakers_Metadata() - { - $report = $this->generateMoverAndShaker(150, 50); - $metadata = $report->getAllTableMetadata(); - - $this->assertEquals(50, $metadata['lastTotalValue']); - $this->assertEquals(150, $metadata['totalValue']); - $this->assertEquals(100, $metadata['evolutionDifference']); - $this->assertEquals(200, $metadata['evolutionTotal']); - - $report = $this->generateMoverAndShaker(75, 50); - $metadata = $report->getAllTableMetadata(); - - $this->assertEquals(50, $metadata['lastTotalValue']); - $this->assertEquals(75, $metadata['totalValue']); - $this->assertEquals(25, $metadata['evolutionDifference']); - $this->assertEquals(50, $metadata['evolutionTotal']); - - $report = $this->generateMoverAndShaker(25, 50); - $metadata = $report->getAllTableMetadata(); - - $this->assertEquals(50, $metadata['lastTotalValue']); - $this->assertEquals(25, $metadata['totalValue']); - $this->assertEquals(-25, $metadata['evolutionDifference']); - $this->assertEquals(-50, $metadata['evolutionTotal']); - } - - public function test_generateMoversAndShakers_ParameterCalculation() - { - $report = $this->generateMoverAndShaker(3000, 50); // evolution of 5900% - $metadata = $report->getAllTableMetadata(); - - $this->assertEquals(6380, $metadata['minGrowthPercentPositive']); - $this->assertEquals(-70, $metadata['minGrowthPercentNegative']); - $this->assertEquals(1, $metadata['minMoversPercent']); - $this->assertEquals(10, $metadata['minNewPercent']); - $this->assertEquals(8, $metadata['minDisappearedPercent']); - - $report = $this->generateMoverAndShaker(300, 100); - $metadata = $report->getAllTableMetadata(); - - $this->assertEquals(240, $metadata['minGrowthPercentPositive']); - $this->assertEquals(-70, $metadata['minGrowthPercentNegative']); - $this->assertEquals(1, $metadata['minMoversPercent']); - $this->assertEquals(6, $metadata['minNewPercent']); - $this->assertEquals(8, $metadata['minDisappearedPercent']); - - $report = $this->generateMoverAndShaker(225, 150); - $metadata = $report->getAllTableMetadata(); - - $this->assertEquals(70, $metadata['minGrowthPercentPositive']); - $this->assertEquals(-70, $metadata['minGrowthPercentNegative']); - $this->assertEquals(1, $metadata['minMoversPercent']); - $this->assertEquals(5, $metadata['minNewPercent']); - $this->assertEquals(7, $metadata['minDisappearedPercent']); - - $report = $this->generateMoverAndShaker(300, 600); - $metadata = $report->getAllTableMetadata(); - - $this->assertEquals(70, $metadata['minGrowthPercentPositive']); - $this->assertEquals(-70, $metadata['minGrowthPercentNegative']); - $this->assertEquals(1, $metadata['minMoversPercent']); - $this->assertEquals(5, $metadata['minNewPercent']); - $this->assertEquals(7, $metadata['minDisappearedPercent']); - - // make sure to force a change of at least 2 visits in all rows if total is soooo low - $report = $this->generateMoverAndShaker(25, 50); - $metadata = $report->getAllTableMetadata(); - - $this->assertEquals(70, $metadata['minGrowthPercentPositive']); - $this->assertEquals(-70, $metadata['minGrowthPercentNegative']); - $this->assertEquals(8, $metadata['minMoversPercent']); - $this->assertEquals(8, $metadata['minNewPercent']); - $this->assertEquals(8, $metadata['minDisappearedPercent']); - - // make sure to force a change of at least 2 visits - $report = $this->generateMoverAndShaker(75, 150); - $metadata = $report->getAllTableMetadata(); - - $this->assertEquals(70, $metadata['minGrowthPercentPositive']); - $this->assertEquals(-70, $metadata['minGrowthPercentNegative']); - $this->assertEquals(3, $metadata['minMoversPercent']); - $this->assertEquals(5, $metadata['minNewPercent']); - $this->assertEquals(7, $metadata['minDisappearedPercent']); - - // make sure no division by zero issue - $report = $this->generateMoverAndShaker(0, 150); - $metadata = $report->getAllTableMetadata(); - - $this->assertEquals(120, $metadata['minGrowthPercentPositive']); - $this->assertEquals(-120, $metadata['minGrowthPercentNegative']); - $this->assertEquals(1, $metadata['minMoversPercent']); - $this->assertEquals(5, $metadata['minNewPercent']); - $this->assertEquals(7, $metadata['minDisappearedPercent']); - } - - private function generateMoverAndShaker($totalValue, $lastTotalValue, $orderBy = null, $limitIncreaser = 99, $limitDecreaser = 99) - { - if (is_null($orderBy)) { - $orderBy = InsightReport::ORDER_BY_ABSOLUTE; - } - - $reportMetadata = array('name' => 'TestReport', 'metrics' => array('nb_visits' => 'Visits')); - - $report = $this->insightReport->generateMoverAndShaker( - $reportMetadata, 'day', '2012-12-12', '2012-12-11', 'nb_visits', $this->currentTable, $this->pastTable, - $totalValue, $lastTotalValue, $orderBy, $limitIncreaser, $limitDecreaser); - - return $report; - } - - private function generateInsight($minMoversPercent, $minNewPercent, $minDisappearedPercent, $minGrowthPercentPositive, $minGrowthPercentNegative, $orderBy = null, $limitIncreaser = 99, $limitDecreaser = 99) - { - if (is_null($orderBy)) { - $orderBy = InsightReport::ORDER_BY_ABSOLUTE; - } - - $reportMetadata = array('name' => 'TestReport', 'metrics' => array('nb_visits' => 'Visits')); - - $report = $this->insightReport->generateInsight( - $reportMetadata, 'day', '2012-12-12', '2012-12-11', 'nb_visits', $this->currentTable, $this->pastTable, - $totalValue = 200, $minMoversPercent, $minNewPercent, $minDisappearedPercent, - $minGrowthPercentPositive, $minGrowthPercentNegative, $orderBy, $limitIncreaser, $limitDecreaser); - - return $report; - } - - private function assertOrder(DataTable $table, $expectedOrder) - { - $this->assertEquals($expectedOrder, $table->getColumn('label')); - $this->assertEquals(count($expectedOrder), $table->getRowsCount()); - } -} diff --git a/plugins/Insights/tests/Integration/ApiTest.php b/plugins/Insights/tests/Integration/ApiTest.php new file mode 100644 index 0000000000..356bc769de --- /dev/null +++ b/plugins/Insights/tests/Integration/ApiTest.php @@ -0,0 +1,269 @@ +api = API::getInstance(); + } + + /** + * '/Mover1' => 2, +8 // 400% + * '/Old1' => 9, -9 // -100% + * '/Mover2' => 24, -11 // -50% + * '/Mover3' => 21, -1 // -5% + * '/Old2' => 3 -3 // -100% + * '/New1', +5 // 100% + * '/New2' +2 // 100% + */ + public function test_getInsights_ShouldReturnCorrectMetadata() + { + $insights = $this->requestInsights(array()); + $metadata = $insights->getAllTableMetadata(); + + $expectedMetadata = array( + 'reportName' => 'Page URLs', + 'metricName' => 'Unique Pageviews', + 'date' => self::$fixture->date1, + 'lastDate' => self::$fixture->date2, + 'period' => 'day', + 'orderBy' => 'absolute', + 'metric' => 'nb_visits', + 'totalValue' => 50, + 'minChangeMovers' => 1, + 'minIncreaseNew' => 1, + 'minDecreaseDisappeared' => 1, + 'minGrowthPercentPositive' => 20, + 'minGrowthPercentNegative' => -20, + 'minMoversPercent' => 2, + 'minNewPercent' => 2, + 'minDisappearedPercent' => 2, + 'lastTotalValue' => 59, + 'evolutionTotal' => -15.3, + 'evolutionDifference' => -9 + ); + + $this->assertInternalType('array', $metadata['report']); + $this->assertEquals('Actions', $metadata['report']['module']); + $this->assertEquals('getPageUrls', $metadata['report']['action']); + unset($metadata['report']); + unset($metadata['totals']); + + $this->assertEquals($expectedMetadata, $metadata); + } + + public function test_getInsights_ShouldGoBackInPastDependingOnComparedToParameter() + { + $insights = $this->requestInsights(array('comparedToXPeriods' => 3)); + + $metadata = $insights->getAllTableMetadata(); + + $this->assertEquals('2010-12-11', $metadata['lastDate']); + } + + public function test_getInsights_ShouldGoBackInPastDependingOnPeriod() + { + $insights = $this->requestInsights(array('period' => 'month')); + + $metadata = $insights->getAllTableMetadata(); + + $this->assertEquals('2010-11-14', $metadata['lastDate']); + } + + public function test_getInsights_ShouldReturnAllRowsIfMinValuesArelow() + { + $insights = $this->requestInsights(array('minImpactPercent' => 0, 'minGrowthPercent' => 1)); + + $expectedLabels = array( + '/Mover1', + '/New1', + '/New2', + '/Mover2', + '/Old1', + '/Old2', + '/Mover3' + ); + $this->assertRows($expectedLabels, $insights); + } + + public function test_getInsights_ShouldReturnReturnNothingIfminImpactPercentIsTooHigh() + { + $insights = $this->requestInsights(array('minImpactPercent' => 10000, 'minGrowthPercent' => 0)); + + $this->assertRows(array(), $insights); + } + + public function test_getInsights_ShouldReturnReturnNothingIfMinGrowthIsHigh() + { + $insights = $this->requestInsights(array('minImpactPercent' => 0, 'minGrowthPercent' => 10000)); + + $this->assertRows(array(), $insights); + } + + public function test_getInsights_ShouldOrderAbsoluteByDefault() + { + $insights = $this->requestInsights(array('minImpactPercent' => 0, 'minGrowthPercent' => 0)); + + $expectedLabels = array( + '/Mover1', + '/New1', + '/New2', + '/Mover2', + '/Old1', + '/Old2', + '/Mover3' + ); + $this->assertRows($expectedLabels, $insights); + } + + public function test_getInsights_ShouldBeAbleToOrderRelative() + { + $insights = $this->requestInsights(array('minImpactPercent' => 0, 'minGrowthPercent' => 0, 'orderBy' => 'relative')); + + $expectedLabels = array( + '/Mover1', + '/New1', + '/New2', + '/Old1', + '/Old2', + '/Mover2', + '/Mover3' + ); + $this->assertRows($expectedLabels, $insights); + } + + public function test_getInsights_ShouldBeAbleToOrderByImportance() + { + $insights = $this->requestInsights(array('minImpactPercent' => 0, 'minGrowthPercent' => 0, 'orderBy' => 'importance')); + + $expectedLabels = array( + '/Mover2', + '/Old1', + '/Mover1', + '/New1', + '/Old2', + '/New2', + '/Mover3' + ); + $this->assertRows($expectedLabels, $insights); + } + + public function test_getInsights_ShouldApplyTheLimit() + { + $insights = $this->requestInsights(array('limitIncreaser' => 1, 'limitDecreaser' => 1)); + + $expectedLabels = array( + '/Mover1', + '/Mover2' + ); + $this->assertRows($expectedLabels, $insights); + } + + public function test_getInsights_ShouldBeAbleToShowOnlyMovers() + { + $insights = $this->requestInsights(array('minImpactPercent' => 0, 'minGrowthPercent' => 0, 'filterBy' => 'movers')); + + $expectedLabels = array( + '/Mover1', + '/Mover2', + '/Mover3' + ); + $this->assertRows($expectedLabels, $insights); + } + + public function test_getInsights_ShouldBeAbleToShowOnlyNew() + { + $insights = $this->requestInsights(array('minImpactPercent' => 0, 'minGrowthPercent' => 0, 'filterBy' => 'new')); + + $expectedLabels = array( + '/New1', + '/New2' + ); + $this->assertRows($expectedLabels, $insights); + } + + public function test_getInsights_ShouldBeAbleToShowOnlyDisappeared() + { + $insights = $this->requestInsights(array('minImpactPercent' => 0, 'minGrowthPercent' => 0, 'filterBy' => 'disappeared')); + + $expectedLabels = array( + '/Old1', + '/Old2' + ); + $this->assertRows($expectedLabels, $insights); + } + + public function test_canGenerateInsights() + { + $this->assertTrue($this->api->canGenerateInsights('2012-12-12', 'day')); + $this->assertTrue($this->api->canGenerateInsights('2012-12-12', 'week')); + $this->assertTrue($this->api->canGenerateInsights('2012-12-12', 'month')); + + $this->assertFalse($this->api->canGenerateInsights('last10', 'day')); + $this->assertFalse($this->api->canGenerateInsights('2012-11-11,2012-12-12', 'range')); + } + + private function requestInsights($requestParams) + { + $params = array( + 'method' => 'Insights.getInsights', + 'idSite' => self::$fixture->idSite, + 'date' => self::$fixture->date1, + 'period' => 'day', + 'format' => 'original', + 'reportUniqueId' => 'Actions_getPageUrls', + ); + + if (!empty($requestParams)) { + foreach ($requestParams as $key => $value) { + $params[$key] = $value; + } + } + + $request = new ApiRequest($params); + return $request->process(); + } + + private function assertRows($expectedLabels, DataTable $dataTable) + { + $this->assertEquals($expectedLabels, $dataTable->getColumn('label')); + $this->assertEquals(count($expectedLabels), $dataTable->getRowsCount()); + } +} + +ApiTest::$fixture = new SomeVisitsDifferentPathsOnTwoDays(); \ No newline at end of file diff --git a/plugins/Insights/tests/Integration/ModelTest.php b/plugins/Insights/tests/Integration/ModelTest.php new file mode 100644 index 0000000000..94ff52201d --- /dev/null +++ b/plugins/Insights/tests/Integration/ModelTest.php @@ -0,0 +1,189 @@ +model = new Model(); + } + + public function test_requestReport_shouldReturnTheDataTableOfTheReport_AndContainReportTotals() + { + $idSite = self::$fixture->idSite; + $date = self::$fixture->date1; + $metric = 'nb_visits'; + + $table = $this->model->requestReport($idSite, 'day', $date, 'Actions_getPageUrls', $metric, false); + + $this->assertEquals(5, $table->getRowsCount()); + + $totals = $table->getMetadata('totals'); + $this->assertEquals(50, $totals[$metric]); + } + + public function test_getReportByUniqueId_shouldReturnReport() + { + $report = $this->model->getReportByUniqueId(self::$fixture->idSite, 'Actions_getPageUrls'); + + $this->assertEquals('Actions', $report['module']); + $this->assertEquals('getPageUrls', $report['action']); + } + + public function test_getLastDate_shouldReturnTheLastDateDependingOnPeriod() + { + $date = $this->model->getLastDate('2012-12-12', 'day', 1); + $this->assertEquals('2012-12-11', $date); + + $date = $this->model->getLastDate('2012-12-12', 'week', 1); + $this->assertEquals('2012-12-05', $date); + + $date = $this->model->getLastDate('2012-12-03', 'week', 1); + $this->assertEquals('2012-11-26', $date); + + $date = $this->model->getLastDate('2012-12-02', 'week', 1); + $this->assertEquals('2012-11-25', $date); + + $date = $this->model->getLastDate('2012-12-12', 'month', 1); + $this->assertEquals('2012-11-12', $date); + + $date = $this->model->getLastDate('2012-12-01', 'month', 1); + $this->assertEquals('2012-11-01', $date); + } + + public function test_getLastDate_shouldReturnTheLastDateDependingOnComparedTo() + { + $date = $this->model->getLastDate('2012-12-12', 'day', 1); + $this->assertEquals('2012-12-11', $date); + + $date = $this->model->getLastDate('2012-12-12', 'day', 2); + $this->assertEquals('2012-12-10', $date); + + $date = $this->model->getLastDate('2012-12-12', 'day', 7); + $this->assertEquals('2012-12-05', $date); + } + + public function test_getMetricTotalValue_shouldReturnTheTotalValueFromMetadata() + { + $table = $this->getTableWithTotal('17'); + + $total = $this->model->getMetricTotalValue($table, 'nb_visits'); + + $this->assertEquals(17, $total); + $this->assertInternalType('integer', $total); + } + + public function test_getMetricTotalValue_shouldReturnZeroIfMetricHasNoTotal() + { + $table = new DataTable(); + $table->setMetadata('totals', array('nb_visits' => '17')); + + $total = $this->model->getMetricTotalValue($table, 'unknown_metric'); + + $this->assertEquals(0, $total); + } + + /** + * @expectedException \Exception + */ + public function test_getLastDate_shouldThrowExceptionIfNotPossibleToGetLastDate() + { + $this->model->getLastDate('last10', 'day', 1); + } + + /** + * @expectedException \Exception + */ + public function test_getLastDate_shouldThrowExceptionInCaseOfRangePeriod() + { + $this->model->getLastDate('2012-11-11,2012-12-12', 'range', 1); + } + + public function test_getTotalValue_shouldCalculateTotals() + { + $total = $this->model->getTotalValue(self::$fixture->idSite, 'day', self::$fixture->date1, 'nb_visits', false); + $this->assertEquals(50, $total); + + $total = $this->model->getTotalValue(self::$fixture->idSite, 'day', self::$fixture->date2, 'nb_visits', false); + $this->assertEquals(59, $total); + } + + public function test_getTotalValue_shouldCalculateTotalsAndApplySegment() + { + $total = $this->model->getTotalValue(self::$fixture->idSite, 'day', self::$fixture->date1, 'nb_visits', 'visitIp==156.15.13.1'); + $this->assertEquals(1, $total); + } + + /** + * @expectedException \Exception + */ + public function test_getTotalValue_shouldReturnZero_IfColumnDoesNotExist() + { + $this->model->getTotalValue(self::$fixture->idSite, 'day', self::$fixture->date1, 'unknown_ColUmn', false); + } + + public function test_getRelevantTotalValue_shouldReturnTotalValue_IfMetricTotalIsHighEnough() + { + $table = $this->getTableWithTotal(25); + $total = $this->model->getRelevantTotalValue($table, 'nb_visits', 50); + $this->assertEquals(50, $total); + } + + public function test_getRelevantTotalValue_shouldReturnMetricTotal_IfMetricTotalIsHigherThanTotalValue() + { + $table = $this->getTableWithTotal(80); + $total = $this->model->getRelevantTotalValue($table, 'nb_visits', 50); + $this->assertEquals(80, $total); + } + + public function test_getRelevantTotalValue_shouldReturnMetricTotal_IfMetricTotalIsTooLow() + { + $table = $this->getTableWithTotal(24); + $total = $this->model->getRelevantTotalValue($table, 'nb_visits', 50); + $this->assertEquals(24, $total); + + $table = $this->getTableWithTotal(0); + $total = $this->model->getRelevantTotalValue($table, 'nb_visits', 50); + $this->assertEquals(0, $total); + } + + private function getTableWithTotal($total) + { + $table = new DataTable(); + $table->setMetadata('totals', array('nb_visits' => $total)); + return $table; + } + +} + +ModelTest::$fixture = new SomeVisitsDifferentPathsOnTwoDays(); \ No newline at end of file diff --git a/plugins/Insights/tests/ModelTest.php b/plugins/Insights/tests/ModelTest.php deleted file mode 100644 index 94ff52201d..0000000000 --- a/plugins/Insights/tests/ModelTest.php +++ /dev/null @@ -1,189 +0,0 @@ -model = new Model(); - } - - public function test_requestReport_shouldReturnTheDataTableOfTheReport_AndContainReportTotals() - { - $idSite = self::$fixture->idSite; - $date = self::$fixture->date1; - $metric = 'nb_visits'; - - $table = $this->model->requestReport($idSite, 'day', $date, 'Actions_getPageUrls', $metric, false); - - $this->assertEquals(5, $table->getRowsCount()); - - $totals = $table->getMetadata('totals'); - $this->assertEquals(50, $totals[$metric]); - } - - public function test_getReportByUniqueId_shouldReturnReport() - { - $report = $this->model->getReportByUniqueId(self::$fixture->idSite, 'Actions_getPageUrls'); - - $this->assertEquals('Actions', $report['module']); - $this->assertEquals('getPageUrls', $report['action']); - } - - public function test_getLastDate_shouldReturnTheLastDateDependingOnPeriod() - { - $date = $this->model->getLastDate('2012-12-12', 'day', 1); - $this->assertEquals('2012-12-11', $date); - - $date = $this->model->getLastDate('2012-12-12', 'week', 1); - $this->assertEquals('2012-12-05', $date); - - $date = $this->model->getLastDate('2012-12-03', 'week', 1); - $this->assertEquals('2012-11-26', $date); - - $date = $this->model->getLastDate('2012-12-02', 'week', 1); - $this->assertEquals('2012-11-25', $date); - - $date = $this->model->getLastDate('2012-12-12', 'month', 1); - $this->assertEquals('2012-11-12', $date); - - $date = $this->model->getLastDate('2012-12-01', 'month', 1); - $this->assertEquals('2012-11-01', $date); - } - - public function test_getLastDate_shouldReturnTheLastDateDependingOnComparedTo() - { - $date = $this->model->getLastDate('2012-12-12', 'day', 1); - $this->assertEquals('2012-12-11', $date); - - $date = $this->model->getLastDate('2012-12-12', 'day', 2); - $this->assertEquals('2012-12-10', $date); - - $date = $this->model->getLastDate('2012-12-12', 'day', 7); - $this->assertEquals('2012-12-05', $date); - } - - public function test_getMetricTotalValue_shouldReturnTheTotalValueFromMetadata() - { - $table = $this->getTableWithTotal('17'); - - $total = $this->model->getMetricTotalValue($table, 'nb_visits'); - - $this->assertEquals(17, $total); - $this->assertInternalType('integer', $total); - } - - public function test_getMetricTotalValue_shouldReturnZeroIfMetricHasNoTotal() - { - $table = new DataTable(); - $table->setMetadata('totals', array('nb_visits' => '17')); - - $total = $this->model->getMetricTotalValue($table, 'unknown_metric'); - - $this->assertEquals(0, $total); - } - - /** - * @expectedException \Exception - */ - public function test_getLastDate_shouldThrowExceptionIfNotPossibleToGetLastDate() - { - $this->model->getLastDate('last10', 'day', 1); - } - - /** - * @expectedException \Exception - */ - public function test_getLastDate_shouldThrowExceptionInCaseOfRangePeriod() - { - $this->model->getLastDate('2012-11-11,2012-12-12', 'range', 1); - } - - public function test_getTotalValue_shouldCalculateTotals() - { - $total = $this->model->getTotalValue(self::$fixture->idSite, 'day', self::$fixture->date1, 'nb_visits', false); - $this->assertEquals(50, $total); - - $total = $this->model->getTotalValue(self::$fixture->idSite, 'day', self::$fixture->date2, 'nb_visits', false); - $this->assertEquals(59, $total); - } - - public function test_getTotalValue_shouldCalculateTotalsAndApplySegment() - { - $total = $this->model->getTotalValue(self::$fixture->idSite, 'day', self::$fixture->date1, 'nb_visits', 'visitIp==156.15.13.1'); - $this->assertEquals(1, $total); - } - - /** - * @expectedException \Exception - */ - public function test_getTotalValue_shouldReturnZero_IfColumnDoesNotExist() - { - $this->model->getTotalValue(self::$fixture->idSite, 'day', self::$fixture->date1, 'unknown_ColUmn', false); - } - - public function test_getRelevantTotalValue_shouldReturnTotalValue_IfMetricTotalIsHighEnough() - { - $table = $this->getTableWithTotal(25); - $total = $this->model->getRelevantTotalValue($table, 'nb_visits', 50); - $this->assertEquals(50, $total); - } - - public function test_getRelevantTotalValue_shouldReturnMetricTotal_IfMetricTotalIsHigherThanTotalValue() - { - $table = $this->getTableWithTotal(80); - $total = $this->model->getRelevantTotalValue($table, 'nb_visits', 50); - $this->assertEquals(80, $total); - } - - public function test_getRelevantTotalValue_shouldReturnMetricTotal_IfMetricTotalIsTooLow() - { - $table = $this->getTableWithTotal(24); - $total = $this->model->getRelevantTotalValue($table, 'nb_visits', 50); - $this->assertEquals(24, $total); - - $table = $this->getTableWithTotal(0); - $total = $this->model->getRelevantTotalValue($table, 'nb_visits', 50); - $this->assertEquals(0, $total); - } - - private function getTableWithTotal($total) - { - $table = new DataTable(); - $table->setMetadata('totals', array('nb_visits' => $total)); - return $table; - } - -} - -ModelTest::$fixture = new SomeVisitsDifferentPathsOnTwoDays(); \ No newline at end of file diff --git a/plugins/Insights/tests/Unit/BaseUnitTest.php b/plugins/Insights/tests/Unit/BaseUnitTest.php new file mode 100644 index 0000000000..97c2c78580 --- /dev/null +++ b/plugins/Insights/tests/Unit/BaseUnitTest.php @@ -0,0 +1,50 @@ +assertEquals($expectedOrder, $this->table->getColumn('label')); + $this->assertEquals(count($expectedOrder), $this->table->getRowsCount()); + } + + protected function assertColumnValues($rowsWithValues) + { + $index = 0; + foreach ($this->table->getRows() as $row) { + $rowToCheck = $rowsWithValues[$index]; + foreach ($rowToCheck as $columnToCheck => $expectedValue) { + $actualValue = $row->getColumn($columnToCheck); + $this->assertEquals($expectedValue, $actualValue, "$columnToCheck in row $index does not match assumed $actualValue is $expectedValue"); + } + $index++; + } + + $this->assertEquals(count($rowsWithValues), $this->table->getRowsCount()); + } + +} diff --git a/plugins/Insights/tests/Unit/FilterExcludeLowValueTest.php b/plugins/Insights/tests/Unit/FilterExcludeLowValueTest.php new file mode 100644 index 0000000000..51c0192ef6 --- /dev/null +++ b/plugins/Insights/tests/Unit/FilterExcludeLowValueTest.php @@ -0,0 +1,85 @@ +table = new DataTable(); + $this->table->addRowsFromArray(array( + array(Row::COLUMNS => array('label' => 'val1', 'growth' => 22, 'isFooBar' => false)), + array(Row::COLUMNS => array('label' => 'val2', 'growth' => 14, 'isFooBar' => true)), + array(Row::COLUMNS => array('label' => 'val3', 'growth' => 18, 'isFooBar' => false)), + array(Row::COLUMNS => array('label' => 'val4', 'growth' => 20, 'isFooBar' => true)), + array(Row::COLUMNS => array('label' => 'val5', 'growth' => 22, 'isFooBar' => true)), + array(Row::COLUMNS => array('label' => 'val6', 'growth' => 25, 'isFooBar' => true)), + array(Row::COLUMNS => array('label' => 'val7', 'growth' => 17, 'isFooBar' => false)), + array(Row::COLUMNS => array('label' => 'val8', 'growth' => 20, 'isFooBar' => false)), + array(Row::COLUMNS => array('label' => 'val9', 'growth' => 0, 'isFooBar' => false)), + array(Row::COLUMNS => array('label' => 'val10', 'growth' => 15, 'isFooBar' => false)), + array(Row::COLUMNS => array('label' => 'val11', 'growth' => 16, 'isFooBar' => true)) + )); + } + + public function testShouldNotRemoveAnyIfMinValueIsZero() + { + $rowsCountBefore = $this->table->getRowsCount(); + $this->assertGreaterThan(0, $rowsCountBefore); + + $this->excludeLowValues(0); + + $this->assertSame($rowsCountBefore, $this->table->getRowsCount()); + } + + public function testShouldKeepAllRowsHavingHigherGrowth() + { + $this->excludeLowValues(15); + + $this->assertOrder(array('val1', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8', 'val10', 'val11')); + } + + public function testShouldKeepRowsIfTheyHaveGivenMinGrowth() + { + $this->excludeLowValues(22); + + $this->assertOrder(array('val1', 'val5', 'val6')); + } + + public function testShouldRemoveAllIfMinValueIsTooHigh() + { + $this->excludeLowValues(99); + + $this->assertOrder(array()); + } + + public function testShouldRemoveValuesOnlyIfColumnToCheckIsTrue() + { + $this->excludeLowValues(21, 'isFooBar'); + + $this->assertOrder(array('val1', 'val3', 'val5', 'val6', 'val7', 'val8', 'val9', 'val10')); + } + + private function excludeLowValues($minimumValue, $columnToCheck = null) + { + $filter = new ExcludeLowValue($this->table, 'growth', $minimumValue, $columnToCheck); + $filter->filter($this->table); + } + +} diff --git a/plugins/Insights/tests/Unit/FilterInsightTest.php b/plugins/Insights/tests/Unit/FilterInsightTest.php new file mode 100644 index 0000000000..67c216b192 --- /dev/null +++ b/plugins/Insights/tests/Unit/FilterInsightTest.php @@ -0,0 +1,226 @@ +currentTable = new DataTable(); + $this->currentTable->addRowsFromArray(array( + array(Row::COLUMNS => array('label' => 'val1', 'nb_visits' => 120)), + array(Row::COLUMNS => array('label' => 'val2', 'nb_visits' => 70)), + array(Row::COLUMNS => array('label' => 'val3', 'nb_visits' => 90)), + array(Row::COLUMNS => array('label' => 'val4', 'nb_visits' => 99)), + array(Row::COLUMNS => array('label' => 'val5', 'nb_visits' => 0)), + array(Row::COLUMNS => array('label' => 'val6', 'nb_visits' => 0)), + array(Row::COLUMNS => array('label' => 'val7', 'nb_visits' => 134)), + array(Row::COLUMNS => array('label' => 'val8', 'nb_visits' => 100)), + array(Row::COLUMNS => array('label' => 'val9', 'nb_visits' => 7)), + array(Row::COLUMNS => array('label' => 'val10', 'nb_visits' => 89)) + )); + + $this->pastTable = new DataTable(); + $this->pastTable->addRowsFromArray(array( + array(Row::COLUMNS => array('label' => 'val1', 'nb_visits' => 102)), + array(Row::COLUMNS => array('label' => 'val102', 'nb_visits' => 29)), + array(Row::COLUMNS => array('label' => 'val4', 'nb_visits' => 120)), + array(Row::COLUMNS => array('label' => 'val6', 'nb_visits' => 313)), + array(Row::COLUMNS => array('label' => 'val109', 'nb_visits' => 0)), + array(Row::COLUMNS => array('label' => 'val8', 'nb_visits' => 140)), + array(Row::COLUMNS => array('label' => 'val9', 'nb_visits' => 72)), + array(Row::COLUMNS => array('label' => 'val107', 'nb_visits' => 415)), + array(Row::COLUMNS => array('label' => 'val10', 'nb_visits' => 0)) + )); + + $this->table = new DataTable(); + } + + public function testConsiderOnlyMovers() + { + $this->applyInsight($considerMovers = true, $considerNew = false, $considerDisappeared = false); + + $this->assertOrder(array('val1', 'val4', 'val6', 'val8', 'val9', 'val10')); + } + + public function testConsiderOnlyNew() + { + $this->applyInsight($considerMovers = false, $considerNew = true, $considerDisappeared = false); + + $this->assertOrder(array('val2', 'val3', 'val5', 'val7')); + } + + public function testConsiderOnlyDisappeared() + { + $this->applyInsight($considerMovers = false, $considerNew = false, $considerDisappeared = true); + + $this->assertOrder(array('val102', 'val109', 'val107')); + } + + public function testConsiderOnlyNewAndDisappeared() + { + $this->applyInsight($considerMovers = false, $considerNew = true, $considerDisappeared = true); + + $this->assertOrder(array('val2', 'val3', 'val5', 'val7', 'val102', 'val109', 'val107')); + } + + public function testConsiderAll() + { + $this->applyInsightConsiderAll(); + + $this->assertSame(13, $this->table->getRowsCount()); + } + + public function testShouldDetectCorrectOldAndNewValue() + { + $this->applyInsightConsiderAll(); + + $values = array( + array('label' => 'val1', 'value_old' => 102, 'value_new' => 120), + array('label' => 'val2', 'value_old' => 0, 'value_new' => 70), + array('label' => 'val3', 'value_old' => 0, 'value_new' => 90), + array('label' => 'val4', 'value_old' => 120, 'value_new' => 99), + array('label' => 'val5', 'value_old' => 0, 'value_new' => 0), + array('label' => 'val6', 'value_old' => 313, 'value_new' => 0), + array('label' => 'val7', 'value_old' => 0, 'value_new' => 134), + array('label' => 'val8', 'value_old' => 140, 'value_new' => 100), + array('label' => 'val9', 'value_old' => 72, 'value_new' => 7), + array('label' => 'val10', 'value_old' => 0, 'value_new' => 89), + array('label' => 'val102', 'value_old' => 29, 'value_new' => 0), + array('label' => 'val109', 'value_old' => 0, 'value_new' => 0), + array('label' => 'val107', 'value_old' => 415, 'value_new' => 0), + ); + + $this->assertColumnValues($values); + } + + public function testShouldDetectWhetherColumGrownOrNot() + { + $this->applyInsightConsiderAll(); + + $values = array( + array('label' => 'val1', 'grown' => true), + array('label' => 'val2', 'grown' => true), + array('label' => 'val3', 'grown' => true), + array('label' => 'val4', 'grown' => false), + array('label' => 'val5', 'grown' => true), + array('label' => 'val6', 'grown' => false), + array('label' => 'val7', 'grown' => true), + array('label' => 'val8', 'grown' => false), + array('label' => 'val9', 'grown' => false), + array('label' => 'val10', 'grown' => true), + array('label' => 'val102', 'grown' => false), + array('label' => 'val109', 'grown' => true), + array('label' => 'val107', 'grown' => false), + ); + + $this->assertColumnValues($values); + } + + public function testShouldDetectWhetherRowIsNewMoverOrDisappeared() + { + $this->applyInsightConsiderAll(); + + $values = array( + array('label' => 'val1', 'isNew' => false, 'isMover' => true, 'isDisappeared' => false), + array('label' => 'val2', 'isNew' => true, 'isMover' => false, 'isDisappeared' => false), + array('label' => 'val3', 'isNew' => true, 'isMover' => false, 'isDisappeared' => false), + array('label' => 'val4', 'isNew' => false, 'isMover' => true, 'isDisappeared' => false), + array('label' => 'val5', 'isNew' => true, 'isMover' => false, 'isDisappeared' => false), + array('label' => 'val6', 'isNew' => false, 'isMover' => true, 'isDisappeared' => false), + array('label' => 'val7', 'isNew' => true, 'isMover' => false, 'isDisappeared' => false), + array('label' => 'val8', 'isNew' => false, 'isMover' => true, 'isDisappeared' => false), + array('label' => 'val9', 'isNew' => false, 'isMover' => true, 'isDisappeared' => false), + array('label' => 'val10', 'isNew' => false, 'isMover' => true, 'isDisappeared' => false), + array('label' => 'val102', 'isNew' => false, 'isMover' => false, 'isDisappeared' => true), + array('label' => 'val109', 'isNew' => false, 'isMover' => false, 'isDisappeared' => true), + array('label' => 'val107', 'isNew' => false, 'isMover' => false, 'isDisappeared' => true) + ); + + $this->assertColumnValues($values); + } + + public function testShouldCalculateDifferenceAndGrowthPercentage() + { + $this->applyInsightConsiderAll(); + + $values = array( + array('label' => 'val1', 'growth_percent' => '17.6%', 'growth_percent_numeric' => '17.6', 'difference' => 18), + array('label' => 'val2', 'growth_percent' => '100%', 'growth_percent_numeric' => '100', 'difference' => 70), + array('label' => 'val3', 'growth_percent' => '100%', 'growth_percent_numeric' => '100', 'difference' => 90), + array('label' => 'val4', 'growth_percent' => '-17.5%', 'growth_percent_numeric' => '-17.5', 'difference' => -21), + array('label' => 'val5', 'growth_percent' => '0%', 'growth_percent_numeric' => '0', 'difference' => 0), + array('label' => 'val6', 'growth_percent' => '-100%', 'growth_percent_numeric' => '-100', 'difference' => -313), + array('label' => 'val7', 'growth_percent' => '100%', 'growth_percent_numeric' => '100', 'difference' => 134), + array('label' => 'val8', 'growth_percent' => '-28.6%', 'growth_percent_numeric' => '-28.6', 'difference' => -40), + array('label' => 'val9', 'growth_percent' => '-90.3%', 'growth_percent_numeric' => '-90.3', 'difference' => -65), + array('label' => 'val10', 'growth_percent' => '100%', 'growth_percent_numeric' => '100', 'difference' => 89), + array('label' => 'val102', 'growth_percent' => '-100%', 'growth_percent_numeric' => '-100', 'difference' => -29), + array('label' => 'val109', 'growth_percent' => '0%', 'growth_percent_numeric' => '0', 'difference' => 0), + array('label' => 'val107', 'growth_percent' => '-100%', 'growth_percent_numeric' => '-100', 'difference' => -415), + ); + + $this->assertColumnValues($values); + } + + public function testShouldCalculateImporance() + { + $this->applyInsightConsiderAll(); + + $values = array( + array('label' => 'val1', 'importance' => 18), + array('label' => 'val2', 'importance' => 70), + array('label' => 'val3', 'importance' => 90), + array('label' => 'val4', 'importance' => 21), + array('label' => 'val5', 'importance' => 0), + array('label' => 'val6', 'importance' => 313), + array('label' => 'val7', 'importance' => 134), + array('label' => 'val8', 'importance' => 40), + array('label' => 'val9', 'importance' => 65), + array('label' => 'val10', 'importance' => 89), + array('label' => 'val102', 'importance' => 29), + array('label' => 'val109', 'importance' => 0), + array('label' => 'val107', 'importance' => 415), + ); + + $this->assertColumnValues($values); + } + + private function applyInsight($considerMovers, $considerNew, $considerDisappeared) + { + $filter = new Insight($this->table, $this->currentTable, $this->pastTable, 'nb_visits', $considerMovers, $considerNew, $considerDisappeared); + $filter->filter($this->table); + } + + private function applyInsightConsiderAll() + { + $this->applyInsight($considerMovers = true, $considerNew = true, $considerDisappeared = true); + } + +} diff --git a/plugins/Insights/tests/Unit/FilterLimitTest.php b/plugins/Insights/tests/Unit/FilterLimitTest.php new file mode 100644 index 0000000000..6f6d703b0a --- /dev/null +++ b/plugins/Insights/tests/Unit/FilterLimitTest.php @@ -0,0 +1,81 @@ +table = new DataTable(); + $this->table->addRowsFromArray(array( + array(Row::COLUMNS => array('label' => 'pos1', 'growth' => 12)), + array(Row::COLUMNS => array('label' => 'pos2', 'growth' => 7)), + array(Row::COLUMNS => array('label' => 'neg1', 'growth' => -9)), + array(Row::COLUMNS => array('label' => 'pos3', 'growth' => 10)), + array(Row::COLUMNS => array('label' => 'neg2', 'growth' => -11)), + array(Row::COLUMNS => array('label' => 'neg3', 'growth' => -13)), + array(Row::COLUMNS => array('label' => 'pos4', 'growth' => 9)), + array(Row::COLUMNS => array('label' => 'pos5', 'growth' => 10)), + array(Row::COLUMNS => array('label' => 'neg4', 'growth' => -7)), + array(Row::COLUMNS => array('label' => 'neg5', 'growth' => -8)) + )); + } + + public function testFilterAll() + { + $this->applyLimit($limitIncreaser = 0, $limitDecreaser = 0); + + $this->assertOrder(array()); + } + + public function testNoDescreaser() + { + $this->applyLimit($limitIncreaser = 4, $limitDecreaser = 0); + + $this->assertOrder(array('pos1', 'pos2', 'pos3', 'pos4')); + } + + public function testNoIncreaser() + { + $this->applyLimit($limitIncreaser = 0, $limitDecreaser = 4); + + $this->assertOrder(array('neg1', 'neg2', 'neg3', 'neg4')); + } + + public function testShouldKeepOrderOfRows() + { + $this->applyLimit($limitIncreaser = 3, $limitDecreaser = 2); + + $this->assertOrder(array('pos1', 'pos2', 'neg1', 'pos3', 'neg2')); + } + + public function testShouldReturnAllRowsIfLimitIsHighEnough() + { + $this->applyLimit($limitIncreaser = 99, $limitDecreaser = 99); + + $this->assertOrder(array('pos1', 'pos2', 'neg1', 'pos3', 'neg2', 'neg3', 'pos4', 'pos5', 'neg4', 'neg5')); + } + + private function applyLimit($limitIncrease, $limitDecrease) + { + $filter = new Limit($this->table, 'growth', $limitIncrease, $limitDecrease); + $filter->filter($this->table); + } + +} diff --git a/plugins/Insights/tests/Unit/FilterMinGrowthTest.php b/plugins/Insights/tests/Unit/FilterMinGrowthTest.php new file mode 100644 index 0000000000..a53245b891 --- /dev/null +++ b/plugins/Insights/tests/Unit/FilterMinGrowthTest.php @@ -0,0 +1,91 @@ +table = new DataTable(); + $this->table->addRowsFromArray(array( + array(Row::COLUMNS => array('label' => 'pos1', 'growth' => 22)), + array(Row::COLUMNS => array('label' => 'pos2', 'growth' => 14)), + array(Row::COLUMNS => array('label' => 'neg1', 'growth' => -18)), + array(Row::COLUMNS => array('label' => 'pos3', 'growth' => 20)), + array(Row::COLUMNS => array('label' => 'neg2', 'growth' => -22)), + array(Row::COLUMNS => array('label' => 'neg3', 'growth' => -25)), + array(Row::COLUMNS => array('label' => 'pos4', 'growth' => 17)), + array(Row::COLUMNS => array('label' => 'pos5', 'growth' => 20)), + array(Row::COLUMNS => array('label' => 'pos6', 'growth' => 0)), + array(Row::COLUMNS => array('label' => 'neg4', 'growth' => -15)), + array(Row::COLUMNS => array('label' => 'neg5', 'growth' => -16)) + )); + } + + public function testShouldNotRemoveAnyIfMinGrowthIsZero() + { + $rowsCountBefore = $this->table->getRowsCount(); + $this->assertGreaterThan(0, $rowsCountBefore); + + $this->applyMinGrowthFilter(0, 0); + + $this->assertSame($rowsCountBefore, $this->table->getRowsCount()); + } + + public function testShouldKeepAllRowsHavingHigherGrowth() + { + $this->applyMinGrowthFilter(15, -15); + + $this->assertOrder(array('pos1', 'neg1', 'pos3', 'neg2', 'neg3', 'pos4', 'pos5', 'neg4', 'neg5')); + } + + public function testShouldKeepRowsIfTheyHaveGivenMinGrowth() + { + $this->applyMinGrowthFilter(22, -22); + + $this->assertOrder(array('pos1', 'neg2', 'neg3')); + } + + public function testDifferentGrowth() + { + $this->applyMinGrowthFilter(22, -16); + $this->assertOrder(array('pos1', 'neg1', 'neg2', 'neg3', 'neg5')); + } + + public function testDifferentGrowth2() + { + $this->applyMinGrowthFilter(15, -24); + $this->assertOrder(array('pos1', 'pos3', 'neg3', 'pos4', 'pos5')); + } + + public function testShouldRemoveAllIfMinGrowthIsTooHigh() + { + $this->applyMinGrowthFilter(999, -999); + + $this->assertOrder(array()); + } + + private function applyMinGrowthFilter($minGrowthPercentPositive, $minGrowthPercentNegative) + { + $filter = new MinGrowth($this->table, 'growth', $minGrowthPercentPositive, $minGrowthPercentNegative); + $filter->filter($this->table); + } + +} diff --git a/plugins/Insights/tests/Unit/FilterOrderByTest.php b/plugins/Insights/tests/Unit/FilterOrderByTest.php new file mode 100644 index 0000000000..8239204a2f --- /dev/null +++ b/plugins/Insights/tests/Unit/FilterOrderByTest.php @@ -0,0 +1,95 @@ +table = new DataTable(); + } + + public function testOrderByShouldListAllHighestPositiveValuesFirstThenAllNegativeValuesLowestFirst() + { + $this->table->addRowsFromArray(array( + array(Row::COLUMNS => array('label' => 'pos1', 'growth' => 12)), + array(Row::COLUMNS => array('label' => 'pos2', 'growth' => 7)), + array(Row::COLUMNS => array('label' => 'neg1', 'growth' => -9)), + array(Row::COLUMNS => array('label' => 'pos3', 'growth' => 10)), + array(Row::COLUMNS => array('label' => 'neg2', 'growth' => -11)), + array(Row::COLUMNS => array('label' => 'neg3', 'growth' => -13)), + array(Row::COLUMNS => array('label' => 'pos4', 'growth' => 9)), + array(Row::COLUMNS => array('label' => 'pos5', 'growth' => 10)), + array(Row::COLUMNS => array('label' => 'pos6', 'growth' => 0)), + array(Row::COLUMNS => array('label' => 'neg4', 'growth' => -7)), + array(Row::COLUMNS => array('label' => 'neg5', 'growth' => -8)) + )); + + $this->applyOrderByFilter(); + + $this->assertOrder(array('pos1', 'pos5', 'pos3', 'pos4', 'pos2', 'pos6', 'neg3', 'neg2', 'neg1', 'neg5', 'neg4')); + } + + public function testOrderByShouldSortDependingOnNbVisitsIfColumnsHaveSameValue() + { + $this->table->addRowsFromArray(array( + array(Row::COLUMNS => array('label' => 'pos1', 'nb_visits' => 40, 'growth' => 7)), + array(Row::COLUMNS => array('label' => 'pos2', 'nb_visits' => 55, 'growth' => 7)), + array(Row::COLUMNS => array('label' => 'pos3', 'nb_visits' => 35, 'growth' => 7)), + array(Row::COLUMNS => array('label' => 'pos4', 'nb_visits' => 60, 'growth' => 7)), + array(Row::COLUMNS => array('label' => 'pos5', 'nb_visits' => 7, 'growth' => 7)), + array(Row::COLUMNS => array('label' => 'pos6', 'nb_visits' => 35, 'growth' => 7)), + array(Row::COLUMNS => array('label' => 'neg1', 'nb_visits' => 33, 'growth' => -5)), + array(Row::COLUMNS => array('label' => 'neg2', 'nb_visits' => 34, 'growth' => -5)), + array(Row::COLUMNS => array('label' => 'neg3', 'nb_visits' => 99, 'growth' => -5)), + array(Row::COLUMNS => array('label' => 'neg4', 'nb_visits' => 20, 'growth' => -5)) + )); + + $this->applyOrderByFilter(); + + $this->assertOrder(array('pos4', 'pos2', 'pos1', 'pos3', 'pos6', 'pos5', 'neg3', 'neg2', 'neg1', 'neg4')); + } + + public function testOrderByShouldSortDependingOnNbVisitsIfColumnsHaveSameValueAndNbVisitsIsNegative() + { + $this->table->addRowsFromArray(array( + array(Row::COLUMNS => array('label' => 'pos1', 'nb_visits' => -40, 'growth' => 7)), + array(Row::COLUMNS => array('label' => 'pos2', 'nb_visits' => -55, 'growth' => 7)), + array(Row::COLUMNS => array('label' => 'pos3', 'nb_visits' => -35, 'growth' => 7)), + array(Row::COLUMNS => array('label' => 'pos4', 'nb_visits' => -60, 'growth' => 7)), + array(Row::COLUMNS => array('label' => 'pos5', 'nb_visits' => -7, 'growth' => 7)), + array(Row::COLUMNS => array('label' => 'pos6', 'nb_visits' => -35, 'growth' => 7)), + array(Row::COLUMNS => array('label' => 'neg1', 'nb_visits' => -33, 'growth' => -5)), + array(Row::COLUMNS => array('label' => 'neg2', 'nb_visits' => -34, 'growth' => -5)), + array(Row::COLUMNS => array('label' => 'neg3', 'nb_visits' => -99, 'growth' => -5)), + array(Row::COLUMNS => array('label' => 'neg4', 'nb_visits' => -20, 'growth' => -5)) + )); + + $this->applyOrderByFilter(); + + $this->assertOrder(array('pos4', 'pos2', 'pos1', 'pos3', 'pos6', 'pos5', 'neg3', 'neg2', 'neg1', 'neg4')); + } + + private function applyOrderByFilter() + { + $filter = new OrderBy($this->table, 'growth', 'nb_visits'); + $filter->filter($this->table); + } + +} diff --git a/plugins/Insights/tests/Unit/InsightReportTest.php b/plugins/Insights/tests/Unit/InsightReportTest.php new file mode 100644 index 0000000000..32901409ac --- /dev/null +++ b/plugins/Insights/tests/Unit/InsightReportTest.php @@ -0,0 +1,471 @@ +currentTable = new DataTable(); + $this->currentTable->addRowsFromArray(array( + array(Row::COLUMNS => array('label' => 'val1', 'nb_visits' => 120)), + array(Row::COLUMNS => array('label' => 'val2', 'nb_visits' => 70)), + array(Row::COLUMNS => array('label' => 'val3', 'nb_visits' => 90)), + array(Row::COLUMNS => array('label' => 'val4', 'nb_visits' => 99)), + array(Row::COLUMNS => array('label' => 'val5', 'nb_visits' => 0)), + array(Row::COLUMNS => array('label' => 'val6', 'nb_visits' => 0)), + array(Row::COLUMNS => array('label' => 'val7', 'nb_visits' => 134)), + array(Row::COLUMNS => array('label' => 'val8', 'nb_visits' => 100)), + array(Row::COLUMNS => array('label' => 'val9', 'nb_visits' => 7)), + array(Row::COLUMNS => array('label' => 'val10', 'nb_visits' => 89)), + array(Row::COLUMNS => array('label' => 'val11', 'nb_visits' => 170)), + array(Row::COLUMNS => array('label' => 'val12', 'nb_visits' => 14)) + )); + + $this->pastTable = new DataTable(); + $this->pastTable->addRowsFromArray(array( + array(Row::COLUMNS => array('label' => 'val1', 'nb_visits' => 102)), + array(Row::COLUMNS => array('label' => 'val102', 'nb_visits' => 29)), + array(Row::COLUMNS => array('label' => 'val4', 'nb_visits' => 120)), + array(Row::COLUMNS => array('label' => 'val6', 'nb_visits' => 180)), + array(Row::COLUMNS => array('label' => 'val109', 'nb_visits' => 0)), + array(Row::COLUMNS => array('label' => 'val8', 'nb_visits' => 140)), + array(Row::COLUMNS => array('label' => 'val9', 'nb_visits' => 72)), + array(Row::COLUMNS => array('label' => 'val107', 'nb_visits' => 150)), + array(Row::COLUMNS => array('label' => 'val10', 'nb_visits' => 0)), + array(Row::COLUMNS => array('label' => 'val11', 'nb_visits' => 5)), + array(Row::COLUMNS => array('label' => 'val12', 'nb_visits' => 5)) + )); + + $this->insightReport = new InsightReport(); + } + + /** + * @dataProvider provideOrderTestData + */ + public function test_generateInsight_Order($orderBy, $expectedOrder) + { + $report = $this->generateInsight(2, 2, 2, 17, -17, $orderBy); + + $this->assertOrder($report, $expectedOrder); + } + + public function provideOrderTestData() + { + return array( + array(InsightReport::ORDER_BY_IMPORTANCE, array('val6', 'val11', 'val107', 'val7', 'val3', 'val10', 'val2', 'val9', 'val8', 'val102', 'val4', 'val1', 'val12')), + array(InsightReport::ORDER_BY_RELATIVE, array('val11', 'val12', 'val7', 'val3', 'val10', 'val2', 'val1', 'val6', 'val107', 'val102', 'val9', 'val8', 'val4')), + array(InsightReport::ORDER_BY_ABSOLUTE, array('val11', 'val7', 'val3', 'val10', 'val2', 'val1', 'val12', 'val6', 'val107', 'val9', 'val8', 'val102', 'val4')), + ); + } + + /** + * @expectedException \Exception + * @expectedExceptionMessage Unsupported orderBy + */ + public function test_generateInsight_Order_ShouldThrowException_IfInvalid() + { + $this->generateInsight(2, 2, 2, 17, -17, 'InvalidOrDeRbY'); + } + + /** + * @dataProvider provideMinGrowthTestData + */ + public function test_generateInsight_MinGrowth($minGrowthPositive, $minGrowthNegative, $expectedOrder) + { + $report = $this->generateInsight(2, 2, 2, $minGrowthPositive, $minGrowthNegative, InsightReport::ORDER_BY_ABSOLUTE); + $this->assertOrder($report, $expectedOrder); + } + + public function provideMinGrowthTestData() + { + return array( + array(4000, -4000, array()), + array(1000, -1000, array('val11')), + array(120, -120, array('val11', 'val12')), + array(80, -80, array('val11', 'val7', 'val3', 'val10', 'val2', 'val12', 'val6', 'val107', 'val9', 'val102')), + array(19, -19, array('val11', 'val7', 'val3', 'val10', 'val2', 'val12', 'val6', 'val107', 'val9', 'val8', 'val102')), + array(17, -17, array('val11', 'val7', 'val3', 'val10', 'val2', 'val1', 'val12', 'val6', 'val107', 'val9', 'val8', 'val102', 'val4')), + array(17, -80, array('val11', 'val7', 'val3', 'val10', 'val2', 'val1', 'val12', 'val6', 'val107', 'val9', 'val102')), + array(17, -4000, array('val11', 'val7', 'val3', 'val10', 'val2', 'val1', 'val12')), + array(4000, -17, array('val6', 'val107', 'val9', 'val8', 'val102', 'val4')), + ); + } + + /** + * @dataProvider provideLimitTestData + */ + public function test_generateInsight_Limit($limitIncrease, $limitDecrease, $expectedOrder) + { + $report = $this->generateInsight(2, 2, 2, 20, -20, InsightReport::ORDER_BY_ABSOLUTE, $limitIncrease, $limitDecrease); + + $this->assertOrder($report, $expectedOrder); + } + + public function provideLimitTestData() + { + return array( + array(1, 1, array('val11', 'val6')), + array(1, 0, array('val11')), // only increase + array(0, 1, array('val6')), // only decrease + array(0, 0, array()), // neither increase nor decrease + ); + } + + public function test_generateInsight_NoMovers() + { + $report = $this->generateInsight(-1, 2, 2, 20, -20); + + $this->assertOrder($report, array('val7', 'val3', 'val2', 'val107', 'val102')); + } + + /** + * @dataProvider provideMinImpactMoversTestData + */ + public function test_generateInsight_MinImpactMovers($minMoversPercent, $expectedOrder) + { + $report = $this->generateInsight($minMoversPercent, -1, -1, 17, -17); + + $this->assertOrder($report, $expectedOrder); + } + + public function provideMinImpactMoversTestData() + { + return array( + array(2, array('val11', 'val10', 'val1', 'val12', 'val6', 'val9', 'val8', 'val4')), + array(20, array('val11', 'val10', 'val6', 'val9', 'val8')), + array(80, array('val11', 'val6')), + array(10000, array()) + ); + } + + public function test_generateInsight_NoNew() + { + $report = $this->generateInsight(2, -1, 2, 17, -17); + + $this->assertOrder($report, array('val11', 'val10', 'val1', 'val12', 'val6', 'val107', 'val9', 'val8', 'val102', 'val4')); + } + + /** + * @dataProvider provideMinImpactNewTestData + */ + public function test_generateInsight_MinImpactNew($minNewPercent, $expectedOrder) + { + $report = $this->generateInsight(-1, $minNewPercent, -1, 17, -17); + + $this->assertOrder($report, $expectedOrder); + } + + public function provideMinImpactNewTestData() + { + return array( + array(2, array('val7', 'val3', 'val2')), + array(22, array('val7', 'val3', 'val2')), + array(36, array('val7', 'val3')), + array(66, array('val7')), + array(10000, array()) + ); + } + + public function test_generateInsight_NoDisappeared() + { + $report = $this->generateInsight(2, 2, -1, 17, -17); + + $this->assertOrder($report, array('val11', 'val7', 'val3', 'val10', 'val2', 'val1', 'val12', 'val6', 'val9', 'val8', 'val4')); + } + + /** + * @dataProvider provideMinImpactDisappearedData + */ + public function test_generateInsight_MinDisappeared($minDisappearedPercent, $expectedOrder) + { + $report = $this->generateInsight(-1, -1, $minDisappearedPercent, 17, -17); + $this->assertOrder($report, $expectedOrder); + } + + public function provideMinImpactDisappearedData() + { + return array( + array(2, array('val107', 'val102')), + array(14, array('val107', 'val102')), + array(15, array('val107')), + array(75, array('val107')), + array(76, array()), + array(10000, array()) + ); + } + + public function test_generateInsights_ShouldSetCorrectMetadata() + { + $report = $this->generateInsight(2, 4, 8, 17, -21); + $metadata = $report->getAllTableMetadata(); + + $expectedMetadata = array( + 'reportName' => 'TestReport', + 'metricName' => 'Visits', + 'date' => '2012-12-12', + 'lastDate' => '2012-12-11', + 'period' => 'day', + 'orderBy' => 'absolute', + 'metric' => 'nb_visits', + 'totalValue' => 200, + 'minChangeMovers' => 4, + 'minIncreaseNew' => 8, + 'minDecreaseDisappeared' => 16, + 'minGrowthPercentPositive' => 17, + 'minGrowthPercentNegative' => -21, + 'minMoversPercent' => 2, + 'minNewPercent' => 4, + 'minDisappearedPercent' => 8, + ); + + $this->assertInternalType('array', $metadata['report']); + $this->assertEquals('TestReport', $metadata['report']['name']); + unset($metadata['report']); + unset($metadata['totals']); + + $this->assertEquals($expectedMetadata, $metadata); + } + + public function test_markMoversAndShakers() + { + $report = $this->generateInsight(2, 2, 2, 5, -5); + $this->insightReport->markMoversAndShakers($report, $this->currentTable, $this->pastTable, 160, 100); + + // increase by 60% --> minGrowth 80% + $movers = array('val11', 'val12', 'val7', 'val9', 'val3', 'val10', 'val2', 'val6', 'val107', 'val102'); + $nonMovers = array('val1', 'val8', 'val4'); + + $this->assertMoversAndShakers($report, $movers, $nonMovers); + } + + public function test_markMoversAndShakers_shouldAddMetadata() + { + $report = $this->generateInsight(2, 2, 2, 5, -5); + $this->insightReport->markMoversAndShakers($report, $this->currentTable, $this->pastTable, 200, 100); + + $metadata = $report->getAllTableMetadata(); + + $this->assertEquals(100, $metadata['lastTotalValue']); + $this->assertEquals(200, $metadata['totalValue']); + $this->assertEquals(100, $metadata['evolutionDifference']); + $this->assertEquals(100, $metadata['evolutionTotal']); + } + + public function test_generateMoversAndShakers() + { + // increase by 60% --> minGrowth 80% + $report = $this->generateMoverAndShaker(160, 100); + $this->assertOrder($report, array('val11', 'val7', 'val3', 'val10', 'val2', 'val12', 'val6', 'val107', 'val9', 'val102')); + + // increase by 1600% --> minGrowth 1640% + $report = $this->generateMoverAndShaker(1600, 100); + $this->assertOrder($report, array('val11', 'val6', 'val107', 'val9')); + + } + + private function assertMoversAndShakers(DataTable $report, $movers, $nonMovers) + { + foreach ($movers as $mover) { + $row = $report->getRowFromLabel($mover); + if (!$row) { + $this->fail("$mover is not a valid label"); + continue; + } + $this->assertTrue($row->getColumn('isMoverAndShaker'), "$mover is not a mover but should be"); + } + + foreach ($nonMovers as $nonMover) { + $row = $report->getRowFromLabel($nonMover); + if (!$row) { + $this->fail("$nonMover is not a valid label"); + continue; + } + $this->assertFalse($row->getColumn('isMoverAndShaker'), "$nonMover is a mover but should be not"); + } + } + + public function test_generateMoversAndShakers_Metadata() + { + $report = $this->generateMoverAndShaker(150, 50); + $metadata = $report->getAllTableMetadata(); + + $this->assertEquals(50, $metadata['lastTotalValue']); + $this->assertEquals(150, $metadata['totalValue']); + $this->assertEquals(100, $metadata['evolutionDifference']); + $this->assertEquals(200, $metadata['evolutionTotal']); + + $report = $this->generateMoverAndShaker(75, 50); + $metadata = $report->getAllTableMetadata(); + + $this->assertEquals(50, $metadata['lastTotalValue']); + $this->assertEquals(75, $metadata['totalValue']); + $this->assertEquals(25, $metadata['evolutionDifference']); + $this->assertEquals(50, $metadata['evolutionTotal']); + + $report = $this->generateMoverAndShaker(25, 50); + $metadata = $report->getAllTableMetadata(); + + $this->assertEquals(50, $metadata['lastTotalValue']); + $this->assertEquals(25, $metadata['totalValue']); + $this->assertEquals(-25, $metadata['evolutionDifference']); + $this->assertEquals(-50, $metadata['evolutionTotal']); + } + + public function test_generateMoversAndShakers_ParameterCalculation() + { + $report = $this->generateMoverAndShaker(3000, 50); // evolution of 5900% + $metadata = $report->getAllTableMetadata(); + + $this->assertEquals(6380, $metadata['minGrowthPercentPositive']); + $this->assertEquals(-70, $metadata['minGrowthPercentNegative']); + $this->assertEquals(1, $metadata['minMoversPercent']); + $this->assertEquals(10, $metadata['minNewPercent']); + $this->assertEquals(8, $metadata['minDisappearedPercent']); + + $report = $this->generateMoverAndShaker(300, 100); + $metadata = $report->getAllTableMetadata(); + + $this->assertEquals(240, $metadata['minGrowthPercentPositive']); + $this->assertEquals(-70, $metadata['minGrowthPercentNegative']); + $this->assertEquals(1, $metadata['minMoversPercent']); + $this->assertEquals(6, $metadata['minNewPercent']); + $this->assertEquals(8, $metadata['minDisappearedPercent']); + + $report = $this->generateMoverAndShaker(225, 150); + $metadata = $report->getAllTableMetadata(); + + $this->assertEquals(70, $metadata['minGrowthPercentPositive']); + $this->assertEquals(-70, $metadata['minGrowthPercentNegative']); + $this->assertEquals(1, $metadata['minMoversPercent']); + $this->assertEquals(5, $metadata['minNewPercent']); + $this->assertEquals(7, $metadata['minDisappearedPercent']); + + $report = $this->generateMoverAndShaker(300, 600); + $metadata = $report->getAllTableMetadata(); + + $this->assertEquals(70, $metadata['minGrowthPercentPositive']); + $this->assertEquals(-70, $metadata['minGrowthPercentNegative']); + $this->assertEquals(1, $metadata['minMoversPercent']); + $this->assertEquals(5, $metadata['minNewPercent']); + $this->assertEquals(7, $metadata['minDisappearedPercent']); + + // make sure to force a change of at least 2 visits in all rows if total is soooo low + $report = $this->generateMoverAndShaker(25, 50); + $metadata = $report->getAllTableMetadata(); + + $this->assertEquals(70, $metadata['minGrowthPercentPositive']); + $this->assertEquals(-70, $metadata['minGrowthPercentNegative']); + $this->assertEquals(8, $metadata['minMoversPercent']); + $this->assertEquals(8, $metadata['minNewPercent']); + $this->assertEquals(8, $metadata['minDisappearedPercent']); + + // make sure to force a change of at least 2 visits + $report = $this->generateMoverAndShaker(75, 150); + $metadata = $report->getAllTableMetadata(); + + $this->assertEquals(70, $metadata['minGrowthPercentPositive']); + $this->assertEquals(-70, $metadata['minGrowthPercentNegative']); + $this->assertEquals(3, $metadata['minMoversPercent']); + $this->assertEquals(5, $metadata['minNewPercent']); + $this->assertEquals(7, $metadata['minDisappearedPercent']); + + // make sure no division by zero issue + $report = $this->generateMoverAndShaker(0, 150); + $metadata = $report->getAllTableMetadata(); + + $this->assertEquals(120, $metadata['minGrowthPercentPositive']); + $this->assertEquals(-120, $metadata['minGrowthPercentNegative']); + $this->assertEquals(1, $metadata['minMoversPercent']); + $this->assertEquals(5, $metadata['minNewPercent']); + $this->assertEquals(7, $metadata['minDisappearedPercent']); + } + + private function generateMoverAndShaker($totalValue, $lastTotalValue, $orderBy = null, $limitIncreaser = 99, $limitDecreaser = 99) + { + if (is_null($orderBy)) { + $orderBy = InsightReport::ORDER_BY_ABSOLUTE; + } + + $reportMetadata = array('name' => 'TestReport', 'metrics' => array('nb_visits' => 'Visits')); + + $report = $this->insightReport->generateMoverAndShaker( + $reportMetadata, 'day', '2012-12-12', '2012-12-11', 'nb_visits', $this->currentTable, $this->pastTable, + $totalValue, $lastTotalValue, $orderBy, $limitIncreaser, $limitDecreaser); + + return $report; + } + + private function generateInsight($minMoversPercent, $minNewPercent, $minDisappearedPercent, $minGrowthPercentPositive, $minGrowthPercentNegative, $orderBy = null, $limitIncreaser = 99, $limitDecreaser = 99) + { + if (is_null($orderBy)) { + $orderBy = InsightReport::ORDER_BY_ABSOLUTE; + } + + $reportMetadata = array('name' => 'TestReport', 'metrics' => array('nb_visits' => 'Visits')); + + $report = $this->insightReport->generateInsight( + $reportMetadata, 'day', '2012-12-12', '2012-12-11', 'nb_visits', $this->currentTable, $this->pastTable, + $totalValue = 200, $minMoversPercent, $minNewPercent, $minDisappearedPercent, + $minGrowthPercentPositive, $minGrowthPercentNegative, $orderBy, $limitIncreaser, $limitDecreaser); + + return $report; + } + + private function assertOrder(DataTable $table, $expectedOrder) + { + $this->assertEquals($expectedOrder, $table->getColumn('label')); + $this->assertEquals(count($expectedOrder), $table->getRowsCount()); + } +} diff --git a/plugins/LanguagesManager/tests/Integration/LanguagesManagerTest.php b/plugins/LanguagesManager/tests/Integration/LanguagesManagerTest.php new file mode 100755 index 0000000000..3ed219acf4 --- /dev/null +++ b/plugins/LanguagesManager/tests/Integration/LanguagesManagerTest.php @@ -0,0 +1,182 @@ +getAvailableLanguages(); + + $plugins = \Piwik\Plugin\Manager::getInstance()->readPluginsDirectory(); + + $pluginsWithTranslation = array(); + + foreach ($plugins as $plugin) { + + if (API::getInstance()->getPluginTranslationsForLanguage($plugin, 'en')) { + + $pluginsWithTranslation[] = $plugin; + } + } + + $return = array(); + foreach ($languages as $language) { + if ($language != 'en') { + $return[] = array($language, null); + + foreach ($pluginsWithTranslation as $plugin) { + + $return[] = array($language, $plugin); + } + } + } + + return $return; + } + + /** + * test all languages + * + * @group Plugins + * + * @dataProvider getTestDataForLanguageFiles + */ + function testGetTranslationsForLanguages($language, $plugin) + { + $translationWriter = new Writer($language, $plugin); + + $baseTranslations = $translationWriter->getTranslations('en'); + + $translationWriter->addValidator(new NoScripts()); + if (empty($plugin)) { + $translationWriter->addValidator(new CoreTranslations($baseTranslations)); + } + + // prevent build from failing when translations string have been deleted +// $translationWriter->addFilter(new ByBaseTranslations($baseTranslations)); + $translationWriter->addFilter(new EmptyTranslations()); + $translationWriter->addFilter(new ByParameterCount($baseTranslations)); + $translationWriter->addFilter(new UnnecassaryWhitespaces($baseTranslations)); + $translationWriter->addFilter(new EncodedEntities()); + + $translations = $translationWriter->getTranslations($language); + + if (empty($translations)) { + return; // skip language / plugin combinations that aren't present + } + + $translationWriter->setTranslations($translations); + + $this->assertTrue($translationWriter->isValid(), $translationWriter->getValidationMessage()); + + if ($translationWriter->wasFiltered()) { + + $translationWriter->saveTemporary(); + $this->fail(implode("\n", $translationWriter->getFilterMessages()) . "\n" + . 'Translation file errors detected in ' . $language . "...\n" + . "To overwrite you could manually fix the language files, or run the following command may work if you have access to oTrance: \n" + . "$ ./console translations:update [--plugin=XYZ] \n"); + } + } + + /** + * test language when it's not defined + * + * @group Plugins + * + * @expectedException Exception + */ + function testWriterInvalidPlugin() + { + new Writer('de', 'iNvaLiDPluGin'); // invalid plugin throws exception + } + + /** + * test language when it's not defined + * + * @group Plugins + */ + function testGetTranslationsForLanguagesNot() + { + $this->assertFalse(API::getInstance()->getTranslationsForLanguage("../no-language")); + } + + /** + * test English short name for language + * + * @group Plugins + */ + function testGetLanguageNamesInEnglish() + { + $languages = API::getInstance()->getAvailableLanguages(); + foreach ($languages as $language) { + $data = file_get_contents(PIWIK_INCLUDE_PATH . "/lang/$language.json"); + $translations = json_decode($data, true); + $name = $translations['General']['EnglishLanguageName']; + + if ($language != 'en') { + $this->assertFalse($name == 'English', "for $language"); + } + + $languageCode = substr($language, 0, 2); + $this->assertTrue(isset($GLOBALS['Piwik_LanguageList'][$languageCode])); + $names = $GLOBALS['Piwik_LanguageList'][$languageCode]; + + if (isset($GLOBALS['Piwik_LanguageList'][$language])) { + if (is_array($names)) { + $this->assertTrue(in_array($name, $names), "$language: failed because $name not a known language name"); + } else { + $this->assertTrue($name == $names, "$language: failed because $name == $names"); + } + } else { + if (is_array($names)) { + $this->assertTrue(strpos($name, $names[0]) !== false); + } else { + $this->fail("$language: expected an array of language names"); + } + } + } + } + + /** + * test format of DataFile/Languages.php + * + * @group Plugins + */ + function testGetLanguagesList() + { + $languages = Common::getLanguagesList(); + $this->assertTrue(count($languages) > 0); + foreach ($languages as $langCode => $langs) { + $this->assertTrue(strlen($langCode) == 2, "$langCode length = 2"); + $this->assertTrue(is_array($langs) && count($langs) >= 1, "$langCode array(names) >= 1"); + } + } +} diff --git a/plugins/LanguagesManager/tests/LanguagesManagerTest.php b/plugins/LanguagesManager/tests/LanguagesManagerTest.php deleted file mode 100755 index 3ed219acf4..0000000000 --- a/plugins/LanguagesManager/tests/LanguagesManagerTest.php +++ /dev/null @@ -1,182 +0,0 @@ -getAvailableLanguages(); - - $plugins = \Piwik\Plugin\Manager::getInstance()->readPluginsDirectory(); - - $pluginsWithTranslation = array(); - - foreach ($plugins as $plugin) { - - if (API::getInstance()->getPluginTranslationsForLanguage($plugin, 'en')) { - - $pluginsWithTranslation[] = $plugin; - } - } - - $return = array(); - foreach ($languages as $language) { - if ($language != 'en') { - $return[] = array($language, null); - - foreach ($pluginsWithTranslation as $plugin) { - - $return[] = array($language, $plugin); - } - } - } - - return $return; - } - - /** - * test all languages - * - * @group Plugins - * - * @dataProvider getTestDataForLanguageFiles - */ - function testGetTranslationsForLanguages($language, $plugin) - { - $translationWriter = new Writer($language, $plugin); - - $baseTranslations = $translationWriter->getTranslations('en'); - - $translationWriter->addValidator(new NoScripts()); - if (empty($plugin)) { - $translationWriter->addValidator(new CoreTranslations($baseTranslations)); - } - - // prevent build from failing when translations string have been deleted -// $translationWriter->addFilter(new ByBaseTranslations($baseTranslations)); - $translationWriter->addFilter(new EmptyTranslations()); - $translationWriter->addFilter(new ByParameterCount($baseTranslations)); - $translationWriter->addFilter(new UnnecassaryWhitespaces($baseTranslations)); - $translationWriter->addFilter(new EncodedEntities()); - - $translations = $translationWriter->getTranslations($language); - - if (empty($translations)) { - return; // skip language / plugin combinations that aren't present - } - - $translationWriter->setTranslations($translations); - - $this->assertTrue($translationWriter->isValid(), $translationWriter->getValidationMessage()); - - if ($translationWriter->wasFiltered()) { - - $translationWriter->saveTemporary(); - $this->fail(implode("\n", $translationWriter->getFilterMessages()) . "\n" - . 'Translation file errors detected in ' . $language . "...\n" - . "To overwrite you could manually fix the language files, or run the following command may work if you have access to oTrance: \n" - . "$ ./console translations:update [--plugin=XYZ] \n"); - } - } - - /** - * test language when it's not defined - * - * @group Plugins - * - * @expectedException Exception - */ - function testWriterInvalidPlugin() - { - new Writer('de', 'iNvaLiDPluGin'); // invalid plugin throws exception - } - - /** - * test language when it's not defined - * - * @group Plugins - */ - function testGetTranslationsForLanguagesNot() - { - $this->assertFalse(API::getInstance()->getTranslationsForLanguage("../no-language")); - } - - /** - * test English short name for language - * - * @group Plugins - */ - function testGetLanguageNamesInEnglish() - { - $languages = API::getInstance()->getAvailableLanguages(); - foreach ($languages as $language) { - $data = file_get_contents(PIWIK_INCLUDE_PATH . "/lang/$language.json"); - $translations = json_decode($data, true); - $name = $translations['General']['EnglishLanguageName']; - - if ($language != 'en') { - $this->assertFalse($name == 'English', "for $language"); - } - - $languageCode = substr($language, 0, 2); - $this->assertTrue(isset($GLOBALS['Piwik_LanguageList'][$languageCode])); - $names = $GLOBALS['Piwik_LanguageList'][$languageCode]; - - if (isset($GLOBALS['Piwik_LanguageList'][$language])) { - if (is_array($names)) { - $this->assertTrue(in_array($name, $names), "$language: failed because $name not a known language name"); - } else { - $this->assertTrue($name == $names, "$language: failed because $name == $names"); - } - } else { - if (is_array($names)) { - $this->assertTrue(strpos($name, $names[0]) !== false); - } else { - $this->fail("$language: expected an array of language names"); - } - } - } - } - - /** - * test format of DataFile/Languages.php - * - * @group Plugins - */ - function testGetLanguagesList() - { - $languages = Common::getLanguagesList(); - $this->assertTrue(count($languages) > 0); - foreach ($languages as $langCode => $langs) { - $this->assertTrue(strlen($langCode) == 2, "$langCode length = 2"); - $this->assertTrue(is_array($langs) && count($langs) >= 1, "$langCode array(names) >= 1"); - } - } -} diff --git a/plugins/LeftMenu/tests/APITest.php b/plugins/LeftMenu/tests/APITest.php deleted file mode 100644 index 1b80cdc0d8..0000000000 --- a/plugins/LeftMenu/tests/APITest.php +++ /dev/null @@ -1,144 +0,0 @@ -api = API::getInstance(); - $this->createSettings(); - } - - public function test_isEnabled_shouldReturnFalse_ByDefault() - { - $this->assertLeftMenuIsDisabled(); - - $this->setUser(); - $this->assertLeftMenuIsDisabled(); - - $this->setSuperUser(); - $this->assertLeftMenuIsDisabled(); - } - - public function test_isEnabled_shouldReturnTrue_IfEnabledSystemWideAndNoUserPreference() - { - $this->enableLeftMenuForAll(); - - $this->assertLeftMenuIsEnabled(); - - $this->setUser(); - $this->assertLeftMenuIsEnabled(); - - $this->setAnonymous(); - $this->assertLeftMenuIsEnabled(); - } - - public function test_isEnabled_AUserPreferenceShouldOverwriteASystemPreference_DefaultDisabled() - { - $this->assertLeftMenuIsDisabled(); - - $this->setUser(); - $this->setUserSettingValue('yes'); - - $this->assertLeftMenuIsEnabled(); - - $this->setAnonymous(); - $this->assertLeftMenuIsDisabled(); - } - - public function test_isEnabled_AUserPreferenceShouldOverwriteASystemPreference_DefaultEnabled() - { - $this->enableLeftMenuForAll(); - - $this->assertLeftMenuIsEnabled(); - - $this->setUser(); - $this->setUserSettingValue('no'); - - $this->assertLeftMenuIsDisabled(); - - $this->setAnonymous(); - $this->assertLeftMenuIsEnabled(); - } - - private function assertLeftMenuIsEnabled() - { - $this->assertTrue($this->api->isEnabled()); - } - - private function assertLeftMenuIsDisabled() - { - $this->assertFalse($this->api->isEnabled()); - } - - private function setSuperUser() - { - $pseudoMockAccess = new FakeAccess; - FakeAccess::$superUser = true; - FakeAccess::$superUserLogin = 'superUserLogin'; - Access::setSingletonInstance($pseudoMockAccess); - $this->createSettings(); - } - - private function setAnonymous() - { - Access::setSingletonInstance(null); - $this->createSettings(); - } - - private function setUser() - { - $pseudoMockAccess = new FakeAccess; - FakeAccess::$idSitesView = array(1); - FakeAccess::$identity = 'userLogin'; - Access::setSingletonInstance($pseudoMockAccess); - $this->createSettings(); - } - - private function enableLeftMenuForAll() - { - $this->setSuperUser(); - $this->settings->globalEnabled->setValue(true); - $this->settings->save(); - } - - private function createSettings() - { - $this->settings = new Settings('LeftMenu'); - } - - private function setUserSettingValue($value) - { - $this->settings->userEnabled->setValue($value); - $this->settings->save(); - } -} diff --git a/plugins/LeftMenu/tests/Integration/APITest.php b/plugins/LeftMenu/tests/Integration/APITest.php new file mode 100644 index 0000000000..0677f57c73 --- /dev/null +++ b/plugins/LeftMenu/tests/Integration/APITest.php @@ -0,0 +1,144 @@ +api = API::getInstance(); + $this->createSettings(); + } + + public function test_isEnabled_shouldReturnFalse_ByDefault() + { + $this->assertLeftMenuIsDisabled(); + + $this->setUser(); + $this->assertLeftMenuIsDisabled(); + + $this->setSuperUser(); + $this->assertLeftMenuIsDisabled(); + } + + public function test_isEnabled_shouldReturnTrue_IfEnabledSystemWideAndNoUserPreference() + { + $this->enableLeftMenuForAll(); + + $this->assertLeftMenuIsEnabled(); + + $this->setUser(); + $this->assertLeftMenuIsEnabled(); + + $this->setAnonymous(); + $this->assertLeftMenuIsEnabled(); + } + + public function test_isEnabled_AUserPreferenceShouldOverwriteASystemPreference_DefaultDisabled() + { + $this->assertLeftMenuIsDisabled(); + + $this->setUser(); + $this->setUserSettingValue('yes'); + + $this->assertLeftMenuIsEnabled(); + + $this->setAnonymous(); + $this->assertLeftMenuIsDisabled(); + } + + public function test_isEnabled_AUserPreferenceShouldOverwriteASystemPreference_DefaultEnabled() + { + $this->enableLeftMenuForAll(); + + $this->assertLeftMenuIsEnabled(); + + $this->setUser(); + $this->setUserSettingValue('no'); + + $this->assertLeftMenuIsDisabled(); + + $this->setAnonymous(); + $this->assertLeftMenuIsEnabled(); + } + + private function assertLeftMenuIsEnabled() + { + $this->assertTrue($this->api->isEnabled()); + } + + private function assertLeftMenuIsDisabled() + { + $this->assertFalse($this->api->isEnabled()); + } + + private function setSuperUser() + { + $pseudoMockAccess = new FakeAccess; + FakeAccess::$superUser = true; + FakeAccess::$superUserLogin = 'superUserLogin'; + Access::setSingletonInstance($pseudoMockAccess); + $this->createSettings(); + } + + private function setAnonymous() + { + Access::setSingletonInstance(null); + $this->createSettings(); + } + + private function setUser() + { + $pseudoMockAccess = new FakeAccess; + FakeAccess::$idSitesView = array(1); + FakeAccess::$identity = 'userLogin'; + Access::setSingletonInstance($pseudoMockAccess); + $this->createSettings(); + } + + private function enableLeftMenuForAll() + { + $this->setSuperUser(); + $this->settings->globalEnabled->setValue(true); + $this->settings->save(); + } + + private function createSettings() + { + $this->settings = new Settings('LeftMenu'); + } + + private function setUserSettingValue($value) + { + $this->settings->userEnabled->setValue($value); + $this->settings->save(); + } +} diff --git a/plugins/Live/tests/APITest.php b/plugins/Live/tests/APITest.php deleted file mode 100644 index 5bdf6f2f22..0000000000 --- a/plugins/Live/tests/APITest.php +++ /dev/null @@ -1,152 +0,0 @@ -api = API::getInstance(); - $this->setSuperUser(); - $this->createSite(); - } - - /** - * @expectedException \Exception - * @expectedExceptionMessage checkUserHasViewAccess Fake exception - */ - public function test_GetCounters_ShouldFail_IfUserHasNoPermission() - { - $this->setAnonymous(); - $this->api->getCounters($this->idSite, 5); - } - - public function test_GetCounters_ShouldReturnZeroForAllCounters_IfThereAreNoVisitsEtc() - { - $counters = $this->api->getCounters($this->idSite, 5); - - $this->assertEquals($this->buildCounter(0, 0, 0, 0), $counters); - } - - public function test_GetCounters_ShouldOnlyReturnResultsOfLastMinutes() - { - $this->trackSomeVisits(); - - $counters = $this->api->getCounters($this->idSite, 5); - $this->assertEquals($this->buildCounter(19, 32, 16, 16), $counters); - - $counters = $this->api->getCounters($this->idSite, 20); - $this->assertEquals($this->buildCounter(24, 60, 20, 40), $counters); - - $counters = $this->api->getCounters($this->idSite, 0); - $this->assertEquals($this->buildCounter(0, 0, 0, 0), $counters); - } - - private function trackSomeVisits() - { - $nowTimestamp = time(); - - // use local tracker so mock location provider can be used - $t = Fixture::getTracker($this->idSite, $nowTimestamp, $defaultInit = true, $useLocal = false); - $t->enableBulkTracking(); - - for ($i = 0; $i != 20; ++$i) { - $t->setForceNewVisit(); - $t->setVisitorId( substr(md5($i * 1000), 0, $t::LENGTH_VISITOR_ID)); - - $factor = 10; - if ($i > 15) { - $factor = 30; // make sure first 15 visits are always within 5 minutes to prevent any random fails - } - $time = $nowTimestamp - ($i * $factor); - - // first visit -> this one is > 5 minutes and should be ignored in one test - $date = Date::factory($time - 600); - $t->setForceVisitDateTime($date->getDatetime()); - $t->setUrl("http://piwik.net/space/quest/iv"); - $t->doTrackPageView("Space Quest XV"); - - $t->doTrackGoal(1); // this one is > 5 minutes and should be ignored in one test - - // second visit - $date = Date::factory($time - 1); - $t->setForceVisitDateTime($date->getDatetime()); - $t->setUrl("http://piwik.net/space/quest/iv"); - $t->doTrackPageView("Space Quest XII"); - - if ($i % 6 == 0) { - $t->setForceNewVisit(); // to test visitors vs visits - } - - // third visit - $date = Date::factory($time); - $t->setForceVisitDateTime($date->getDatetime()); - $t->setUrl("http://piwik.net/grue/$i"); - $t->doTrackPageView('It is pitch black...'); - - $t->doTrackGoal(2); - } - - $t->doBulkTrack(); - } - - private function buildCounter($visits, $actions, $visitors, $visitsConverted) - { - return array(array( - 'visits' => $visits, - 'actions' => $actions, - 'visitors' => $visitors, - 'visitsConverted' => $visitsConverted, - )); - } - - private function createSite() - { - Fixture::createWebsite('2013-01-23 01:23:45'); - GoalsApi::getInstance()->addGoal(1, 'MyName', 'manually', '', 'contains'); - GoalsApi::getInstance()->addGoal(1, 'MyGoal', 'manually', '', 'contains'); - } - - private function setSuperUser() - { - $pseudoMockAccess = new FakeAccess(); - FakeAccess::$superUser = true; - Access::setSingletonInstance($pseudoMockAccess); - } - - private function setAnonymous() - { - $pseudoMockAccess = new FakeAccess(); - FakeAccess::$superUser = false; - Access::setSingletonInstance($pseudoMockAccess); - } - -} diff --git a/plugins/Live/tests/Integration/APITest.php b/plugins/Live/tests/Integration/APITest.php new file mode 100644 index 0000000000..7c49eb2eae --- /dev/null +++ b/plugins/Live/tests/Integration/APITest.php @@ -0,0 +1,152 @@ +api = API::getInstance(); + $this->setSuperUser(); + $this->createSite(); + } + + /** + * @expectedException \Exception + * @expectedExceptionMessage checkUserHasViewAccess Fake exception + */ + public function test_GetCounters_ShouldFail_IfUserHasNoPermission() + { + $this->setAnonymous(); + $this->api->getCounters($this->idSite, 5); + } + + public function test_GetCounters_ShouldReturnZeroForAllCounters_IfThereAreNoVisitsEtc() + { + $counters = $this->api->getCounters($this->idSite, 5); + + $this->assertEquals($this->buildCounter(0, 0, 0, 0), $counters); + } + + public function test_GetCounters_ShouldOnlyReturnResultsOfLastMinutes() + { + $this->trackSomeVisits(); + + $counters = $this->api->getCounters($this->idSite, 5); + $this->assertEquals($this->buildCounter(19, 32, 16, 16), $counters); + + $counters = $this->api->getCounters($this->idSite, 20); + $this->assertEquals($this->buildCounter(24, 60, 20, 40), $counters); + + $counters = $this->api->getCounters($this->idSite, 0); + $this->assertEquals($this->buildCounter(0, 0, 0, 0), $counters); + } + + private function trackSomeVisits() + { + $nowTimestamp = time(); + + // use local tracker so mock location provider can be used + $t = Fixture::getTracker($this->idSite, $nowTimestamp, $defaultInit = true, $useLocal = false); + $t->enableBulkTracking(); + + for ($i = 0; $i != 20; ++$i) { + $t->setForceNewVisit(); + $t->setVisitorId( substr(md5($i * 1000), 0, $t::LENGTH_VISITOR_ID)); + + $factor = 10; + if ($i > 15) { + $factor = 30; // make sure first 15 visits are always within 5 minutes to prevent any random fails + } + $time = $nowTimestamp - ($i * $factor); + + // first visit -> this one is > 5 minutes and should be ignored in one test + $date = Date::factory($time - 600); + $t->setForceVisitDateTime($date->getDatetime()); + $t->setUrl("http://piwik.net/space/quest/iv"); + $t->doTrackPageView("Space Quest XV"); + + $t->doTrackGoal(1); // this one is > 5 minutes and should be ignored in one test + + // second visit + $date = Date::factory($time - 1); + $t->setForceVisitDateTime($date->getDatetime()); + $t->setUrl("http://piwik.net/space/quest/iv"); + $t->doTrackPageView("Space Quest XII"); + + if ($i % 6 == 0) { + $t->setForceNewVisit(); // to test visitors vs visits + } + + // third visit + $date = Date::factory($time); + $t->setForceVisitDateTime($date->getDatetime()); + $t->setUrl("http://piwik.net/grue/$i"); + $t->doTrackPageView('It is pitch black...'); + + $t->doTrackGoal(2); + } + + $t->doBulkTrack(); + } + + private function buildCounter($visits, $actions, $visitors, $visitsConverted) + { + return array(array( + 'visits' => $visits, + 'actions' => $actions, + 'visitors' => $visitors, + 'visitsConverted' => $visitsConverted, + )); + } + + private function createSite() + { + Fixture::createWebsite('2013-01-23 01:23:45'); + GoalsApi::getInstance()->addGoal(1, 'MyName', 'manually', '', 'contains'); + GoalsApi::getInstance()->addGoal(1, 'MyGoal', 'manually', '', 'contains'); + } + + private function setSuperUser() + { + $pseudoMockAccess = new FakeAccess(); + FakeAccess::$superUser = true; + Access::setSingletonInstance($pseudoMockAccess); + } + + private function setAnonymous() + { + $pseudoMockAccess = new FakeAccess(); + FakeAccess::$superUser = false; + Access::setSingletonInstance($pseudoMockAccess); + } + +} diff --git a/plugins/Login/tests/Integration/LoginTest.php b/plugins/Login/tests/Integration/LoginTest.php new file mode 100644 index 0000000000..4af87cc115 --- /dev/null +++ b/plugins/Login/tests/Integration/LoginTest.php @@ -0,0 +1,404 @@ +auth = new Auth(); + } + + /** + * @group Plugins + */ + public function testAuthenticateFailureNoLoginNoTokenAuth() + { + // no login; no token auth + $rc = $this->auth->authenticate(); + $this->assertFailedLogin($rc); + } + + /** + * @group Plugins + */ + public function testAuthenticateFailureEmptyLoginNoTokenAuth() + { + // empty login; no token auth + $this->auth->setLogin(''); + $rc = $this->auth->authenticate(); + $this->assertFailedLogin($rc); + } + + /** + * @group Plugins + */ + public function testAuthenticateFailureNonExistentUser() + { + // non-existent user + $this->auth->setLogin('nobody'); + $rc = $this->auth->authenticate(); + $this->assertFailedLogin($rc); + } + + /** + * @group Plugins + */ + public function testAuthenticateFailureAnonymousNotExisting() + { + // anonymous user doesn't exist yet + $rc = $this->authenticate($login = 'anonymous', $authToken = ''); + $this->assertFailedLogin($rc); + } + + /** + * @group Plugins + */ + public function testAuthenticateFailureAnonymousNotExistentEmptyLogin() + { + // empty login; anonymous user doesn't exist yet + $rc = $this->authenticate($login = '', $authToken = 'anonymous'); + + $this->assertFailedLogin($rc); + } + + /** + * @group Plugins + */ + public function testAuthenticateFailureAnonymousNotExistentEmptyLoginWithTokenAuth() + { + // API authentication; anonymous user doesn't exist yet + $rc = $this->authenticate($login = null, $authToken = 'anonymous'); + $this->assertFailedLogin($rc); + } + + /** + * @group Plugins + */ + public function testAuthenticateFailureAnonymousNotExistentWithLoginAndTokenAuth() + { + // anonymous user doesn't exist yet + $rc = $this->authenticate($login = 'anonymous', $authToken = 'anonymous'); + $this->assertFailedLogin($rc); + } + + /** + * @group Plugins + */ + public function testAuthenticateFailureAnonymousWithLogin() + { + DbHelper::createAnonymousUser(); + + // missing token_auth + $rc = $this->authenticate($login = 'anonymous', $authToken = ''); + $this->assertFailedLogin($rc); + } + + /** + * @group Plugins + */ + public function testAuthenticateFailureAnonymousEmptyLoginWithTokenAuth() + { + DbHelper::createAnonymousUser(); + + // empty login + $rc = $this->authenticate($login = '', $authToken = 'anonymous'); + $this->assertFailedLogin($rc); + } + + /** + * @group Plugins + */ + public function testAuthenticateFailureAnonymousLoginTokenAuthMissmatch() + { + DbHelper::createAnonymousUser(); + + // not equal + $rc = $this->authenticate($login = 'anonymous', $authToken = 0); + $this->assertFailedLogin($rc); + } + + /** + * @group Plugins + */ + public function testAuthenticateSuccessAnonymousWithTokenAuth() + { + DbHelper::createAnonymousUser(); + + // API authentication + $rc = $this->authenticate($login = null, $authToken = 'anonymous'); + $this->assertUserLogin($rc, $login = 'anonymous', $tokenLength = 9); + } + + /** + * @group Plugins + */ + public function testAuthenticateSuccessAnonymous() + { + DbHelper::createAnonymousUser(); + + // valid login & token auth + $rc = $this->authenticate($login = 'anonymous', $authToken = 'anonymous'); + $this->assertUserLogin($rc, $login = 'anonymous', $tokenLength = 9); + } + + /** + * @group Plugins + */ + public function testAuthenticateFailureUserEmptyTokenAuth() + { + $user = $this->_setUpUser(); + + // empty token auth + $rc = $this->authenticate($login = $user['login'], $authToken = ''); + $this->assertFailedLogin($rc); + } + + /** + * @group Plugins + */ + public function testAuthenticateFailureUserInvalidTokenAuth() + { + $user = $this->_setUpUser(); + + // not a token auth + $rc = $this->authenticate($login = $user['login'], $authToken = $user['password']); + $this->assertFailedLogin($rc); + } + + /** + * @group Plugins + */ + public function testAuthenticateFailureUserInvalidTokenAuth2() + { + $user = $this->_setUpUser(); + + // not a token auth + $rc = $this->authenticate($login = $user['login'], $authToken = md5($user['password'])); + $this->assertFailedLogin($rc); + } + + /** + * @group Plugins + */ + public function testAuthenticateFailureUserEmptyLogin() + { + $user = $this->_setUpUser(); + + // empty login + $rc = $this->authenticate($login = '', $user['tokenAuth']); + $this->assertFailedLogin($rc); + } + + /** + * @group Plugins + */ + public function testAuthenticateFailureUserWithSuperUserAccessEmptyLogin() + { + $user = $this->_setUpUser(); + $this->_setUpSuperUserAccessViaDb(); + + // empty login + $rc = $this->authenticate($login = '', $user['tokenAuth']); + $this->assertFailedLogin($rc); + } + + /** + * @group Plugins + */ + public function testAuthenticateFailureUserLoginTokenAuthMissmatch() + { + $this->_setUpUser(); + + // not equal + $rc = $this->authenticate($login = 0, $authToken = 0); + $this->assertFailedLogin($rc); + } + + /** + * @group Plugins + */ + public function testAuthenticateFailureUserLoginTokenAuthMissmatch2() + { + $user = $this->_setUpUser(); + + // not equal + $rc = $this->authenticate($login = 0, $user['tokenAuth']); + $this->assertFailedLogin($rc); + } + + /** + * @group Plugins + */ + public function testAuthenticateFailureUserLoginTokenAuthMissmatch3() + { + $user = $this->_setUpUser(); + + // not equal + $rc = $this->authenticate($user['login'], $authToken = 0); + $this->assertFailedLogin($rc); + } + + /** + * @group Plugins + */ + public function testAuthenticateFailureUserWithSuperUserAccessLoginTokenAuthMissmatch() + { + $user = $this->_setUpUser(); + $this->_setUpSuperUserAccessViaDb(); + + // not equal + $rc = $this->authenticate($login = null, $authToken = $user['password']); + $this->assertFailedLogin($rc); + } + + /** + * @group Plugins + */ + public function testAuthenticateSuccessUserTokenAuth() + { + $user = $this->_setUpUser(); + + // API authentication + $rc = $this->authenticate($login = null, $user['tokenAuth']); + $this->assertUserLogin($rc); + } + + /** + * @group Plugins + */ + public function testAuthenticateSuccessUserWithSuperUserAccessByTokenAuth() + { + $user = $this->_setUpUser(); + $this->_setUpSuperUserAccessViaDb(); + + // API authentication + $rc = $this->authenticate($login = null, $user['tokenAuth']); + $this->assertSuperUserLogin($rc, 'user'); + } + + /** + * @group Plugins + */ + public function testAuthenticateSuccessUserLoginAndTokenAuth() + { + $user = $this->_setUpUser(); + + // valid login & token auth + $rc = $this->authenticate($user['login'], $user['tokenAuth']); + $this->assertUserLogin($rc); + } + + /** + * @group Plugins + */ + public function testAuthenticateSuccessUserWithSuperUserAccessLoginAndTokenAuth() + { + $user = $this->_setUpUser(); + $this->_setUpSuperUserAccessViaDb(); + + // valid login & token auth + $rc = $this->authenticate($user['login'], $user['tokenAuth']); + $this->assertSuperUserLogin($rc, 'user'); + } + + /** + * @group Plugins + */ + public function testAuthenticateSuccessLoginAndHashedTokenAuth() + { + $user = $this->_setUpUser(); + $hash = \Piwik\Plugins\Login\SessionInitializer::getHashTokenAuth($user['login'], $user['tokenAuth']); + + // valid login & hashed token auth + $rc = $this->authenticate($user['login'], $tokenAuth = $hash); + $this->assertUserLogin($rc); + } + + protected function _setUpUser() + { + $user = array('login' => 'user', + 'password' => 'geqgeagae', + 'email' => 'test@test.com', + 'alias' => 'alias', + 'superuser_access' => 0); + + API::getInstance()->addUser($user['login'], $user['password'], $user['email'], $user['alias']); + + $user['tokenAuth'] = API::getInstance()->getTokenAuth($user['login'], md5($user['password'])); + + return $user; + } + + private function _setUpSuperUserAccessViaDb() + { + API::getInstance()->setSuperUserAccess('user', true); + } + + private function authenticate($login, $tokenAuth) + { + $this->auth->setLogin($login); + $this->auth->setTokenAuth($tokenAuth); + + return $this->auth->authenticate(); + } + + private function assertFailedLogin(AuthResult $authResult) + { + $this->assertEquals(AuthResult::FAILURE, $authResult->getCode()); + } + + private function assertSuperUserLogin(AuthResult $authResult, $login = 'superUserLogin', $tokenLength = 32) + { + $this->assertEquals(AuthResult::SUCCESS_SUPERUSER_AUTH_CODE, $authResult->getCode()); + $this->assertEquals($login, $authResult->getIdentity()); + $this->assertEquals($tokenLength, strlen($authResult->getTokenAuth())); + } + + private function assertUserLogin(AuthResult $authResult, $login = 'user', $tokenLength = 32) + { + $this->assertEquals(AuthResult::SUCCESS, $authResult->getCode()); + $this->assertEquals($login, $authResult->getIdentity()); + $this->assertEquals($tokenLength, strlen($authResult->getTokenAuth())); + } + +} diff --git a/plugins/Login/tests/LoginTest.php b/plugins/Login/tests/LoginTest.php deleted file mode 100644 index 8e431c9372..0000000000 --- a/plugins/Login/tests/LoginTest.php +++ /dev/null @@ -1,404 +0,0 @@ -auth = new Auth(); - } - - /** - * @group Plugins - */ - public function testAuthenticateFailureNoLoginNoTokenAuth() - { - // no login; no token auth - $rc = $this->auth->authenticate(); - $this->assertFailedLogin($rc); - } - - /** - * @group Plugins - */ - public function testAuthenticateFailureEmptyLoginNoTokenAuth() - { - // empty login; no token auth - $this->auth->setLogin(''); - $rc = $this->auth->authenticate(); - $this->assertFailedLogin($rc); - } - - /** - * @group Plugins - */ - public function testAuthenticateFailureNonExistentUser() - { - // non-existent user - $this->auth->setLogin('nobody'); - $rc = $this->auth->authenticate(); - $this->assertFailedLogin($rc); - } - - /** - * @group Plugins - */ - public function testAuthenticateFailureAnonymousNotExisting() - { - // anonymous user doesn't exist yet - $rc = $this->authenticate($login = 'anonymous', $authToken = ''); - $this->assertFailedLogin($rc); - } - - /** - * @group Plugins - */ - public function testAuthenticateFailureAnonymousNotExistentEmptyLogin() - { - // empty login; anonymous user doesn't exist yet - $rc = $this->authenticate($login = '', $authToken = 'anonymous'); - - $this->assertFailedLogin($rc); - } - - /** - * @group Plugins - */ - public function testAuthenticateFailureAnonymousNotExistentEmptyLoginWithTokenAuth() - { - // API authentication; anonymous user doesn't exist yet - $rc = $this->authenticate($login = null, $authToken = 'anonymous'); - $this->assertFailedLogin($rc); - } - - /** - * @group Plugins - */ - public function testAuthenticateFailureAnonymousNotExistentWithLoginAndTokenAuth() - { - // anonymous user doesn't exist yet - $rc = $this->authenticate($login = 'anonymous', $authToken = 'anonymous'); - $this->assertFailedLogin($rc); - } - - /** - * @group Plugins - */ - public function testAuthenticateFailureAnonymousWithLogin() - { - DbHelper::createAnonymousUser(); - - // missing token_auth - $rc = $this->authenticate($login = 'anonymous', $authToken = ''); - $this->assertFailedLogin($rc); - } - - /** - * @group Plugins - */ - public function testAuthenticateFailureAnonymousEmptyLoginWithTokenAuth() - { - DbHelper::createAnonymousUser(); - - // empty login - $rc = $this->authenticate($login = '', $authToken = 'anonymous'); - $this->assertFailedLogin($rc); - } - - /** - * @group Plugins - */ - public function testAuthenticateFailureAnonymousLoginTokenAuthMissmatch() - { - DbHelper::createAnonymousUser(); - - // not equal - $rc = $this->authenticate($login = 'anonymous', $authToken = 0); - $this->assertFailedLogin($rc); - } - - /** - * @group Plugins - */ - public function testAuthenticateSuccessAnonymousWithTokenAuth() - { - DbHelper::createAnonymousUser(); - - // API authentication - $rc = $this->authenticate($login = null, $authToken = 'anonymous'); - $this->assertUserLogin($rc, $login = 'anonymous', $tokenLength = 9); - } - - /** - * @group Plugins - */ - public function testAuthenticateSuccessAnonymous() - { - DbHelper::createAnonymousUser(); - - // valid login & token auth - $rc = $this->authenticate($login = 'anonymous', $authToken = 'anonymous'); - $this->assertUserLogin($rc, $login = 'anonymous', $tokenLength = 9); - } - - /** - * @group Plugins - */ - public function testAuthenticateFailureUserEmptyTokenAuth() - { - $user = $this->_setUpUser(); - - // empty token auth - $rc = $this->authenticate($login = $user['login'], $authToken = ''); - $this->assertFailedLogin($rc); - } - - /** - * @group Plugins - */ - public function testAuthenticateFailureUserInvalidTokenAuth() - { - $user = $this->_setUpUser(); - - // not a token auth - $rc = $this->authenticate($login = $user['login'], $authToken = $user['password']); - $this->assertFailedLogin($rc); - } - - /** - * @group Plugins - */ - public function testAuthenticateFailureUserInvalidTokenAuth2() - { - $user = $this->_setUpUser(); - - // not a token auth - $rc = $this->authenticate($login = $user['login'], $authToken = md5($user['password'])); - $this->assertFailedLogin($rc); - } - - /** - * @group Plugins - */ - public function testAuthenticateFailureUserEmptyLogin() - { - $user = $this->_setUpUser(); - - // empty login - $rc = $this->authenticate($login = '', $user['tokenAuth']); - $this->assertFailedLogin($rc); - } - - /** - * @group Plugins - */ - public function testAuthenticateFailureUserWithSuperUserAccessEmptyLogin() - { - $user = $this->_setUpUser(); - $this->_setUpSuperUserAccessViaDb(); - - // empty login - $rc = $this->authenticate($login = '', $user['tokenAuth']); - $this->assertFailedLogin($rc); - } - - /** - * @group Plugins - */ - public function testAuthenticateFailureUserLoginTokenAuthMissmatch() - { - $this->_setUpUser(); - - // not equal - $rc = $this->authenticate($login = 0, $authToken = 0); - $this->assertFailedLogin($rc); - } - - /** - * @group Plugins - */ - public function testAuthenticateFailureUserLoginTokenAuthMissmatch2() - { - $user = $this->_setUpUser(); - - // not equal - $rc = $this->authenticate($login = 0, $user['tokenAuth']); - $this->assertFailedLogin($rc); - } - - /** - * @group Plugins - */ - public function testAuthenticateFailureUserLoginTokenAuthMissmatch3() - { - $user = $this->_setUpUser(); - - // not equal - $rc = $this->authenticate($user['login'], $authToken = 0); - $this->assertFailedLogin($rc); - } - - /** - * @group Plugins - */ - public function testAuthenticateFailureUserWithSuperUserAccessLoginTokenAuthMissmatch() - { - $user = $this->_setUpUser(); - $this->_setUpSuperUserAccessViaDb(); - - // not equal - $rc = $this->authenticate($login = null, $authToken = $user['password']); - $this->assertFailedLogin($rc); - } - - /** - * @group Plugins - */ - public function testAuthenticateSuccessUserTokenAuth() - { - $user = $this->_setUpUser(); - - // API authentication - $rc = $this->authenticate($login = null, $user['tokenAuth']); - $this->assertUserLogin($rc); - } - - /** - * @group Plugins - */ - public function testAuthenticateSuccessUserWithSuperUserAccessByTokenAuth() - { - $user = $this->_setUpUser(); - $this->_setUpSuperUserAccessViaDb(); - - // API authentication - $rc = $this->authenticate($login = null, $user['tokenAuth']); - $this->assertSuperUserLogin($rc, 'user'); - } - - /** - * @group Plugins - */ - public function testAuthenticateSuccessUserLoginAndTokenAuth() - { - $user = $this->_setUpUser(); - - // valid login & token auth - $rc = $this->authenticate($user['login'], $user['tokenAuth']); - $this->assertUserLogin($rc); - } - - /** - * @group Plugins - */ - public function testAuthenticateSuccessUserWithSuperUserAccessLoginAndTokenAuth() - { - $user = $this->_setUpUser(); - $this->_setUpSuperUserAccessViaDb(); - - // valid login & token auth - $rc = $this->authenticate($user['login'], $user['tokenAuth']); - $this->assertSuperUserLogin($rc, 'user'); - } - - /** - * @group Plugins - */ - public function testAuthenticateSuccessLoginAndHashedTokenAuth() - { - $user = $this->_setUpUser(); - $hash = \Piwik\Plugins\Login\SessionInitializer::getHashTokenAuth($user['login'], $user['tokenAuth']); - - // valid login & hashed token auth - $rc = $this->authenticate($user['login'], $tokenAuth = $hash); - $this->assertUserLogin($rc); - } - - protected function _setUpUser() - { - $user = array('login' => 'user', - 'password' => 'geqgeagae', - 'email' => 'test@test.com', - 'alias' => 'alias', - 'superuser_access' => 0); - - API::getInstance()->addUser($user['login'], $user['password'], $user['email'], $user['alias']); - - $user['tokenAuth'] = API::getInstance()->getTokenAuth($user['login'], md5($user['password'])); - - return $user; - } - - private function _setUpSuperUserAccessViaDb() - { - API::getInstance()->setSuperUserAccess('user', true); - } - - private function authenticate($login, $tokenAuth) - { - $this->auth->setLogin($login); - $this->auth->setTokenAuth($tokenAuth); - - return $this->auth->authenticate(); - } - - private function assertFailedLogin(AuthResult $authResult) - { - $this->assertEquals(AuthResult::FAILURE, $authResult->getCode()); - } - - private function assertSuperUserLogin(AuthResult $authResult, $login = 'superUserLogin', $tokenLength = 32) - { - $this->assertEquals(AuthResult::SUCCESS_SUPERUSER_AUTH_CODE, $authResult->getCode()); - $this->assertEquals($login, $authResult->getIdentity()); - $this->assertEquals($tokenLength, strlen($authResult->getTokenAuth())); - } - - private function assertUserLogin(AuthResult $authResult, $login = 'user', $tokenLength = 32) - { - $this->assertEquals(AuthResult::SUCCESS, $authResult->getCode()); - $this->assertEquals($login, $authResult->getIdentity()); - $this->assertEquals($tokenLength, strlen($authResult->getTokenAuth())); - } - -} diff --git a/plugins/MobileMessaging/tests/Integration/MobileMessagingTest.php b/plugins/MobileMessaging/tests/Integration/MobileMessagingTest.php new file mode 100644 index 0000000000..35479dcea8 --- /dev/null +++ b/plugins/MobileMessaging/tests/Integration/MobileMessagingTest.php @@ -0,0 +1,262 @@ +idSiteAccess = APISitesManager::getInstance()->addSite("test", "http://test"); + + \Piwik\Plugin\Manager::getInstance()->loadPlugins(array('ScheduledReports', 'MobileMessaging', 'MultiSites')); + \Piwik\Plugin\Manager::getInstance()->installLoadedPlugins(); + } + + /** + * When the MultiSites plugin is not activated, the SMS content should invite the user to activate it back + * + * @group Plugins + */ + public function testWarnUserViaSMSMultiSitesDeactivated() + { + // safety net + \Piwik\Plugin\Manager::getInstance()->loadPlugins(array('ScheduledReports', 'MobileMessaging')); + $this->assertFalse(\Piwik\Plugin\Manager::getInstance()->isPluginActivated('MultiSites')); + + $APIScheduledReports = APIScheduledReports::getInstance(); + $reportId = $APIScheduledReports->addReport( + $this->idSiteAccess, + 'description', + 'month', + 0, + 'mobile', + 'sms', + array(), + array("phoneNumbers" => array('33698896656')) + ); + + list($outputFilename, $prettyDate, $websiteName, $additionalFiles) = + $APIScheduledReports->generateReport( + $reportId, + '01-01-2010', + 'en', + 2 + ); + + $handle = fopen($outputFilename, "r"); + $contents = fread($handle, filesize($outputFilename)); + fclose($handle); + + $this->assertEquals( + \Piwik\Piwik::translate('MobileMessaging_MultiSites_Must_Be_Activated'), + $contents + ); + } + + /** + * Dataprovider for testTruncate + */ + public function getTruncateTestCases() + { + + $stdGSMx459 = str_repeat('a', 459); + + $extGSMx229 = str_repeat('€', 229); + + $alternatedGSMx153 = str_repeat('a€', 153); + + $GSMWithRegExpSpecialChars = $stdGSMx459 . '[\^$.|?*/+()'; + + $UCS2x201 = str_repeat('控', 201); + + // appended strings + $stdGSMAppendedString = 'too long'; + $extGSMAppendedString = '[too long]'; + $UCS2AppendedString = '[控控]'; + + return array( + + // maximum number of standard GSM characters + array($stdGSMx459, $stdGSMx459, 3, 'N/A'), + + // maximum number of extended GSM characters + array($extGSMx229, $extGSMx229, 3, 'N/A'), + + // maximum number of alternated GSM characters + array($alternatedGSMx153, $alternatedGSMx153, 3, 'N/A'), + + // standard GSM, one 'a' too many, appended with standard GSM characters + array(str_repeat('a', 451) . $stdGSMAppendedString, $stdGSMx459 . 'a', 3, $stdGSMAppendedString), + + // standard GSM, one 'a' too many, appended with extended GSM characters + array(str_repeat('a', 447) . $extGSMAppendedString, $stdGSMx459 . 'a', 3, $extGSMAppendedString), + + // standard GSM, one 'a' too many, appended with UCS2 characters + array(str_repeat('a', 197) . $UCS2AppendedString, $stdGSMx459 . 'a', 3, $UCS2AppendedString), + + // extended GSM, one '€' too many, appended with standard GSM characters + array(str_repeat('€', 225) . $stdGSMAppendedString, $extGSMx229 . '€', 3, $stdGSMAppendedString), + + // extended GSM, one '€' too many, appended with extended GSM characters + array(str_repeat('€', 223) . $extGSMAppendedString, $extGSMx229 . '€', 3, $extGSMAppendedString), + + // extended GSM, one '€' too many, appended with UCS2 characters + array(str_repeat('€', 197) . $UCS2AppendedString, $extGSMx229 . '€', 3, $UCS2AppendedString), + + // alternated GSM, one 'a' too many, appended with standard GSM characters + array(str_repeat('a€', 150) . 'a' . $stdGSMAppendedString, $alternatedGSMx153 . 'a', 3, $stdGSMAppendedString), + + // alternated GSM, one 'a' too many, appended with extended GSM characters + array(str_repeat('a€', 149) . $extGSMAppendedString, $alternatedGSMx153 . 'a', 3, $extGSMAppendedString), + + // alternated GSM, one 'a' too many, appended with UCS2 characters + array(str_repeat('a€', 98) . 'a' . $UCS2AppendedString, $alternatedGSMx153 . 'a', 3, $UCS2AppendedString), + + // alternated GSM, one '€' too many, appended with standard GSM characters + array(str_repeat('a€', 150) . 'a' . $stdGSMAppendedString, $alternatedGSMx153 . '€', 3, $stdGSMAppendedString), + + // alternated GSM, one '€' too many, appended with extended GSM characters + array(str_repeat('a€', 149) . $extGSMAppendedString, $alternatedGSMx153 . '€', 3, $extGSMAppendedString), + + // alternated GSM, one '€' too many, appended with UCS2 characters + array(str_repeat('a€', 98) . 'a' . $UCS2AppendedString, $alternatedGSMx153 . '€', 3, $UCS2AppendedString), + + // GSM with RegExp reserved special chars + array(str_repeat('a', 451) . $stdGSMAppendedString, $GSMWithRegExpSpecialChars, 3, $stdGSMAppendedString), + + // maximum number of UCS-2 characters + array($UCS2x201, $UCS2x201, 3, 'N/A'), + + // UCS-2, one '控' too many, appended with UCS2 characters + array(str_repeat('控', 197) . $UCS2AppendedString, $UCS2x201 . '控', 3, $UCS2AppendedString), + + // UCS-2, one '控' too many, appended with standard GSM characters + array(str_repeat('控', 193) . $stdGSMAppendedString, $UCS2x201 . '控', 3, $stdGSMAppendedString) + ); + } + + /** + * @group Plugins + * + * @dataProvider getTruncateTestCases + */ + public function testTruncate($expected, $stringToTruncate, $maximumNumberOfConcatenatedSMS, $appendedString) + { + $this->assertEquals( + $expected, + SMSProvider::truncate($stringToTruncate, $maximumNumberOfConcatenatedSMS, $appendedString) + ); + } + + /** + * Dataprovider for testContainsUCS2Characters + */ + public function getContainsUCS2CharactersTestCases() + { + return array( + array(false, 'too long'), + array(false, '[too long]'), + array(false, '€'), + array(true, '[控控]'), + ); + } + + /** + * @group Plugins + * + * @dataProvider getContainsUCS2CharactersTestCases + */ + public function testContainsUCS2Characters($expected, $stringToTest) + { + $this->assertEquals( + $expected, + SMSProvider::containsUCS2Characters($stringToTest) + ); + } + + /** + * @group Plugins + */ + public function testSanitizePhoneNumber() + { + $this->assertEquals('676932647', APIMobileMessaging::sanitizePhoneNumber(' 6 76 93 26 47')); + } + + /** + * @group Plugins + */ + public function testPhoneNumberIsSanitized() + { + $mobileMessagingAPI = APIMobileMessaging::getInstance(); + $mobileMessagingAPI->setSMSAPICredential('StubbedProvider', ''); + $mobileMessagingAPI->addPhoneNumber(' 6 76 93 26 47'); + $this->assertEquals('676932647', key($mobileMessagingAPI->getPhoneNumbers())); + } + + /** + * Dataprovider for testSendReport + */ + public function getSendReportTestCases() + { + return array( + array('reportContent', '0101010101', 'Piwik.org', 'reportContent', '0101010101', 'Piwik.org'), + array('reportContent', '0101010101', 'General_Reports', 'reportContent', '0101010101', 'General_MultiSitesSummary'), + ); + } + + /** + * @group Plugins + * + * @dataProvider getSendReportTestCases + */ + public function testSendReport($expectedReportContent, $expectedPhoneNumber, $expectedFrom, $reportContent, $phoneNumber, $reportSubject) + { + $report = array( + 'parameters' => array(MobileMessaging::PHONE_NUMBERS_PARAMETER => array($phoneNumber)), + ); + + $stubbedAPIMobileMessaging = $this->getMock('\\Piwik\\Plugins\\MobileMessaging\\API', array('sendSMS', 'getInstance'), $arguments = array(), $mockClassName = '', $callOriginalConstructor = false); + $stubbedAPIMobileMessaging->expects($this->once())->method('sendSMS')->with( + $this->equalTo($expectedReportContent, 0), + $this->equalTo($expectedPhoneNumber, 1), + $this->equalTo($expectedFrom, 2) + ); + + \Piwik\Plugins\MobileMessaging\API::setSingletonInstance($stubbedAPIMobileMessaging); + + $mobileMessaging = new MobileMessaging(); + $mobileMessaging->sendReport(MobileMessaging::MOBILE_TYPE, $report, $reportContent, null, null, $reportSubject, null, null); + + \Piwik\Plugins\MobileMessaging\API::unsetInstance(); + } +} diff --git a/plugins/MobileMessaging/tests/MobileMessagingTest.php b/plugins/MobileMessaging/tests/MobileMessagingTest.php deleted file mode 100644 index dab19beb83..0000000000 --- a/plugins/MobileMessaging/tests/MobileMessagingTest.php +++ /dev/null @@ -1,262 +0,0 @@ -idSiteAccess = APISitesManager::getInstance()->addSite("test", "http://test"); - - \Piwik\Plugin\Manager::getInstance()->loadPlugins(array('ScheduledReports', 'MobileMessaging', 'MultiSites')); - \Piwik\Plugin\Manager::getInstance()->installLoadedPlugins(); - } - - /** - * When the MultiSites plugin is not activated, the SMS content should invite the user to activate it back - * - * @group Plugins - */ - public function testWarnUserViaSMSMultiSitesDeactivated() - { - // safety net - \Piwik\Plugin\Manager::getInstance()->loadPlugins(array('ScheduledReports', 'MobileMessaging')); - $this->assertFalse(\Piwik\Plugin\Manager::getInstance()->isPluginActivated('MultiSites')); - - $APIScheduledReports = APIScheduledReports::getInstance(); - $reportId = $APIScheduledReports->addReport( - $this->idSiteAccess, - 'description', - 'month', - 0, - 'mobile', - 'sms', - array(), - array("phoneNumbers" => array('33698896656')) - ); - - list($outputFilename, $prettyDate, $websiteName, $additionalFiles) = - $APIScheduledReports->generateReport( - $reportId, - '01-01-2010', - 'en', - 2 - ); - - $handle = fopen($outputFilename, "r"); - $contents = fread($handle, filesize($outputFilename)); - fclose($handle); - - $this->assertEquals( - \Piwik\Piwik::translate('MobileMessaging_MultiSites_Must_Be_Activated'), - $contents - ); - } - - /** - * Dataprovider for testTruncate - */ - public function getTruncateTestCases() - { - - $stdGSMx459 = str_repeat('a', 459); - - $extGSMx229 = str_repeat('€', 229); - - $alternatedGSMx153 = str_repeat('a€', 153); - - $GSMWithRegExpSpecialChars = $stdGSMx459 . '[\^$.|?*/+()'; - - $UCS2x201 = str_repeat('控', 201); - - // appended strings - $stdGSMAppendedString = 'too long'; - $extGSMAppendedString = '[too long]'; - $UCS2AppendedString = '[控控]'; - - return array( - - // maximum number of standard GSM characters - array($stdGSMx459, $stdGSMx459, 3, 'N/A'), - - // maximum number of extended GSM characters - array($extGSMx229, $extGSMx229, 3, 'N/A'), - - // maximum number of alternated GSM characters - array($alternatedGSMx153, $alternatedGSMx153, 3, 'N/A'), - - // standard GSM, one 'a' too many, appended with standard GSM characters - array(str_repeat('a', 451) . $stdGSMAppendedString, $stdGSMx459 . 'a', 3, $stdGSMAppendedString), - - // standard GSM, one 'a' too many, appended with extended GSM characters - array(str_repeat('a', 447) . $extGSMAppendedString, $stdGSMx459 . 'a', 3, $extGSMAppendedString), - - // standard GSM, one 'a' too many, appended with UCS2 characters - array(str_repeat('a', 197) . $UCS2AppendedString, $stdGSMx459 . 'a', 3, $UCS2AppendedString), - - // extended GSM, one '€' too many, appended with standard GSM characters - array(str_repeat('€', 225) . $stdGSMAppendedString, $extGSMx229 . '€', 3, $stdGSMAppendedString), - - // extended GSM, one '€' too many, appended with extended GSM characters - array(str_repeat('€', 223) . $extGSMAppendedString, $extGSMx229 . '€', 3, $extGSMAppendedString), - - // extended GSM, one '€' too many, appended with UCS2 characters - array(str_repeat('€', 197) . $UCS2AppendedString, $extGSMx229 . '€', 3, $UCS2AppendedString), - - // alternated GSM, one 'a' too many, appended with standard GSM characters - array(str_repeat('a€', 150) . 'a' . $stdGSMAppendedString, $alternatedGSMx153 . 'a', 3, $stdGSMAppendedString), - - // alternated GSM, one 'a' too many, appended with extended GSM characters - array(str_repeat('a€', 149) . $extGSMAppendedString, $alternatedGSMx153 . 'a', 3, $extGSMAppendedString), - - // alternated GSM, one 'a' too many, appended with UCS2 characters - array(str_repeat('a€', 98) . 'a' . $UCS2AppendedString, $alternatedGSMx153 . 'a', 3, $UCS2AppendedString), - - // alternated GSM, one '€' too many, appended with standard GSM characters - array(str_repeat('a€', 150) . 'a' . $stdGSMAppendedString, $alternatedGSMx153 . '€', 3, $stdGSMAppendedString), - - // alternated GSM, one '€' too many, appended with extended GSM characters - array(str_repeat('a€', 149) . $extGSMAppendedString, $alternatedGSMx153 . '€', 3, $extGSMAppendedString), - - // alternated GSM, one '€' too many, appended with UCS2 characters - array(str_repeat('a€', 98) . 'a' . $UCS2AppendedString, $alternatedGSMx153 . '€', 3, $UCS2AppendedString), - - // GSM with RegExp reserved special chars - array(str_repeat('a', 451) . $stdGSMAppendedString, $GSMWithRegExpSpecialChars, 3, $stdGSMAppendedString), - - // maximum number of UCS-2 characters - array($UCS2x201, $UCS2x201, 3, 'N/A'), - - // UCS-2, one '控' too many, appended with UCS2 characters - array(str_repeat('控', 197) . $UCS2AppendedString, $UCS2x201 . '控', 3, $UCS2AppendedString), - - // UCS-2, one '控' too many, appended with standard GSM characters - array(str_repeat('控', 193) . $stdGSMAppendedString, $UCS2x201 . '控', 3, $stdGSMAppendedString) - ); - } - - /** - * @group Plugins - * - * @dataProvider getTruncateTestCases - */ - public function testTruncate($expected, $stringToTruncate, $maximumNumberOfConcatenatedSMS, $appendedString) - { - $this->assertEquals( - $expected, - SMSProvider::truncate($stringToTruncate, $maximumNumberOfConcatenatedSMS, $appendedString) - ); - } - - /** - * Dataprovider for testContainsUCS2Characters - */ - public function getContainsUCS2CharactersTestCases() - { - return array( - array(false, 'too long'), - array(false, '[too long]'), - array(false, '€'), - array(true, '[控控]'), - ); - } - - /** - * @group Plugins - * - * @dataProvider getContainsUCS2CharactersTestCases - */ - public function testContainsUCS2Characters($expected, $stringToTest) - { - $this->assertEquals( - $expected, - SMSProvider::containsUCS2Characters($stringToTest) - ); - } - - /** - * @group Plugins - */ - public function testSanitizePhoneNumber() - { - $this->assertEquals('676932647', APIMobileMessaging::sanitizePhoneNumber(' 6 76 93 26 47')); - } - - /** - * @group Plugins - */ - public function testPhoneNumberIsSanitized() - { - $mobileMessagingAPI = APIMobileMessaging::getInstance(); - $mobileMessagingAPI->setSMSAPICredential('StubbedProvider', ''); - $mobileMessagingAPI->addPhoneNumber(' 6 76 93 26 47'); - $this->assertEquals('676932647', key($mobileMessagingAPI->getPhoneNumbers())); - } - - /** - * Dataprovider for testSendReport - */ - public function getSendReportTestCases() - { - return array( - array('reportContent', '0101010101', 'Piwik.org', 'reportContent', '0101010101', 'Piwik.org'), - array('reportContent', '0101010101', 'General_Reports', 'reportContent', '0101010101', 'General_MultiSitesSummary'), - ); - } - - /** - * @group Plugins - * - * @dataProvider getSendReportTestCases - */ - public function testSendReport($expectedReportContent, $expectedPhoneNumber, $expectedFrom, $reportContent, $phoneNumber, $reportSubject) - { - $report = array( - 'parameters' => array(MobileMessaging::PHONE_NUMBERS_PARAMETER => array($phoneNumber)), - ); - - $stubbedAPIMobileMessaging = $this->getMock('\\Piwik\\Plugins\\MobileMessaging\\API', array('sendSMS', 'getInstance'), $arguments = array(), $mockClassName = '', $callOriginalConstructor = false); - $stubbedAPIMobileMessaging->expects($this->once())->method('sendSMS')->with( - $this->equalTo($expectedReportContent, 0), - $this->equalTo($expectedPhoneNumber, 1), - $this->equalTo($expectedFrom, 2) - ); - - \Piwik\Plugins\MobileMessaging\API::setSingletonInstance($stubbedAPIMobileMessaging); - - $mobileMessaging = new MobileMessaging(); - $mobileMessaging->sendReport(MobileMessaging::MOBILE_TYPE, $report, $reportContent, null, null, $reportSubject, null, null); - - \Piwik\Plugins\MobileMessaging\API::unsetInstance(); - } -} diff --git a/plugins/MultiSites/tests/Integration/MultiSitesTest.php b/plugins/MultiSites/tests/Integration/MultiSitesTest.php new file mode 100644 index 0000000000..5f07c7131c --- /dev/null +++ b/plugins/MultiSites/tests/Integration/MultiSitesTest.php @@ -0,0 +1,52 @@ +setSuperUserAccess(true); + + $this->idSiteAccess = APISitesManager::getInstance()->addSite("test", "http://test"); + + \Piwik\Plugin\Manager::getInstance()->loadPlugins(array('MultiSites', 'VisitsSummary', 'Actions')); + \Piwik\Plugin\Manager::getInstance()->installLoadedPlugins(); + } + + /** + * Testing that getOne returns a row even when there are no data + * This is necessary otherwise ResponseBuilder throws 'Call to a member function getColumns() on a non-object' + * + * @group Plugins + */ + public function testWhenNoDataGetOneReturnsRow() + { + $dataTable = APIMultiSites::getInstance()->getOne($this->idSiteAccess, 'month', '01-01-2010'); + $this->assertEquals(1, $dataTable->getRowsCount()); + + // safety net + $this->assertEquals(0, $dataTable->getFirstRow()->getColumn('nb_visits')); + } +} diff --git a/plugins/MultiSites/tests/MultiSitesTest.php b/plugins/MultiSites/tests/MultiSitesTest.php deleted file mode 100644 index 9f317d5ca7..0000000000 --- a/plugins/MultiSites/tests/MultiSitesTest.php +++ /dev/null @@ -1,52 +0,0 @@ -setSuperUserAccess(true); - - $this->idSiteAccess = APISitesManager::getInstance()->addSite("test", "http://test"); - - \Piwik\Plugin\Manager::getInstance()->loadPlugins(array('MultiSites', 'VisitsSummary', 'Actions')); - \Piwik\Plugin\Manager::getInstance()->installLoadedPlugins(); - } - - /** - * Testing that getOne returns a row even when there are no data - * This is necessary otherwise ResponseBuilder throws 'Call to a member function getColumns() on a non-object' - * - * @group Plugins - */ - public function testWhenNoDataGetOneReturnsRow() - { - $dataTable = APIMultiSites::getInstance()->getOne($this->idSiteAccess, 'month', '01-01-2010'); - $this->assertEquals(1, $dataTable->getRowsCount()); - - // safety net - $this->assertEquals(0, $dataTable->getFirstRow()->getColumn('nb_visits')); - } -} diff --git a/plugins/PrivacyManager/tests/AnonymizeIPTest.php b/plugins/PrivacyManager/tests/AnonymizeIPTest.php deleted file mode 100644 index 0ed4e6e4ca..0000000000 --- a/plugins/PrivacyManager/tests/AnonymizeIPTest.php +++ /dev/null @@ -1,92 +0,0 @@ -assertEquals($expected[$maskLength], $res, "Got " . bin2hex($res) . ", Expected " . bin2hex($expected[$maskLength])); - } - - // edge case (bounds check) - $this->assertEquals("\x00\x00\x00\x00", IPAnonymizer::applyIPMask(IP::P2N($ip), 5)); - - // mask IPv4 mapped addresses - for ($maskLength = 0; $maskLength <= 4; $maskLength++) { - $res = IPAnonymizer::applyIPMask(IP::P2N('::ffff:' . $ip), $maskLength); - $this->assertEquals($res, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff" . $expected[$maskLength], "Got " . bin2hex($res) . ", Expected " . bin2hex($expected[$maskLength])); - } - $this->assertEquals("\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\x00\x00\x00\x00\x00", IPAnonymizer::applyIPMask(IP::P2N('::ffff:' . $ip), 5)); - } - - /** - * @dataProvider getipv6Addresses - * @group Plugins - */ - public function testApplyIPMask6($ip, $expected) - { - // each IP is tested with 0 to 4 octets masked - for ($maskLength = 0; $maskLength < 4; $maskLength++) { - $res = IPAnonymizer::applyIPMask(IP::P2N($ip), $maskLength); - $this->assertEquals($expected[$maskLength], $res, "Got " . bin2hex($res) . ", Expected " . bin2hex($expected[$maskLength]) . ", Mask Level " . $maskLength); - } - } -} \ No newline at end of file diff --git a/plugins/PrivacyManager/tests/Integration/PrivacyManagerConfigTest.php b/plugins/PrivacyManager/tests/Integration/PrivacyManagerConfigTest.php new file mode 100644 index 0000000000..88194e78f1 --- /dev/null +++ b/plugins/PrivacyManager/tests/Integration/PrivacyManagerConfigTest.php @@ -0,0 +1,102 @@ +config = new PrivacyManagerConfig(); + } + + public function test_useAnonymizedIpForVisitEnrichment() + { + $this->assertTrue($this->config->useAnonymizedIpForVisitEnrichment); + + $this->config->useAnonymizedIpForVisitEnrichment = false; + + $this->assertFalse($this->config->useAnonymizedIpForVisitEnrichment); + + $this->config->useAnonymizedIpForVisitEnrichment = true; + + $this->assertTrue($this->config->useAnonymizedIpForVisitEnrichment); + } + + public function test_doNotTrackEnabled() + { + $this->assertTrue($this->config->doNotTrackEnabled); + + $this->config->doNotTrackEnabled = true; + + $this->assertTrue($this->config->doNotTrackEnabled); + + $this->config->doNotTrackEnabled = false; + + $this->assertFalse($this->config->doNotTrackEnabled); + } + + public function test_ipAnonymizerEnabled() + { + $this->assertFalse($this->config->ipAnonymizerEnabled); + + $this->config->ipAnonymizerEnabled = true; + + $this->assertTrue($this->config->ipAnonymizerEnabled); + } + + public function test_ipAddressMaskLength() + { + $this->assertSame(1, $this->config->ipAddressMaskLength); + + $this->config->ipAddressMaskLength = '19'; + + $this->assertSame(19, $this->config->ipAddressMaskLength); + } + + public function test_setTrackerCacheContent() + { + $content = $this->config->setTrackerCacheGeneral(array('existingEntry' => 'test')); + + $expected = array( + 'existingEntry' => 'test', + 'PrivacyManager.ipAddressMaskLength' => 1, + 'PrivacyManager.ipAnonymizerEnabled' => false, + 'PrivacyManager.doNotTrackEnabled' => true, + 'PrivacyManager.useAnonymizedIpForVisitEnrichment' => true, + ); + + $this->assertEquals($expected, $content); + } + + public function test_setTrackerCacheContent_ShouldGetValuesFromConfig() + { + Option::set('PrivacyManager.ipAddressMaskLength', '232'); + + $content = $this->config->setTrackerCacheGeneral(array('existingEntry' => 'test')); + + $this->assertEquals(232, $content['PrivacyManager.ipAddressMaskLength']); + } + +} diff --git a/plugins/PrivacyManager/tests/Integration/PrivacyManagerTest.php b/plugins/PrivacyManager/tests/Integration/PrivacyManagerTest.php new file mode 100644 index 0000000000..f9e3b43079 --- /dev/null +++ b/plugins/PrivacyManager/tests/Integration/PrivacyManagerTest.php @@ -0,0 +1,86 @@ +manager = new PrivacyManager(); + \Piwik\Option::set('delete_logs_enable', 1); + \Piwik\Option::set('delete_logs_older_than', 270); + \Piwik\Option::set('delete_reports_keep_week_reports', 1); + } + + public function test_getPurgeDataSettings_shouldUseOnlyConfigValuesIfUIisDisabled() + { + $this->setUIEnabled(false); + + $settings = $this->manager->getPurgeDataSettings(); + $expected = $this->getDefaultPurgeSettings(); + + $this->assertEquals($expected, $settings); + } + + public function test_getPurgeDataSettings_shouldAlsoUseOptionValuesIfUIisEnabled() + { + $this->setUIEnabled(true); + + $settings = $this->manager->getPurgeDataSettings(); + $expected = $this->getDefaultPurgeSettings(); + + $expected['delete_logs_enable'] = 1; + $expected['delete_logs_older_than'] = 270; + $expected['delete_reports_keep_week_reports'] = 1; + + $this->assertEquals($expected, $settings); + } + + private function setUIEnabled($enabled) + { + \Piwik\Config::getInstance()->General['enable_delete_old_data_settings_admin'] = $enabled; + } + + private function getDefaultPurgeSettings() + { + $expected = array( + 'delete_logs_enable' => 0, + 'delete_logs_schedule_lowest_interval' => 7, + 'delete_logs_older_than' => 180, + 'delete_logs_max_rows_per_query' => 100000, + 'enable_auto_database_size_estimate' => 1, + 'delete_reports_enable' => 0, + 'delete_reports_older_than' => 12, + 'delete_reports_keep_basic_metrics' => 1, + 'delete_reports_keep_day_reports' => 0, + 'delete_reports_keep_week_reports' => 0, + 'delete_reports_keep_month_reports' => 1, + 'delete_reports_keep_year_reports' => 1, + 'delete_reports_keep_range_reports' => 0, + 'delete_reports_keep_segment_reports' => 0, + ); + return $expected; + } + +} diff --git a/plugins/PrivacyManager/tests/PrivacyManagerConfigTest.php b/plugins/PrivacyManager/tests/PrivacyManagerConfigTest.php deleted file mode 100644 index 88194e78f1..0000000000 --- a/plugins/PrivacyManager/tests/PrivacyManagerConfigTest.php +++ /dev/null @@ -1,102 +0,0 @@ -config = new PrivacyManagerConfig(); - } - - public function test_useAnonymizedIpForVisitEnrichment() - { - $this->assertTrue($this->config->useAnonymizedIpForVisitEnrichment); - - $this->config->useAnonymizedIpForVisitEnrichment = false; - - $this->assertFalse($this->config->useAnonymizedIpForVisitEnrichment); - - $this->config->useAnonymizedIpForVisitEnrichment = true; - - $this->assertTrue($this->config->useAnonymizedIpForVisitEnrichment); - } - - public function test_doNotTrackEnabled() - { - $this->assertTrue($this->config->doNotTrackEnabled); - - $this->config->doNotTrackEnabled = true; - - $this->assertTrue($this->config->doNotTrackEnabled); - - $this->config->doNotTrackEnabled = false; - - $this->assertFalse($this->config->doNotTrackEnabled); - } - - public function test_ipAnonymizerEnabled() - { - $this->assertFalse($this->config->ipAnonymizerEnabled); - - $this->config->ipAnonymizerEnabled = true; - - $this->assertTrue($this->config->ipAnonymizerEnabled); - } - - public function test_ipAddressMaskLength() - { - $this->assertSame(1, $this->config->ipAddressMaskLength); - - $this->config->ipAddressMaskLength = '19'; - - $this->assertSame(19, $this->config->ipAddressMaskLength); - } - - public function test_setTrackerCacheContent() - { - $content = $this->config->setTrackerCacheGeneral(array('existingEntry' => 'test')); - - $expected = array( - 'existingEntry' => 'test', - 'PrivacyManager.ipAddressMaskLength' => 1, - 'PrivacyManager.ipAnonymizerEnabled' => false, - 'PrivacyManager.doNotTrackEnabled' => true, - 'PrivacyManager.useAnonymizedIpForVisitEnrichment' => true, - ); - - $this->assertEquals($expected, $content); - } - - public function test_setTrackerCacheContent_ShouldGetValuesFromConfig() - { - Option::set('PrivacyManager.ipAddressMaskLength', '232'); - - $content = $this->config->setTrackerCacheGeneral(array('existingEntry' => 'test')); - - $this->assertEquals(232, $content['PrivacyManager.ipAddressMaskLength']); - } - -} diff --git a/plugins/PrivacyManager/tests/PrivacyManagerTest.php b/plugins/PrivacyManager/tests/PrivacyManagerTest.php deleted file mode 100644 index f9e3b43079..0000000000 --- a/plugins/PrivacyManager/tests/PrivacyManagerTest.php +++ /dev/null @@ -1,86 +0,0 @@ -manager = new PrivacyManager(); - \Piwik\Option::set('delete_logs_enable', 1); - \Piwik\Option::set('delete_logs_older_than', 270); - \Piwik\Option::set('delete_reports_keep_week_reports', 1); - } - - public function test_getPurgeDataSettings_shouldUseOnlyConfigValuesIfUIisDisabled() - { - $this->setUIEnabled(false); - - $settings = $this->manager->getPurgeDataSettings(); - $expected = $this->getDefaultPurgeSettings(); - - $this->assertEquals($expected, $settings); - } - - public function test_getPurgeDataSettings_shouldAlsoUseOptionValuesIfUIisEnabled() - { - $this->setUIEnabled(true); - - $settings = $this->manager->getPurgeDataSettings(); - $expected = $this->getDefaultPurgeSettings(); - - $expected['delete_logs_enable'] = 1; - $expected['delete_logs_older_than'] = 270; - $expected['delete_reports_keep_week_reports'] = 1; - - $this->assertEquals($expected, $settings); - } - - private function setUIEnabled($enabled) - { - \Piwik\Config::getInstance()->General['enable_delete_old_data_settings_admin'] = $enabled; - } - - private function getDefaultPurgeSettings() - { - $expected = array( - 'delete_logs_enable' => 0, - 'delete_logs_schedule_lowest_interval' => 7, - 'delete_logs_older_than' => 180, - 'delete_logs_max_rows_per_query' => 100000, - 'enable_auto_database_size_estimate' => 1, - 'delete_reports_enable' => 0, - 'delete_reports_older_than' => 12, - 'delete_reports_keep_basic_metrics' => 1, - 'delete_reports_keep_day_reports' => 0, - 'delete_reports_keep_week_reports' => 0, - 'delete_reports_keep_month_reports' => 1, - 'delete_reports_keep_year_reports' => 1, - 'delete_reports_keep_range_reports' => 0, - 'delete_reports_keep_segment_reports' => 0, - ); - return $expected; - } - -} diff --git a/plugins/PrivacyManager/tests/Unit/AnonymizeIPTest.php b/plugins/PrivacyManager/tests/Unit/AnonymizeIPTest.php new file mode 100644 index 0000000000..0ed4e6e4ca --- /dev/null +++ b/plugins/PrivacyManager/tests/Unit/AnonymizeIPTest.php @@ -0,0 +1,92 @@ +assertEquals($expected[$maskLength], $res, "Got " . bin2hex($res) . ", Expected " . bin2hex($expected[$maskLength])); + } + + // edge case (bounds check) + $this->assertEquals("\x00\x00\x00\x00", IPAnonymizer::applyIPMask(IP::P2N($ip), 5)); + + // mask IPv4 mapped addresses + for ($maskLength = 0; $maskLength <= 4; $maskLength++) { + $res = IPAnonymizer::applyIPMask(IP::P2N('::ffff:' . $ip), $maskLength); + $this->assertEquals($res, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff" . $expected[$maskLength], "Got " . bin2hex($res) . ", Expected " . bin2hex($expected[$maskLength])); + } + $this->assertEquals("\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\x00\x00\x00\x00\x00", IPAnonymizer::applyIPMask(IP::P2N('::ffff:' . $ip), 5)); + } + + /** + * @dataProvider getipv6Addresses + * @group Plugins + */ + public function testApplyIPMask6($ip, $expected) + { + // each IP is tested with 0 to 4 octets masked + for ($maskLength = 0; $maskLength < 4; $maskLength++) { + $res = IPAnonymizer::applyIPMask(IP::P2N($ip), $maskLength); + $this->assertEquals($expected[$maskLength], $res, "Got " . bin2hex($res) . ", Expected " . bin2hex($expected[$maskLength]) . ", Mask Level " . $maskLength); + } + } +} \ No newline at end of file diff --git a/plugins/Proxy/tests/ProxyTest.php b/plugins/Proxy/tests/ProxyTest.php deleted file mode 100644 index 8b460a35cc..0000000000 --- a/plugins/Proxy/tests/ProxyTest.php +++ /dev/null @@ -1,48 +0,0 @@ -assertEquals($expected, Controller::isPiwikUrl($url)); - } -} - diff --git a/plugins/Proxy/tests/Unit/ProxyTest.php b/plugins/Proxy/tests/Unit/ProxyTest.php new file mode 100644 index 0000000000..fa0175d040 --- /dev/null +++ b/plugins/Proxy/tests/Unit/ProxyTest.php @@ -0,0 +1,48 @@ +assertEquals($expected, Controller::isPiwikUrl($url)); + } +} + diff --git a/plugins/Referrers/tests/ReferrersTest.php b/plugins/Referrers/tests/ReferrersTest.php deleted file mode 100644 index 909e6bf65e..0000000000 --- a/plugins/Referrers/tests/ReferrersTest.php +++ /dev/null @@ -1,246 +0,0 @@ - $searchEngine) { - $searchEngines[] = array($url, $searchEngine); - } - return $searchEngines; - } - - /** - * search engine has at least one keyword - * - * @group Plugins - * - * @dataProvider getSearchEngines - */ - public function testMissingSearchEngineKeyword($url, $searchEngine) - { - // Get list of search engines and first appearing URL - static $searchEngines = array(); - - $name = parse_url('http://' . $url); - if (!array_key_exists($searchEngine[0], $searchEngines)) { - $searchEngines[$searchEngine[0]] = $url; - - $this->assertTrue(!empty($searchEngine[1]), $name['host']); - } - } - - /** - * search engine is defined in DataFiles/SearchEngines.php but there's no favicon - * - * @group Plugins - * - * @dataProvider getSearchEngines - */ - public function testMissingSearchEngineIcons($url, $searchEngine) - { - // Get list of existing favicons - $favicons = scandir(PIWIK_PATH_TEST_TO_ROOT . '/plugins/Referrers/images/searchEngines/'); - - // Get list of search engines and first appearing URL - static $searchEngines = array(); - - $name = parse_url('http://' . $url); - if (!array_key_exists($searchEngine[0], $searchEngines)) { - $searchEngines[$searchEngine[0]] = $url; - - $this->assertTrue(in_array($name['host'] . '.png', $favicons), $name['host']); - } - } - - /** - * favicon exists but there's no corresponding search engine defined in DataFiles/SearchEngines.php - * - * @group Plugins - */ - public function testObsoleteSearchEngineIcons() - { - include PIWIK_PATH_TEST_TO_ROOT . '/core/DataFiles/SearchEngines.php'; - - // Get list of search engines and first appearing URL - $searchEngines = array(); - foreach ($GLOBALS['Piwik_SearchEngines'] as $url => $searchEngine) { - $name = parse_url('http://' . $url); - if (!array_key_exists($name['host'], $searchEngines)) { - $searchEngines[$name['host']] = true; - } - } - - // Get list of existing favicons - $favicons = scandir(PIWIK_PATH_TEST_TO_ROOT . '/plugins/Referrers/images/searchEngines/'); - foreach ($favicons as $name) { - if ($name[0] == '.' || strpos($name, 'xx.') === 0) { - continue; - } - - $host = substr($name, 0, -4); - $this->assertTrue(array_key_exists($host, $searchEngines), $host); - } - } - - /** - * get search engine host from url - * - * @group Plugins - */ - public function testGetSearchEngineHostFromUrl() - { - $data = array( - 'http://www.google.com/cse' => array('www.google.com', 'www.google.com/cse'), - 'http://www.google.com' => array('www.google.com', 'www.google.com'), - ); - - foreach ($data as $url => $expected) { - $this->assertEquals($expected[0], \Piwik\Plugins\Referrers\getSearchEngineHostFromUrl($url)); - $this->assertEquals($expected[1], \Piwik\Plugins\Referrers\getSearchEngineHostPathFromUrl($url)); - } - } - - /** - * Dataprovider for testGetSearchEngineUrlFromUrlAndKeyword - */ - public function getSearchEngineUrlFromUrlAndKeywordTestData() - { - return array( - array('http://apollo.lv/portal/search/', 'piwik', 'http://apollo.lv/portal/search/?cof=FORID%3A11&q=piwik&search_where=www'), - array('http://bing.com/images/search', 'piwik', 'http://bing.com/images/search/?q=piwik'), - array('http://google.com', 'piwik', 'http://google.com/search?q=piwik'), - ); - } - - /** - * get search engine url from name and keyword - * - * @group Plugins - * - * @dataProvider getSearchEngineUrlFromUrlAndKeywordTestData - */ - public function testGetSearchEngineUrlFromUrlAndKeyword($url, $keyword, $expected) - { - include PIWIK_PATH_TEST_TO_ROOT . '/core/DataFiles/SearchEngines.php'; - $this->assertEquals($expected, \Piwik\Plugins\Referrers\getSearchEngineUrlFromUrlAndKeyword($url, $keyword)); - } - - /** - * Dataprovider for getSocialNetworkFromDomainTestData - */ - public function getSocialNetworkFromDomainTestData() - { - return array( - array('http://www.facebook.com', 'Facebook'), - array('http://www.facebook.com/piwik', 'Facebook'), - array('http://m.facebook.com', 'Facebook'), - array('https://m.facebook.com', 'Facebook'), - array('m.facebook.com', 'Facebook'), - array('http://lastfm.com.tr', 'Last.fm'), - array('http://t.co/test', 'Twitter'), - array('http://xxt.co/test', \Piwik\Piwik::translate('General_Unknown')), - array('asdfasdfadsf.com', \Piwik\Piwik::translate('General_Unknown')), - array('http://xwayn.com', \Piwik\Piwik::translate('General_Unknown')), - array('http://live.com/test', \Piwik\Piwik::translate('General_Unknown')), - ); - } - - /** - * @group Plugins - * - * @dataProvider getSocialNetworkFromDomainTestData - */ - public function testGetSocialNetworkFromDomain($url, $expected) - { - include PIWIK_INCLUDE_PATH . '/core/DataFiles/Socials.php'; - $this->assertEquals($expected, \Piwik\Plugins\Referrers\getSocialNetworkFromDomain($url)); - } - - public function getSocialsLogoFromUrlTestData() - { - return array( - array('http://www.facebook.com', 'facebook.com.png'), - array('www.facebook.com', 'facebook.com.png',), - array('http://lastfm.com.tr', 'last.fm.png'), - array('http://asdfasdf.org/test', 'xx.png'), - array('http://www.google.com', 'xx.png'), - ); - } - - /** - * @group Plugins - * - * @dataProvider getSocialsLogoFromUrlTestData - */ - public function testGetSocialsLogoFromUrl($url, $expected) - { - include PIWIK_INCLUDE_PATH . '/core/DataFiles/Socials.php'; - $this->assertContains($expected, \Piwik\Plugins\Referrers\getSocialsLogoFromUrl($url)); - } - - public function isSocialUrlTestData() - { - return array( - array('http://www.facebook.com', 'Facebook', true), - array('http://www.facebook.com', 'Twitter', false), - array('http://m.facebook.com', false, true), - array('http://lastfm.com.tr', 'Last.fm', true), - array('http://asdfasdf.org/test', false, false), - array('http://asdfasdf.com/test', 'Facebook', false), - ); - } - - /** - * @group Plugins - * - * @dataProvider isSocialUrlTestData - */ - public function testIsSocialUrl($url, $assumedSocial, $expected) - { - include PIWIK_INCLUDE_PATH . '/core/DataFiles/Socials.php'; - $this->assertEquals($expected, \Piwik\Plugins\Referrers\isSocialUrl($url, $assumedSocial)); - } - - public function removeUrlProtocolTestData() - { - return array( - array('http://www.facebook.com', 'www.facebook.com'), - array('https://bla.fr', 'bla.fr'), - array('ftp://bla.fr', 'bla.fr'), - array('udp://bla.fr', 'bla.fr'), - array('bla.fr', 'bla.fr'), - array('ASDasdASDDasd', 'ASDasdASDDasd'), - ); - } - - /** - * @group Plugins - * - * @dataProvider removeUrlProtocolTestData - */ - public function testRemoveUrlProtocol($url, $expected) - { - $this->assertEquals($expected, \Piwik\Plugins\Referrers\removeUrlProtocol($url)); - } -} diff --git a/plugins/Referrers/tests/Unit/ReferrersTest.php b/plugins/Referrers/tests/Unit/ReferrersTest.php new file mode 100644 index 0000000000..909e6bf65e --- /dev/null +++ b/plugins/Referrers/tests/Unit/ReferrersTest.php @@ -0,0 +1,246 @@ + $searchEngine) { + $searchEngines[] = array($url, $searchEngine); + } + return $searchEngines; + } + + /** + * search engine has at least one keyword + * + * @group Plugins + * + * @dataProvider getSearchEngines + */ + public function testMissingSearchEngineKeyword($url, $searchEngine) + { + // Get list of search engines and first appearing URL + static $searchEngines = array(); + + $name = parse_url('http://' . $url); + if (!array_key_exists($searchEngine[0], $searchEngines)) { + $searchEngines[$searchEngine[0]] = $url; + + $this->assertTrue(!empty($searchEngine[1]), $name['host']); + } + } + + /** + * search engine is defined in DataFiles/SearchEngines.php but there's no favicon + * + * @group Plugins + * + * @dataProvider getSearchEngines + */ + public function testMissingSearchEngineIcons($url, $searchEngine) + { + // Get list of existing favicons + $favicons = scandir(PIWIK_PATH_TEST_TO_ROOT . '/plugins/Referrers/images/searchEngines/'); + + // Get list of search engines and first appearing URL + static $searchEngines = array(); + + $name = parse_url('http://' . $url); + if (!array_key_exists($searchEngine[0], $searchEngines)) { + $searchEngines[$searchEngine[0]] = $url; + + $this->assertTrue(in_array($name['host'] . '.png', $favicons), $name['host']); + } + } + + /** + * favicon exists but there's no corresponding search engine defined in DataFiles/SearchEngines.php + * + * @group Plugins + */ + public function testObsoleteSearchEngineIcons() + { + include PIWIK_PATH_TEST_TO_ROOT . '/core/DataFiles/SearchEngines.php'; + + // Get list of search engines and first appearing URL + $searchEngines = array(); + foreach ($GLOBALS['Piwik_SearchEngines'] as $url => $searchEngine) { + $name = parse_url('http://' . $url); + if (!array_key_exists($name['host'], $searchEngines)) { + $searchEngines[$name['host']] = true; + } + } + + // Get list of existing favicons + $favicons = scandir(PIWIK_PATH_TEST_TO_ROOT . '/plugins/Referrers/images/searchEngines/'); + foreach ($favicons as $name) { + if ($name[0] == '.' || strpos($name, 'xx.') === 0) { + continue; + } + + $host = substr($name, 0, -4); + $this->assertTrue(array_key_exists($host, $searchEngines), $host); + } + } + + /** + * get search engine host from url + * + * @group Plugins + */ + public function testGetSearchEngineHostFromUrl() + { + $data = array( + 'http://www.google.com/cse' => array('www.google.com', 'www.google.com/cse'), + 'http://www.google.com' => array('www.google.com', 'www.google.com'), + ); + + foreach ($data as $url => $expected) { + $this->assertEquals($expected[0], \Piwik\Plugins\Referrers\getSearchEngineHostFromUrl($url)); + $this->assertEquals($expected[1], \Piwik\Plugins\Referrers\getSearchEngineHostPathFromUrl($url)); + } + } + + /** + * Dataprovider for testGetSearchEngineUrlFromUrlAndKeyword + */ + public function getSearchEngineUrlFromUrlAndKeywordTestData() + { + return array( + array('http://apollo.lv/portal/search/', 'piwik', 'http://apollo.lv/portal/search/?cof=FORID%3A11&q=piwik&search_where=www'), + array('http://bing.com/images/search', 'piwik', 'http://bing.com/images/search/?q=piwik'), + array('http://google.com', 'piwik', 'http://google.com/search?q=piwik'), + ); + } + + /** + * get search engine url from name and keyword + * + * @group Plugins + * + * @dataProvider getSearchEngineUrlFromUrlAndKeywordTestData + */ + public function testGetSearchEngineUrlFromUrlAndKeyword($url, $keyword, $expected) + { + include PIWIK_PATH_TEST_TO_ROOT . '/core/DataFiles/SearchEngines.php'; + $this->assertEquals($expected, \Piwik\Plugins\Referrers\getSearchEngineUrlFromUrlAndKeyword($url, $keyword)); + } + + /** + * Dataprovider for getSocialNetworkFromDomainTestData + */ + public function getSocialNetworkFromDomainTestData() + { + return array( + array('http://www.facebook.com', 'Facebook'), + array('http://www.facebook.com/piwik', 'Facebook'), + array('http://m.facebook.com', 'Facebook'), + array('https://m.facebook.com', 'Facebook'), + array('m.facebook.com', 'Facebook'), + array('http://lastfm.com.tr', 'Last.fm'), + array('http://t.co/test', 'Twitter'), + array('http://xxt.co/test', \Piwik\Piwik::translate('General_Unknown')), + array('asdfasdfadsf.com', \Piwik\Piwik::translate('General_Unknown')), + array('http://xwayn.com', \Piwik\Piwik::translate('General_Unknown')), + array('http://live.com/test', \Piwik\Piwik::translate('General_Unknown')), + ); + } + + /** + * @group Plugins + * + * @dataProvider getSocialNetworkFromDomainTestData + */ + public function testGetSocialNetworkFromDomain($url, $expected) + { + include PIWIK_INCLUDE_PATH . '/core/DataFiles/Socials.php'; + $this->assertEquals($expected, \Piwik\Plugins\Referrers\getSocialNetworkFromDomain($url)); + } + + public function getSocialsLogoFromUrlTestData() + { + return array( + array('http://www.facebook.com', 'facebook.com.png'), + array('www.facebook.com', 'facebook.com.png',), + array('http://lastfm.com.tr', 'last.fm.png'), + array('http://asdfasdf.org/test', 'xx.png'), + array('http://www.google.com', 'xx.png'), + ); + } + + /** + * @group Plugins + * + * @dataProvider getSocialsLogoFromUrlTestData + */ + public function testGetSocialsLogoFromUrl($url, $expected) + { + include PIWIK_INCLUDE_PATH . '/core/DataFiles/Socials.php'; + $this->assertContains($expected, \Piwik\Plugins\Referrers\getSocialsLogoFromUrl($url)); + } + + public function isSocialUrlTestData() + { + return array( + array('http://www.facebook.com', 'Facebook', true), + array('http://www.facebook.com', 'Twitter', false), + array('http://m.facebook.com', false, true), + array('http://lastfm.com.tr', 'Last.fm', true), + array('http://asdfasdf.org/test', false, false), + array('http://asdfasdf.com/test', 'Facebook', false), + ); + } + + /** + * @group Plugins + * + * @dataProvider isSocialUrlTestData + */ + public function testIsSocialUrl($url, $assumedSocial, $expected) + { + include PIWIK_INCLUDE_PATH . '/core/DataFiles/Socials.php'; + $this->assertEquals($expected, \Piwik\Plugins\Referrers\isSocialUrl($url, $assumedSocial)); + } + + public function removeUrlProtocolTestData() + { + return array( + array('http://www.facebook.com', 'www.facebook.com'), + array('https://bla.fr', 'bla.fr'), + array('ftp://bla.fr', 'bla.fr'), + array('udp://bla.fr', 'bla.fr'), + array('bla.fr', 'bla.fr'), + array('ASDasdASDDasd', 'ASDasdASDDasd'), + ); + } + + /** + * @group Plugins + * + * @dataProvider removeUrlProtocolTestData + */ + public function testRemoveUrlProtocol($url, $expected) + { + $this->assertEquals($expected, \Piwik\Plugins\Referrers\removeUrlProtocol($url)); + } +} diff --git a/plugins/SEO/tests/SEOTest.php b/plugins/SEO/tests/SEOTest.php deleted file mode 100644 index 06f627d2b4..0000000000 --- a/plugins/SEO/tests/SEOTest.php +++ /dev/null @@ -1,68 +0,0 @@ -getRank('http://www.microsoft.com/'); - } catch(Exception $e) { - $this->markTestSkipped('A SEO http request failed, Skipping this test for now. Error was: '.$e->getMessage()); - } - $renderer = Renderer::factory('php'); - $renderer->setSerialize(false); - $ranks = $renderer->render($dataTable); - foreach ($ranks as $rank) { - $message = $rank['id'] . ' expected non-zero rank, got [' . $rank['rank'] . ']'; - if(empty($rank['rank'])) { - $this->markTestSkipped("Skipped to avoid random build failure: " . $message); - } - $this->assertNotEmpty($rank['rank'], $message); - } - } -} diff --git a/plugins/SEO/tests/Unit/SEOTest.php b/plugins/SEO/tests/Unit/SEOTest.php new file mode 100644 index 0000000000..71cc2e341d --- /dev/null +++ b/plugins/SEO/tests/Unit/SEOTest.php @@ -0,0 +1,68 @@ +getRank('http://www.microsoft.com/'); + } catch(Exception $e) { + $this->markTestSkipped('A SEO http request failed, Skipping this test for now. Error was: '.$e->getMessage()); + } + $renderer = Renderer::factory('php'); + $renderer->setSerialize(false); + $ranks = $renderer->render($dataTable); + foreach ($ranks as $rank) { + $message = $rank['id'] . ' expected non-zero rank, got [' . $rank['rank'] . ']'; + if(empty($rank['rank'])) { + $this->markTestSkipped("Skipped to avoid random build failure: " . $message); + } + $this->assertNotEmpty($rank['rank'], $message); + } + } +} diff --git a/plugins/ScheduledReports/tests/ApiTest.php b/plugins/ScheduledReports/tests/ApiTest.php deleted file mode 100644 index 7f5f1649e0..0000000000 --- a/plugins/ScheduledReports/tests/ApiTest.php +++ /dev/null @@ -1,513 +0,0 @@ -loadPlugins(array('API', 'UserCountry', 'ScheduledReports', 'MobileMessaging')); - \Piwik\Plugin\Manager::getInstance()->installLoadedPlugins(); - - APISitesManager::getInstance()->addSite("Test", array("http://piwik.net")); - - APISitesManager::getInstance()->addSite("Test", array("http://piwik.net")); - FakeAccess::setIdSitesView(array($this->idSite, 2)); - APIScheduledReports::$cache = array(); - } - - /** - * @group Plugins - */ - public function testAddReportGetReports() - { - $data = array( - 'idsite' => $this->idSite, - 'description' => 'test description"', - 'type' => 'email', - 'period' => ScheduledTime::PERIOD_DAY, - 'hour' => '4', - 'format' => 'pdf', - 'reports' => array('UserCountry_getCountry'), - 'parameters' => array( - 'displayFormat' => '1', - 'emailMe' => true, - 'additionalEmails' => array('test@test.com', 't2@test.com'), - 'evolutionGraph' => true - ) - ); - - $dataWebsiteTwo = $data; - $dataWebsiteTwo['idsite'] = 2; - $dataWebsiteTwo['period'] = ScheduledTime::PERIOD_MONTH; - - self::addReport($dataWebsiteTwo); - - // Testing getReports without parameters - $tmp = APIScheduledReports::getInstance()->getReports(); - $report = reset($tmp); - $this->assertReportsEqual($report, $dataWebsiteTwo); - - $idReport = self::addReport($data); - - // Passing 3 parameters - $tmp = APIScheduledReports::getInstance()->getReports($this->idSite, $data['period'], $idReport); - $report = reset($tmp); - $this->assertReportsEqual($report, $data); - - // Passing only idsite - $tmp = APIScheduledReports::getInstance()->getReports($this->idSite); - $report = reset($tmp); - $this->assertReportsEqual($report, $data); - - // Passing only period - $tmp = APIScheduledReports::getInstance()->getReports($idSite = false, $data['period']); - $report = reset($tmp); - $this->assertReportsEqual($report, $data); - - // Passing only idreport - $tmp = APIScheduledReports::getInstance()->getReports($idSite = false, $period = false, $idReport); - $report = reset($tmp); - $this->assertReportsEqual($report, $data); - } - - /** - * @group Plugins - */ - public function testGetReportsIdReportNotFound() - { - try { - APIScheduledReports::getInstance()->getReports($idSite = false, $period = false, $idReport = 1); - } catch (Exception $e) { - return; - } - $this->fail('Expected exception not raised'); - } - - /** - * @group Plugins - */ - public function testGetReportsInvalidPermission() - { - try { - APIScheduledReports::getInstance()->getReports( - $idSite = 44, - $period = false, - self::addReport(self::getDailyPDFReportData($this->idSite)) - ); - - } catch (Exception $e) { - return; - } - $this->fail('Expected exception not raised'); - } - - /** - * @group Plugins - */ - public function testAddReportInvalidWebsite() - { - try { - self::addReport(self::getDailyPDFReportData(33)); - } catch (Exception $e) { - return; - } - $this->fail('Expected exception not raised'); - } - - /** - * @group Plugins - */ - public function testAddReportInvalidPeriod() - { - try { - $data = self::getDailyPDFReportData($this->idSite); - $data['period'] = 'dx'; - self::addReport($data); - } catch (Exception $e) { - return; - } - $this->fail('Expected exception not raised'); - } - - /** - * @group Plugins - */ - public function testUpdateReport() - { - $idReport = self::addReport(self::getDailyPDFReportData($this->idSite)); - $dataAfter = self::getMonthlyEmailReportData($this->idSite); - - self::updateReport($idReport, $dataAfter); - - $reports = APIScheduledReports::getInstance()->getReports($idSite = false, $period = false, $idReport); - - $this->assertReportsEqual( - reset($reports), - $dataAfter - ); - } - - /** - * @group Plugins - */ - public function testDeleteReport() - { - // Deletes non existing report throws exception - try { - APIScheduledReports::getInstance()->deleteReport($idReport = 1); - $this->fail('Exception not raised'); - } catch (Exception $e) { - } - - $idReport = self::addReport(self::getMonthlyEmailReportData($this->idSite)); - $this->assertEquals(1, count(APIScheduledReports::getInstance()->getReports())); - APIScheduledReports::getInstance()->deleteReport($idReport); - $this->assertEquals(0, count(APIScheduledReports::getInstance()->getReports())); - } - - /** - * @group Plugins - */ - public function testGetTopMenuTranslationKeyMobileMessagingInactive() - { - // unload MobileMessaging plugin - \Piwik\Plugin\Manager::getInstance()->loadPlugins(array('ScheduledReports')); - - $pdfReportPlugin = new Menu(); - $this->assertEquals( - Menu::PDF_REPORTS_TOP_MENU_TRANSLATION_KEY, - $pdfReportPlugin->getTopMenuTranslationKey() - ); - } - - /** - * @group Plugins - */ - public function testGetTopMenuTranslationKeyUserIsAnonymous() - { - $anonymousAccess = new FakeAccess; - FakeAccess::$identity = 'anonymous'; - Access::setSingletonInstance($anonymousAccess); - - $pdfReportPlugin = new Menu(); - $this->assertEquals( - Menu::MOBILE_MESSAGING_TOP_MENU_TRANSLATION_KEY, - $pdfReportPlugin->getTopMenuTranslationKey() - ); - } - - /** - * top menu should display 'Email & SMS reports' when the user has set-up a valid mobile provider account - * even though there is no sms reports configured - * - * @group Plugins - */ - public function testGetTopMenuTranslationKeyNoReportMobileAccountOK() - { - // set mobile provider account - self::setSuperUser(); - APIMobileMessaging::getInstance()->setSMSAPICredential('StubbedProvider', ''); - - $pdfReportPlugin = new Menu(); - $this->assertEquals( - Menu::MOBILE_MESSAGING_TOP_MENU_TRANSLATION_KEY, - $pdfReportPlugin->getTopMenuTranslationKey() - ); - } - - /** - * top menu should display 'Email reports' when the user has not set-up a valid mobile provider account - * and no reports at all have been configured - * - * @group Plugins - */ - public function testGetTopMenuTranslationKeyNoReportMobileAccountKO() - { - $pdfReportPlugin = new Menu(); - $this->assertEquals( - Menu::PDF_REPORTS_TOP_MENU_TRANSLATION_KEY, - $pdfReportPlugin->getTopMenuTranslationKey() - ); - } - - /** - * top menu should display 'Email & SMS reports' if there is at least one sms report - * whatever the status of the mobile provider account - * - * @group Plugins - */ - public function testGetTopMenuTranslationKeyOneSMSReportMobileAccountKO() - { - APIScheduledReports::getInstance()->addReport( - 1, - '', - ScheduledTime::PERIOD_DAY, - 0, - MobileMessaging::MOBILE_TYPE, - MobileMessaging::SMS_FORMAT, - array(), - array( - MobileMessaging::PHONE_NUMBERS_PARAMETER => array() - ) - ); - - $pdfReportPlugin = new Menu(); - $this->assertEquals( - Menu::MOBILE_MESSAGING_TOP_MENU_TRANSLATION_KEY, - $pdfReportPlugin->getTopMenuTranslationKey() - ); - } - - /** - * top menu should display 'Email reports' if there are no SMS reports and at least one email report - * whatever the status of the mobile provider account - * - * @group Plugins - */ - public function testGetTopMenuTranslationKeyNoSMSReportAccountOK() - { - // set mobile provider account - self::setSuperUser(); - APIMobileMessaging::getInstance()->setSMSAPICredential('StubbedProvider', ''); - - self::addReport(self::getMonthlyEmailReportData($this->idSite)); - - $pdfReportPlugin = new Menu(); - $this->assertEquals( - Menu::PDF_REPORTS_TOP_MENU_TRANSLATION_KEY, - $pdfReportPlugin->getTopMenuTranslationKey() - ); - } - - /** - * @group Plugins - */ - public function testGetScheduledTasks() - { - // stub API to control getReports() return values - $report1 = self::getDailyPDFReportData($this->idSite); - $report1['idreport'] = 1; - $report1['hour'] = 0; - $report1['deleted'] = 0; - - $report2 = self::getMonthlyEmailReportData($this->idSite); - $report2['idreport'] = 2; - $report2['idsite'] = 2; - $report2['hour'] = 0; - $report2['deleted'] = 0; - - $report3 = self::getMonthlyEmailReportData($this->idSite); - $report3['idreport'] = 3; - $report3['deleted'] = 1; // should not be scheduled - - $report4 = self::getMonthlyEmailReportData($this->idSite); - $report4['idreport'] = 4; - $report4['idsite'] = 1; - $report4['hour'] = 8; - $report4['deleted'] = 0; - - $report5 = self::getMonthlyEmailReportData($this->idSite); - $report5['idreport'] = 5; - $report5['idsite'] = 2; - $report5['hour'] = 8; - $report5['deleted'] = 0; - - // test no exception is raised when a scheduled report is set to never send - $report6 = self::getMonthlyEmailReportData($this->idSite); - $report6['idreport'] = 6; - $report6['period'] = ScheduledTime::PERIOD_NEVER; - $report6['deleted'] = 0; - - $stubbedAPIScheduledReports = $this->getMock('\\Piwik\\Plugins\\ScheduledReports\\API', array('getReports', 'getInstance'), $arguments = array(), $mockClassName = '', $callOriginalConstructor = false); - $stubbedAPIScheduledReports->expects($this->any())->method('getReports')->will($this->returnValue( - array($report1, $report2, $report3, $report4, $report5, $report6)) - ); - \Piwik\Plugins\ScheduledReports\API::setSingletonInstance($stubbedAPIScheduledReports); - - // initialize sites 1 and 2 - Site::setSites( array( - 1 => array('timezone' => 'Europe/Paris'), - 2 => array('timezone' => 'UTC-6.5'), - )); - - // expected tasks - $scheduleTask1 = ScheduledTime::factory('daily'); - $scheduleTask1->setHour(0); // paris is UTC-1, period ends at 23h UTC - $scheduleTask1->setTimezone('Europe/Paris'); - - $scheduleTask2 = new Monthly(); - $scheduleTask2->setHour(0); // site is UTC-6.5, period ends at 6h30 UTC, smallest resolution is hour - $scheduleTask2->setTimezone('UTC-6.5'); - - $scheduleTask3 = new Monthly(); - $scheduleTask3->setHour(8); // paris is UTC-1, configured to be sent at 8h - $scheduleTask3->setTimezone('Europe/Paris'); - - $scheduleTask4 = new Monthly(); - $scheduleTask4->setHour(8); // site is UTC-6.5, configured to be sent at 8h - $scheduleTask4->setTimezone('UTC-6.5'); - - $expectedTasks = array( - new ScheduledTask (APIScheduledReports::getInstance(), 'sendReport', 1, $scheduleTask1), - new ScheduledTask (APIScheduledReports::getInstance(), 'sendReport', 2, $scheduleTask2), - new ScheduledTask (APIScheduledReports::getInstance(), 'sendReport', 4, $scheduleTask3), - new ScheduledTask (APIScheduledReports::getInstance(), 'sendReport', 5, $scheduleTask4), - ); - - $pdfReportPlugin = new Tasks(); - $pdfReportPlugin->schedule(); - $tasks = $pdfReportPlugin->getScheduledTasks(); - $this->assertEquals($expectedTasks, $tasks); - - \Piwik\Plugins\ScheduledReports\API::unsetInstance(); - - } - - /** - * Dataprovider for testGetReportSubjectAndReportTitle - */ - public function getGetReportSubjectAndReportTitleTestCases() - { - return array( - array('Piwik.org', 'General_Website Piwik.org', 'Piwik.org', array('UserSettings_getBrowserType')), - array('Piwik.org', 'General_Website Piwik.org', 'Piwik.org', array('MultiSites_getAll', 'UserSettings_getBrowserType')), - array('General_MultiSitesSummary', 'General_MultiSitesSummary', 'Piwik.org', array('MultiSites_getAll')), - ); - } - - /** - * @group Plugins - * - * @dataProvider getGetReportSubjectAndReportTitleTestCases - */ - public function testGetReportSubjectAndReportTitle($expectedReportSubject, $expectedReportTitle, $websiteName, $reports) - { - $getReportSubjectAndReportTitle = new ReflectionMethod( - '\\Piwik\\Plugins\\ScheduledReports\\API', 'getReportSubjectAndReportTitle' - ); - $getReportSubjectAndReportTitle->setAccessible(true); - - list($reportSubject, $reportTitle) = $getReportSubjectAndReportTitle->invoke( APIScheduledReports::getInstance(), $websiteName, $reports); - $this->assertEquals($expectedReportSubject, $reportSubject); - $this->assertEquals($expectedReportTitle, $reportTitle); - } - - private function assertReportsEqual($report, $data) - { - foreach ($data as $key => $value) { - if ($key == 'description') $value = substr($value, 0, 250); - $this->assertEquals($value, $report[$key], "Error for $key for report " . var_export($report, true) . " and data " . var_export($data, true)); - } - } - - private static function addReport($data) - { - $idReport = APIScheduledReports::getInstance()->addReport( - $data['idsite'], - $data['description'], - $data['period'], - $data['hour'], - $data['type'], - $data['format'], - $data['reports'], - $data['parameters'] - ); - return $idReport; - } - - private static function getDailyPDFReportData($idSite) - { - return array( - 'idsite' => $idSite, - 'description' => 'test description"', - 'period' => ScheduledTime::PERIOD_DAY, - 'hour' => '7', - 'type' => 'email', - 'format' => 'pdf', - 'reports' => array('UserCountry_getCountry'), - 'parameters' => array( - 'displayFormat' => '1', - 'emailMe' => true, - 'additionalEmails' => array('test@test.com', 't2@test.com'), - 'evolutionGraph' => false - ) - ); - } - - private static function getMonthlyEmailReportData($idSite) - { - return array( - 'idsite' => $idSite, - 'description' => 'very very long and possibly truncated description. very very long and possibly truncated description. very very long and possibly truncated description. very very long and possibly truncated description. very very long and possibly truncated description. ', - 'period' => ScheduledTime::PERIOD_MONTH, - 'hour' => '0', - 'type' => 'email', - 'format' => 'pdf', - 'reports' => array('UserCountry_getContinent'), - 'parameters' => array( - 'displayFormat' => '1', - 'emailMe' => false, - 'additionalEmails' => array('blabla@ec.fr'), - 'evolutionGraph' => false - ) - ); - } - - private static function updateReport($idReport, $data) - { - $idReport = APIScheduledReports::getInstance()->updateReport( - $idReport, - $data['idsite'], - $data['description'], - $data['period'], - $data['hour'], - $data['type'], - $data['format'], - $data['reports'], - $data['parameters']); - return $idReport; - } - - private static function setSuperUser() - { - $pseudoMockAccess = new FakeAccess; - FakeAccess::$superUser = true; - Access::setSingletonInstance($pseudoMockAccess); - } -} diff --git a/plugins/ScheduledReports/tests/Integration/ApiTest.php b/plugins/ScheduledReports/tests/Integration/ApiTest.php new file mode 100644 index 0000000000..7f5f1649e0 --- /dev/null +++ b/plugins/ScheduledReports/tests/Integration/ApiTest.php @@ -0,0 +1,513 @@ +loadPlugins(array('API', 'UserCountry', 'ScheduledReports', 'MobileMessaging')); + \Piwik\Plugin\Manager::getInstance()->installLoadedPlugins(); + + APISitesManager::getInstance()->addSite("Test", array("http://piwik.net")); + + APISitesManager::getInstance()->addSite("Test", array("http://piwik.net")); + FakeAccess::setIdSitesView(array($this->idSite, 2)); + APIScheduledReports::$cache = array(); + } + + /** + * @group Plugins + */ + public function testAddReportGetReports() + { + $data = array( + 'idsite' => $this->idSite, + 'description' => 'test description"', + 'type' => 'email', + 'period' => ScheduledTime::PERIOD_DAY, + 'hour' => '4', + 'format' => 'pdf', + 'reports' => array('UserCountry_getCountry'), + 'parameters' => array( + 'displayFormat' => '1', + 'emailMe' => true, + 'additionalEmails' => array('test@test.com', 't2@test.com'), + 'evolutionGraph' => true + ) + ); + + $dataWebsiteTwo = $data; + $dataWebsiteTwo['idsite'] = 2; + $dataWebsiteTwo['period'] = ScheduledTime::PERIOD_MONTH; + + self::addReport($dataWebsiteTwo); + + // Testing getReports without parameters + $tmp = APIScheduledReports::getInstance()->getReports(); + $report = reset($tmp); + $this->assertReportsEqual($report, $dataWebsiteTwo); + + $idReport = self::addReport($data); + + // Passing 3 parameters + $tmp = APIScheduledReports::getInstance()->getReports($this->idSite, $data['period'], $idReport); + $report = reset($tmp); + $this->assertReportsEqual($report, $data); + + // Passing only idsite + $tmp = APIScheduledReports::getInstance()->getReports($this->idSite); + $report = reset($tmp); + $this->assertReportsEqual($report, $data); + + // Passing only period + $tmp = APIScheduledReports::getInstance()->getReports($idSite = false, $data['period']); + $report = reset($tmp); + $this->assertReportsEqual($report, $data); + + // Passing only idreport + $tmp = APIScheduledReports::getInstance()->getReports($idSite = false, $period = false, $idReport); + $report = reset($tmp); + $this->assertReportsEqual($report, $data); + } + + /** + * @group Plugins + */ + public function testGetReportsIdReportNotFound() + { + try { + APIScheduledReports::getInstance()->getReports($idSite = false, $period = false, $idReport = 1); + } catch (Exception $e) { + return; + } + $this->fail('Expected exception not raised'); + } + + /** + * @group Plugins + */ + public function testGetReportsInvalidPermission() + { + try { + APIScheduledReports::getInstance()->getReports( + $idSite = 44, + $period = false, + self::addReport(self::getDailyPDFReportData($this->idSite)) + ); + + } catch (Exception $e) { + return; + } + $this->fail('Expected exception not raised'); + } + + /** + * @group Plugins + */ + public function testAddReportInvalidWebsite() + { + try { + self::addReport(self::getDailyPDFReportData(33)); + } catch (Exception $e) { + return; + } + $this->fail('Expected exception not raised'); + } + + /** + * @group Plugins + */ + public function testAddReportInvalidPeriod() + { + try { + $data = self::getDailyPDFReportData($this->idSite); + $data['period'] = 'dx'; + self::addReport($data); + } catch (Exception $e) { + return; + } + $this->fail('Expected exception not raised'); + } + + /** + * @group Plugins + */ + public function testUpdateReport() + { + $idReport = self::addReport(self::getDailyPDFReportData($this->idSite)); + $dataAfter = self::getMonthlyEmailReportData($this->idSite); + + self::updateReport($idReport, $dataAfter); + + $reports = APIScheduledReports::getInstance()->getReports($idSite = false, $period = false, $idReport); + + $this->assertReportsEqual( + reset($reports), + $dataAfter + ); + } + + /** + * @group Plugins + */ + public function testDeleteReport() + { + // Deletes non existing report throws exception + try { + APIScheduledReports::getInstance()->deleteReport($idReport = 1); + $this->fail('Exception not raised'); + } catch (Exception $e) { + } + + $idReport = self::addReport(self::getMonthlyEmailReportData($this->idSite)); + $this->assertEquals(1, count(APIScheduledReports::getInstance()->getReports())); + APIScheduledReports::getInstance()->deleteReport($idReport); + $this->assertEquals(0, count(APIScheduledReports::getInstance()->getReports())); + } + + /** + * @group Plugins + */ + public function testGetTopMenuTranslationKeyMobileMessagingInactive() + { + // unload MobileMessaging plugin + \Piwik\Plugin\Manager::getInstance()->loadPlugins(array('ScheduledReports')); + + $pdfReportPlugin = new Menu(); + $this->assertEquals( + Menu::PDF_REPORTS_TOP_MENU_TRANSLATION_KEY, + $pdfReportPlugin->getTopMenuTranslationKey() + ); + } + + /** + * @group Plugins + */ + public function testGetTopMenuTranslationKeyUserIsAnonymous() + { + $anonymousAccess = new FakeAccess; + FakeAccess::$identity = 'anonymous'; + Access::setSingletonInstance($anonymousAccess); + + $pdfReportPlugin = new Menu(); + $this->assertEquals( + Menu::MOBILE_MESSAGING_TOP_MENU_TRANSLATION_KEY, + $pdfReportPlugin->getTopMenuTranslationKey() + ); + } + + /** + * top menu should display 'Email & SMS reports' when the user has set-up a valid mobile provider account + * even though there is no sms reports configured + * + * @group Plugins + */ + public function testGetTopMenuTranslationKeyNoReportMobileAccountOK() + { + // set mobile provider account + self::setSuperUser(); + APIMobileMessaging::getInstance()->setSMSAPICredential('StubbedProvider', ''); + + $pdfReportPlugin = new Menu(); + $this->assertEquals( + Menu::MOBILE_MESSAGING_TOP_MENU_TRANSLATION_KEY, + $pdfReportPlugin->getTopMenuTranslationKey() + ); + } + + /** + * top menu should display 'Email reports' when the user has not set-up a valid mobile provider account + * and no reports at all have been configured + * + * @group Plugins + */ + public function testGetTopMenuTranslationKeyNoReportMobileAccountKO() + { + $pdfReportPlugin = new Menu(); + $this->assertEquals( + Menu::PDF_REPORTS_TOP_MENU_TRANSLATION_KEY, + $pdfReportPlugin->getTopMenuTranslationKey() + ); + } + + /** + * top menu should display 'Email & SMS reports' if there is at least one sms report + * whatever the status of the mobile provider account + * + * @group Plugins + */ + public function testGetTopMenuTranslationKeyOneSMSReportMobileAccountKO() + { + APIScheduledReports::getInstance()->addReport( + 1, + '', + ScheduledTime::PERIOD_DAY, + 0, + MobileMessaging::MOBILE_TYPE, + MobileMessaging::SMS_FORMAT, + array(), + array( + MobileMessaging::PHONE_NUMBERS_PARAMETER => array() + ) + ); + + $pdfReportPlugin = new Menu(); + $this->assertEquals( + Menu::MOBILE_MESSAGING_TOP_MENU_TRANSLATION_KEY, + $pdfReportPlugin->getTopMenuTranslationKey() + ); + } + + /** + * top menu should display 'Email reports' if there are no SMS reports and at least one email report + * whatever the status of the mobile provider account + * + * @group Plugins + */ + public function testGetTopMenuTranslationKeyNoSMSReportAccountOK() + { + // set mobile provider account + self::setSuperUser(); + APIMobileMessaging::getInstance()->setSMSAPICredential('StubbedProvider', ''); + + self::addReport(self::getMonthlyEmailReportData($this->idSite)); + + $pdfReportPlugin = new Menu(); + $this->assertEquals( + Menu::PDF_REPORTS_TOP_MENU_TRANSLATION_KEY, + $pdfReportPlugin->getTopMenuTranslationKey() + ); + } + + /** + * @group Plugins + */ + public function testGetScheduledTasks() + { + // stub API to control getReports() return values + $report1 = self::getDailyPDFReportData($this->idSite); + $report1['idreport'] = 1; + $report1['hour'] = 0; + $report1['deleted'] = 0; + + $report2 = self::getMonthlyEmailReportData($this->idSite); + $report2['idreport'] = 2; + $report2['idsite'] = 2; + $report2['hour'] = 0; + $report2['deleted'] = 0; + + $report3 = self::getMonthlyEmailReportData($this->idSite); + $report3['idreport'] = 3; + $report3['deleted'] = 1; // should not be scheduled + + $report4 = self::getMonthlyEmailReportData($this->idSite); + $report4['idreport'] = 4; + $report4['idsite'] = 1; + $report4['hour'] = 8; + $report4['deleted'] = 0; + + $report5 = self::getMonthlyEmailReportData($this->idSite); + $report5['idreport'] = 5; + $report5['idsite'] = 2; + $report5['hour'] = 8; + $report5['deleted'] = 0; + + // test no exception is raised when a scheduled report is set to never send + $report6 = self::getMonthlyEmailReportData($this->idSite); + $report6['idreport'] = 6; + $report6['period'] = ScheduledTime::PERIOD_NEVER; + $report6['deleted'] = 0; + + $stubbedAPIScheduledReports = $this->getMock('\\Piwik\\Plugins\\ScheduledReports\\API', array('getReports', 'getInstance'), $arguments = array(), $mockClassName = '', $callOriginalConstructor = false); + $stubbedAPIScheduledReports->expects($this->any())->method('getReports')->will($this->returnValue( + array($report1, $report2, $report3, $report4, $report5, $report6)) + ); + \Piwik\Plugins\ScheduledReports\API::setSingletonInstance($stubbedAPIScheduledReports); + + // initialize sites 1 and 2 + Site::setSites( array( + 1 => array('timezone' => 'Europe/Paris'), + 2 => array('timezone' => 'UTC-6.5'), + )); + + // expected tasks + $scheduleTask1 = ScheduledTime::factory('daily'); + $scheduleTask1->setHour(0); // paris is UTC-1, period ends at 23h UTC + $scheduleTask1->setTimezone('Europe/Paris'); + + $scheduleTask2 = new Monthly(); + $scheduleTask2->setHour(0); // site is UTC-6.5, period ends at 6h30 UTC, smallest resolution is hour + $scheduleTask2->setTimezone('UTC-6.5'); + + $scheduleTask3 = new Monthly(); + $scheduleTask3->setHour(8); // paris is UTC-1, configured to be sent at 8h + $scheduleTask3->setTimezone('Europe/Paris'); + + $scheduleTask4 = new Monthly(); + $scheduleTask4->setHour(8); // site is UTC-6.5, configured to be sent at 8h + $scheduleTask4->setTimezone('UTC-6.5'); + + $expectedTasks = array( + new ScheduledTask (APIScheduledReports::getInstance(), 'sendReport', 1, $scheduleTask1), + new ScheduledTask (APIScheduledReports::getInstance(), 'sendReport', 2, $scheduleTask2), + new ScheduledTask (APIScheduledReports::getInstance(), 'sendReport', 4, $scheduleTask3), + new ScheduledTask (APIScheduledReports::getInstance(), 'sendReport', 5, $scheduleTask4), + ); + + $pdfReportPlugin = new Tasks(); + $pdfReportPlugin->schedule(); + $tasks = $pdfReportPlugin->getScheduledTasks(); + $this->assertEquals($expectedTasks, $tasks); + + \Piwik\Plugins\ScheduledReports\API::unsetInstance(); + + } + + /** + * Dataprovider for testGetReportSubjectAndReportTitle + */ + public function getGetReportSubjectAndReportTitleTestCases() + { + return array( + array('Piwik.org', 'General_Website Piwik.org', 'Piwik.org', array('UserSettings_getBrowserType')), + array('Piwik.org', 'General_Website Piwik.org', 'Piwik.org', array('MultiSites_getAll', 'UserSettings_getBrowserType')), + array('General_MultiSitesSummary', 'General_MultiSitesSummary', 'Piwik.org', array('MultiSites_getAll')), + ); + } + + /** + * @group Plugins + * + * @dataProvider getGetReportSubjectAndReportTitleTestCases + */ + public function testGetReportSubjectAndReportTitle($expectedReportSubject, $expectedReportTitle, $websiteName, $reports) + { + $getReportSubjectAndReportTitle = new ReflectionMethod( + '\\Piwik\\Plugins\\ScheduledReports\\API', 'getReportSubjectAndReportTitle' + ); + $getReportSubjectAndReportTitle->setAccessible(true); + + list($reportSubject, $reportTitle) = $getReportSubjectAndReportTitle->invoke( APIScheduledReports::getInstance(), $websiteName, $reports); + $this->assertEquals($expectedReportSubject, $reportSubject); + $this->assertEquals($expectedReportTitle, $reportTitle); + } + + private function assertReportsEqual($report, $data) + { + foreach ($data as $key => $value) { + if ($key == 'description') $value = substr($value, 0, 250); + $this->assertEquals($value, $report[$key], "Error for $key for report " . var_export($report, true) . " and data " . var_export($data, true)); + } + } + + private static function addReport($data) + { + $idReport = APIScheduledReports::getInstance()->addReport( + $data['idsite'], + $data['description'], + $data['period'], + $data['hour'], + $data['type'], + $data['format'], + $data['reports'], + $data['parameters'] + ); + return $idReport; + } + + private static function getDailyPDFReportData($idSite) + { + return array( + 'idsite' => $idSite, + 'description' => 'test description"', + 'period' => ScheduledTime::PERIOD_DAY, + 'hour' => '7', + 'type' => 'email', + 'format' => 'pdf', + 'reports' => array('UserCountry_getCountry'), + 'parameters' => array( + 'displayFormat' => '1', + 'emailMe' => true, + 'additionalEmails' => array('test@test.com', 't2@test.com'), + 'evolutionGraph' => false + ) + ); + } + + private static function getMonthlyEmailReportData($idSite) + { + return array( + 'idsite' => $idSite, + 'description' => 'very very long and possibly truncated description. very very long and possibly truncated description. very very long and possibly truncated description. very very long and possibly truncated description. very very long and possibly truncated description. ', + 'period' => ScheduledTime::PERIOD_MONTH, + 'hour' => '0', + 'type' => 'email', + 'format' => 'pdf', + 'reports' => array('UserCountry_getContinent'), + 'parameters' => array( + 'displayFormat' => '1', + 'emailMe' => false, + 'additionalEmails' => array('blabla@ec.fr'), + 'evolutionGraph' => false + ) + ); + } + + private static function updateReport($idReport, $data) + { + $idReport = APIScheduledReports::getInstance()->updateReport( + $idReport, + $data['idsite'], + $data['description'], + $data['period'], + $data['hour'], + $data['type'], + $data['format'], + $data['reports'], + $data['parameters']); + return $idReport; + } + + private static function setSuperUser() + { + $pseudoMockAccess = new FakeAccess; + FakeAccess::$superUser = true; + Access::setSingletonInstance($pseudoMockAccess); + } +} diff --git a/plugins/ScheduledReports/tests/Integration/ScheduledReportsTest.php b/plugins/ScheduledReports/tests/Integration/ScheduledReportsTest.php new file mode 100644 index 0000000000..241e063aa0 --- /dev/null +++ b/plugins/ScheduledReports/tests/Integration/ScheduledReportsTest.php @@ -0,0 +1,163 @@ +reports = new ScheduledReports(); + $this->setIdentity('userlogin'); + + for ($i = 1; $i <= 4; $i++) { + Fixture::createWebsite('2014-01-01 00:00:00'); + $this->addReport('userlogin', $i); + } + + $this->addReport('otherUser', 1); + $this->addReport('anotherUser', 2); + } + + public function test_deleteUserReportForSites_shouldNotRemoveAnythingIfNoSitesOrNoLogin() + { + $this->reports->deleteUserReportForSites('userLogin', array()); + + $this->assertHasReport('userlogin', 1); + $this->assertHasReport('userlogin', 2); + $this->assertHasReport('userlogin', 3); + $this->assertHasReport('userlogin', 4); + $this->assertHasReport('otherUser', 1); + $this->assertHasReport('anotherUser', 2); + + $this->reports->deleteUserReportForSites('', array(1, 2, 3, 4)); + + $this->assertHasReport('userlogin', 1); + $this->assertHasReport('userlogin', 2); + $this->assertHasReport('userlogin', 3); + $this->assertHasReport('userlogin', 4); + $this->assertHasReport('otherUser', 1); + $this->assertHasReport('anotherUser', 2); + } + + public function test_deleteUserReportForSites_shouldNotFailIfUserHasNoReports() + { + $this->reports->deleteUserReportForSites('unk', array()); + + $this->assertHasReport('userlogin', 1); + $this->assertHasReport('userlogin', 2); + $this->assertHasReport('userlogin', 3); + $this->assertHasReport('userlogin', 4); + $this->assertHasReport('otherUser', 1); + $this->assertHasReport('anotherUser', 2); + } + + public function test_deleteUserReportForSites_shouldRemoveOnlyReportsForGivenSitesAndLogin() + { + $this->reports->deleteUserReportForSites('userLogin', array(1, 2)); + + $this->assertHasNotReport('userlogin', 1); + $this->assertHasNotReport('userlogin', 2); + + $this->assertHasReport('userlogin', 3); + $this->assertHasReport('userlogin', 4); + $this->assertHasReport('otherUser', 1); + $this->assertHasReport('anotherUser', 2); + } + + public function test_ScheduledReports_shouldRemoveOnlyReportsForGivenSitesAndLogin_IfEventIsTriggered() + { + Piwik::postEvent('UsersManager.removeSiteAccess', array('userLogin', array(1, 2))); + + $this->assertHasNotReport('userlogin', 1); + $this->assertHasNotReport('userlogin', 2); + + $this->assertHasReport('userlogin', 3); + $this->assertHasReport('userlogin', 4); + $this->assertHasReport('otherUser', 1); + $this->assertHasReport('anotherUser', 2); + } + + public function test_deleteUserReport_shouldRemoveAllReportsOfASpecificUser() + { + $this->reports->deleteUserReport('userLogin'); + + $this->assertHasNotReport('userlogin', 1); + $this->assertHasNotReport('userlogin', 2); + $this->assertHasNotReport('userlogin', 3); + $this->assertHasNotReport('userlogin', 4); + + $this->assertHasReport('otherUser', 1); + $this->assertHasReport('anotherUser', 2); + } + + private function assertHasReport($login, $idSite) + { + $report = $this->getReport($login, $idSite); + + $this->assertNotEmpty($report, "Report for $login, $idSite should exist but does not"); + } + + private function assertHasNotReport($login, $idSite) + { + try { + $this->getReport($login, $idSite); + $this->fail("Report for $login, $idSite should not exist but does"); + } catch (\Exception $e) { + $this->assertContains("Requested report couldn't be found", $e->getMessage()); + } + } + + private function getReport($login, $idSite) + { + $this->setIdentity($login); + + return API::getInstance()->getReports($idSite, 'day', $this->reportIds[$login . '_' . $idSite]); + } + + private function addReport($login, $idSite) + { + $this->setIdentity($login); + + $reportType = 'email'; + $reportFormat = 'pdf'; + $reports = array(); + $parameters = array(ScheduledReports::DISPLAY_FORMAT_PARAMETER => ScheduledReports::DISPLAY_FORMAT_TABLES_ONLY); + + $reportId = API::getInstance()->addReport($idSite, 'description', 'day', 3, $reportType, $reportFormat, $reports, $parameters); + $this->reportIds[$login . '_' . $idSite] = $reportId; + } + + private function setIdentity($login) + { + $pseudoMockAccess = new \FakeAccess(); + $pseudoMockAccess::$identity = $login; + $pseudoMockAccess::$superUser = true; + Access::setSingletonInstance($pseudoMockAccess); + } + +} diff --git a/plugins/ScheduledReports/tests/ScheduledReportsTest.php b/plugins/ScheduledReports/tests/ScheduledReportsTest.php deleted file mode 100644 index 241e063aa0..0000000000 --- a/plugins/ScheduledReports/tests/ScheduledReportsTest.php +++ /dev/null @@ -1,163 +0,0 @@ -reports = new ScheduledReports(); - $this->setIdentity('userlogin'); - - for ($i = 1; $i <= 4; $i++) { - Fixture::createWebsite('2014-01-01 00:00:00'); - $this->addReport('userlogin', $i); - } - - $this->addReport('otherUser', 1); - $this->addReport('anotherUser', 2); - } - - public function test_deleteUserReportForSites_shouldNotRemoveAnythingIfNoSitesOrNoLogin() - { - $this->reports->deleteUserReportForSites('userLogin', array()); - - $this->assertHasReport('userlogin', 1); - $this->assertHasReport('userlogin', 2); - $this->assertHasReport('userlogin', 3); - $this->assertHasReport('userlogin', 4); - $this->assertHasReport('otherUser', 1); - $this->assertHasReport('anotherUser', 2); - - $this->reports->deleteUserReportForSites('', array(1, 2, 3, 4)); - - $this->assertHasReport('userlogin', 1); - $this->assertHasReport('userlogin', 2); - $this->assertHasReport('userlogin', 3); - $this->assertHasReport('userlogin', 4); - $this->assertHasReport('otherUser', 1); - $this->assertHasReport('anotherUser', 2); - } - - public function test_deleteUserReportForSites_shouldNotFailIfUserHasNoReports() - { - $this->reports->deleteUserReportForSites('unk', array()); - - $this->assertHasReport('userlogin', 1); - $this->assertHasReport('userlogin', 2); - $this->assertHasReport('userlogin', 3); - $this->assertHasReport('userlogin', 4); - $this->assertHasReport('otherUser', 1); - $this->assertHasReport('anotherUser', 2); - } - - public function test_deleteUserReportForSites_shouldRemoveOnlyReportsForGivenSitesAndLogin() - { - $this->reports->deleteUserReportForSites('userLogin', array(1, 2)); - - $this->assertHasNotReport('userlogin', 1); - $this->assertHasNotReport('userlogin', 2); - - $this->assertHasReport('userlogin', 3); - $this->assertHasReport('userlogin', 4); - $this->assertHasReport('otherUser', 1); - $this->assertHasReport('anotherUser', 2); - } - - public function test_ScheduledReports_shouldRemoveOnlyReportsForGivenSitesAndLogin_IfEventIsTriggered() - { - Piwik::postEvent('UsersManager.removeSiteAccess', array('userLogin', array(1, 2))); - - $this->assertHasNotReport('userlogin', 1); - $this->assertHasNotReport('userlogin', 2); - - $this->assertHasReport('userlogin', 3); - $this->assertHasReport('userlogin', 4); - $this->assertHasReport('otherUser', 1); - $this->assertHasReport('anotherUser', 2); - } - - public function test_deleteUserReport_shouldRemoveAllReportsOfASpecificUser() - { - $this->reports->deleteUserReport('userLogin'); - - $this->assertHasNotReport('userlogin', 1); - $this->assertHasNotReport('userlogin', 2); - $this->assertHasNotReport('userlogin', 3); - $this->assertHasNotReport('userlogin', 4); - - $this->assertHasReport('otherUser', 1); - $this->assertHasReport('anotherUser', 2); - } - - private function assertHasReport($login, $idSite) - { - $report = $this->getReport($login, $idSite); - - $this->assertNotEmpty($report, "Report for $login, $idSite should exist but does not"); - } - - private function assertHasNotReport($login, $idSite) - { - try { - $this->getReport($login, $idSite); - $this->fail("Report for $login, $idSite should not exist but does"); - } catch (\Exception $e) { - $this->assertContains("Requested report couldn't be found", $e->getMessage()); - } - } - - private function getReport($login, $idSite) - { - $this->setIdentity($login); - - return API::getInstance()->getReports($idSite, 'day', $this->reportIds[$login . '_' . $idSite]); - } - - private function addReport($login, $idSite) - { - $this->setIdentity($login); - - $reportType = 'email'; - $reportFormat = 'pdf'; - $reports = array(); - $parameters = array(ScheduledReports::DISPLAY_FORMAT_PARAMETER => ScheduledReports::DISPLAY_FORMAT_TABLES_ONLY); - - $reportId = API::getInstance()->addReport($idSite, 'description', 'day', 3, $reportType, $reportFormat, $reports, $parameters); - $this->reportIds[$login . '_' . $idSite] = $reportId; - } - - private function setIdentity($login) - { - $pseudoMockAccess = new \FakeAccess(); - $pseudoMockAccess::$identity = $login; - $pseudoMockAccess::$superUser = true; - Access::setSingletonInstance($pseudoMockAccess); - } - -} diff --git a/plugins/SegmentEditor/tests/Integration/SegmentEditorTest.php b/plugins/SegmentEditor/tests/Integration/SegmentEditorTest.php new file mode 100644 index 0000000000..3fd322b62f --- /dev/null +++ b/plugins/SegmentEditor/tests/Integration/SegmentEditorTest.php @@ -0,0 +1,210 @@ +loadPlugin('SegmentEditor'); + \Piwik\Plugin\Manager::getInstance()->installLoadedPlugins(); + + // setup the access layer + $pseudoMockAccess = new FakeAccess; + FakeAccess::setIdSitesView(array(1, 2)); + FakeAccess::setIdSitesAdmin(array(3, 4)); + + //finally we set the user as a Super User by default + FakeAccess::$superUser = true; + FakeAccess::$superUserLogin = 'superusertest'; + Access::setSingletonInstance($pseudoMockAccess); + + APISitesManager::getInstance()->addSite('test', 'http://example.org'); + } + + /** + * @group Plugins + */ + public function testAddInvalidSegment_ShouldThrow() + { + try { + API::getInstance()->add('name', 'test==test2'); + $this->fail("Exception not raised."); + } catch (Exception $expected) { + } + try { + API::getInstance()->add('name', 'test'); + $this->fail("Exception not raised."); + } catch (Exception $expected) { + } + } + + /** + * @group Plugins + */ + public function test_AddAndGet_SimpleSegment() + { + $name = 'name'; + $definition = 'searches>1,visitIp!=127.0.0.1'; + $idSegment = API::getInstance()->add($name, $definition); + $this->assertEquals($idSegment, 1); + $segment = API::getInstance()->get($idSegment); + unset($segment['ts_created']); + $expected = array( + 'idsegment' => 1, + 'name' => $name, + 'definition' => $definition, + 'login' => 'superUserLogin', + 'enable_all_users' => '0', + 'enable_only_idsite' => '0', + 'auto_archive' => '0', + 'ts_last_edit' => null, + 'deleted' => '0', + ); + + $this->assertEquals($segment, $expected); + } + + /** + * @group Plugins + */ + public function test_AddAndGet_AnotherSegment() + { + $name = 'name'; + $definition = 'searches>1,visitIp!=127.0.0.1'; + $idSegment = API::getInstance()->add($name, $definition, $idSite = 1, $autoArchive = 1, $enabledAllUsers = 1); + $this->assertEquals($idSegment, 1); + + // Testing get() + $segment = API::getInstance()->get($idSegment); + $expected = array( + 'idsegment' => '1', + 'name' => $name, + 'definition' => $definition, + 'login' => 'superUserLogin', + 'enable_all_users' => '1', + 'enable_only_idsite' => '1', + 'auto_archive' => '1', + 'ts_last_edit' => null, + 'deleted' => '0', + ); + unset($segment['ts_created']); + $this->assertEquals($segment, $expected); + + // There is a segment to process for this particular site + $model = new Model(); + $segments = $model->getSegmentsToAutoArchive($idSite); + unset($segments[0]['ts_created']); + $this->assertEquals($segments, array($expected)); + + // There is no segment to process for a non existing site + try { + $model->getSegmentsToAutoArchive(33); + $this->fail(); + } catch(Exception $e) { + // expected + } + + // There is no segment to process across all sites + $segments = $model->getSegmentsToAutoArchive($idSite = false); + $this->assertEquals($segments, array()); + } + + /** + * @group Plugins + */ + public function test_UpdateSegment() + { + $name = 'name"'; + $definition = 'searches>1,visitIp!=127.0.0.1'; + $nameSegment1 = 'hello'; + $idSegment1 = API::getInstance()->add($nameSegment1, 'searches==0', $idSite = 1, $autoArchive = 1, $enabledAllUsers = 1); + $idSegment2 = API::getInstance()->add($name, $definition, $idSite = 1, $autoArchive = 1, $enabledAllUsers = 1); + + $updatedSegment = array( + 'idsegment' => $idSegment2, + 'name' => 'NEW name', + 'definition' => 'searches==0', + 'enable_only_idsite' => '0', + 'enable_all_users' => '0', + 'auto_archive' => '0', + 'ts_last_edit' => Date::now()->getDatetime(), + 'ts_created' => Date::now()->getDatetime(), + 'login' => Piwik::getCurrentUserLogin(), + 'deleted' => '0', + ); + API::getInstance()->update($idSegment2, + $updatedSegment['name'], + $updatedSegment['definition'], + $updatedSegment['enable_only_idsite'], + $updatedSegment['auto_archive'], + $updatedSegment['enable_all_users'] + ); + + $newSegment = API::getInstance()->get($idSegment2); + + // avoid test failures for when ts_created/ts_last_edit are different by between 1/2 secs + $this->removeSecondsFromSegmentInfo($updatedSegment); + $this->removeSecondsFromSegmentInfo($newSegment); + + $this->assertEquals($newSegment, $updatedSegment); + + // Check the other segmenet was not updated + $newSegment = API::getInstance()->get($idSegment1); + $this->assertEquals($newSegment['name'], $nameSegment1); + } + + /** + * @group Plugins + */ + public function test_deleteSegment() + { + $idSegment1 = API::getInstance()->add('name 1', 'searches==0', $idSite = 1, $autoArchive = 1, $enabledAllUsers = 1); + $idSegment2 = API::getInstance()->add('name 2', 'searches>1,visitIp!=127.0.0.1', $idSite = 1, $autoArchive = 1, $enabledAllUsers = 1); + + $deleted = API::getInstance()->delete($idSegment2); + $this->assertTrue($deleted); + try { + API::getInstance()->get($idSegment2); + $this->fail("getting deleted segment should have failed"); + } catch(Exception $e) { + // expected + } + + // and this should work + API::getInstance()->get($idSegment1); + } + + private function removeSecondsFromSegmentInfo(&$segmentInfo) + { + $timestampProperties = array('ts_last_edit', 'ts_created'); + foreach ($timestampProperties as $propertyName) { + if (isset($segmentInfo[$propertyName])) { + $segmentInfo[$propertyName] = substr($segmentInfo[$propertyName], 0, strlen($segmentInfo[$propertyName] - 2)); + } + } + } +} diff --git a/plugins/SegmentEditor/tests/SegmentEditorTest.php b/plugins/SegmentEditor/tests/SegmentEditorTest.php deleted file mode 100644 index 16f1b3fe34..0000000000 --- a/plugins/SegmentEditor/tests/SegmentEditorTest.php +++ /dev/null @@ -1,210 +0,0 @@ -loadPlugin('SegmentEditor'); - \Piwik\Plugin\Manager::getInstance()->installLoadedPlugins(); - - // setup the access layer - $pseudoMockAccess = new FakeAccess; - FakeAccess::setIdSitesView(array(1, 2)); - FakeAccess::setIdSitesAdmin(array(3, 4)); - - //finally we set the user as a Super User by default - FakeAccess::$superUser = true; - FakeAccess::$superUserLogin = 'superusertest'; - Access::setSingletonInstance($pseudoMockAccess); - - APISitesManager::getInstance()->addSite('test', 'http://example.org'); - } - - /** - * @group Plugins - */ - public function testAddInvalidSegment_ShouldThrow() - { - try { - API::getInstance()->add('name', 'test==test2'); - $this->fail("Exception not raised."); - } catch (Exception $expected) { - } - try { - API::getInstance()->add('name', 'test'); - $this->fail("Exception not raised."); - } catch (Exception $expected) { - } - } - - /** - * @group Plugins - */ - public function test_AddAndGet_SimpleSegment() - { - $name = 'name'; - $definition = 'searches>1,visitIp!=127.0.0.1'; - $idSegment = API::getInstance()->add($name, $definition); - $this->assertEquals($idSegment, 1); - $segment = API::getInstance()->get($idSegment); - unset($segment['ts_created']); - $expected = array( - 'idsegment' => 1, - 'name' => $name, - 'definition' => $definition, - 'login' => 'superUserLogin', - 'enable_all_users' => '0', - 'enable_only_idsite' => '0', - 'auto_archive' => '0', - 'ts_last_edit' => null, - 'deleted' => '0', - ); - - $this->assertEquals($segment, $expected); - } - - /** - * @group Plugins - */ - public function test_AddAndGet_AnotherSegment() - { - $name = 'name'; - $definition = 'searches>1,visitIp!=127.0.0.1'; - $idSegment = API::getInstance()->add($name, $definition, $idSite = 1, $autoArchive = 1, $enabledAllUsers = 1); - $this->assertEquals($idSegment, 1); - - // Testing get() - $segment = API::getInstance()->get($idSegment); - $expected = array( - 'idsegment' => '1', - 'name' => $name, - 'definition' => $definition, - 'login' => 'superUserLogin', - 'enable_all_users' => '1', - 'enable_only_idsite' => '1', - 'auto_archive' => '1', - 'ts_last_edit' => null, - 'deleted' => '0', - ); - unset($segment['ts_created']); - $this->assertEquals($segment, $expected); - - // There is a segment to process for this particular site - $model = new Model(); - $segments = $model->getSegmentsToAutoArchive($idSite); - unset($segments[0]['ts_created']); - $this->assertEquals($segments, array($expected)); - - // There is no segment to process for a non existing site - try { - $model->getSegmentsToAutoArchive(33); - $this->fail(); - } catch(Exception $e) { - // expected - } - - // There is no segment to process across all sites - $segments = $model->getSegmentsToAutoArchive($idSite = false); - $this->assertEquals($segments, array()); - } - - /** - * @group Plugins - */ - public function test_UpdateSegment() - { - $name = 'name"'; - $definition = 'searches>1,visitIp!=127.0.0.1'; - $nameSegment1 = 'hello'; - $idSegment1 = API::getInstance()->add($nameSegment1, 'searches==0', $idSite = 1, $autoArchive = 1, $enabledAllUsers = 1); - $idSegment2 = API::getInstance()->add($name, $definition, $idSite = 1, $autoArchive = 1, $enabledAllUsers = 1); - - $updatedSegment = array( - 'idsegment' => $idSegment2, - 'name' => 'NEW name', - 'definition' => 'searches==0', - 'enable_only_idsite' => '0', - 'enable_all_users' => '0', - 'auto_archive' => '0', - 'ts_last_edit' => Date::now()->getDatetime(), - 'ts_created' => Date::now()->getDatetime(), - 'login' => Piwik::getCurrentUserLogin(), - 'deleted' => '0', - ); - API::getInstance()->update($idSegment2, - $updatedSegment['name'], - $updatedSegment['definition'], - $updatedSegment['enable_only_idsite'], - $updatedSegment['auto_archive'], - $updatedSegment['enable_all_users'] - ); - - $newSegment = API::getInstance()->get($idSegment2); - - // avoid test failures for when ts_created/ts_last_edit are different by between 1/2 secs - $this->removeSecondsFromSegmentInfo($updatedSegment); - $this->removeSecondsFromSegmentInfo($newSegment); - - $this->assertEquals($newSegment, $updatedSegment); - - // Check the other segmenet was not updated - $newSegment = API::getInstance()->get($idSegment1); - $this->assertEquals($newSegment['name'], $nameSegment1); - } - - /** - * @group Plugins - */ - public function test_deleteSegment() - { - $idSegment1 = API::getInstance()->add('name 1', 'searches==0', $idSite = 1, $autoArchive = 1, $enabledAllUsers = 1); - $idSegment2 = API::getInstance()->add('name 2', 'searches>1,visitIp!=127.0.0.1', $idSite = 1, $autoArchive = 1, $enabledAllUsers = 1); - - $deleted = API::getInstance()->delete($idSegment2); - $this->assertTrue($deleted); - try { - API::getInstance()->get($idSegment2); - $this->fail("getting deleted segment should have failed"); - } catch(Exception $e) { - // expected - } - - // and this should work - API::getInstance()->get($idSegment1); - } - - private function removeSecondsFromSegmentInfo(&$segmentInfo) - { - $timestampProperties = array('ts_last_edit', 'ts_created'); - foreach ($timestampProperties as $propertyName) { - if (isset($segmentInfo[$propertyName])) { - $segmentInfo[$propertyName] = substr($segmentInfo[$propertyName], 0, strlen($segmentInfo[$propertyName] - 2)); - } - } - } -} diff --git a/plugins/SitesManager/tests/Integration/SiteUrlsTest.php b/plugins/SitesManager/tests/Integration/SiteUrlsTest.php new file mode 100644 index 0000000000..2ab2711c8d --- /dev/null +++ b/plugins/SitesManager/tests/Integration/SiteUrlsTest.php @@ -0,0 +1,145 @@ +siteUrls = new SiteUrls(); + $this->api = API::getInstance(); + + SiteUrls::clearSitesCache(); + } + + public function testGetAllSiteUrls_shouldReturnAnEmptyArray_IfThereAreNoSites() + { + $this->assertSiteUrls(array()); + } + + public function testGetAllSiteUrls_shouldReturnUrlsForEachSiteId() + { + $this->addSite('http://www.example.com'); // only one main URL + $this->assertSiteUrls(array(1 => array('http://www.example.com'))); + + $this->addSite('http://www.example.com', 'http://www.piwik.org'); // main URL and alias URL + $this->assertSiteUrls(array(1 => array('http://www.example.com'), 2 => array('http://www.example.com', 'http://www.piwik.org'))); + + $this->api->addSiteAliasUrls(2, 'http://piwik.org'); + $this->assertSiteUrls(array(1 => array('http://www.example.com'), 2 => array('http://www.example.com', 'http://piwik.org', 'http://www.piwik.org'))); + + $this->api->setSiteAliasUrls(2, array()); + $this->assertSiteUrls(array(1 => array('http://www.example.com'), 2 => array('http://www.example.com'))); + } + + public function testGetAllCachedSiteUrls_shouldReturnAnEmptyArray_IfThereAreNoSites() + { + $this->assertCachedSiteUrls(array()); + } + + public function testGetAllCachedSiteUrls_ShouldReturnCorrectResultEvenIfItIsCachedAsWeClearTheCacheOnAnyChange() + { + $this->addSite('http://www.example.com'); // only one main URL + $this->assertCachedSiteUrls(array(1 => array('http://www.example.com'))); + + $this->addSite('http://www.example.com', 'http://www.piwik.org'); // main URL and alias URL + $this->assertCachedSiteUrls(array(1 => array('http://www.example.com'), 2 => array('http://www.example.com', 'http://www.piwik.org'))); + + $this->api->addSiteAliasUrls(2, 'http://piwik.org'); + $this->assertCachedSiteUrls(array(1 => array('http://www.example.com'), 2 => array('http://www.example.com', 'http://piwik.org', 'http://www.piwik.org'))); + + $this->api->setSiteAliasUrls(2, array()); + $this->assertCachedSiteUrls(array(1 => array('http://www.example.com'), 2 => array('http://www.example.com'))); + + $this->api->updateSite(1, 'siteName3', array('http://updated.example.com', 'http://2.example.com')); + $this->assertCachedSiteUrls(array(1 => array('http://updated.example.com', 'http://2.example.com'), 2 => array('http://www.example.com'))); + } + + public function testGetAllCachedSiteUrls_ShouldWriteACacheFile() + { + // make sure cache is empty + $this->assertValueInCache(false); + + $this->addSite('http://www.example.com'); + $this->siteUrls->getAllCachedSiteUrls(); + + // make sure we have a cached result + $this->assertValueInCache(array(1 => array('http://www.example.com'))); + } + + public function test_clearSitesCache_ShouldActuallyDeleteACache() + { + $this->addSite('http://www.example.com'); + $this->siteUrls->getAllCachedSiteUrls(); + + // make sure we have a cached result + $this->assertValueInCache(array(1 => array('http://www.example.com'))); + + SiteUrls::clearSitesCache(); + + // make sure is empty now + $this->assertValueInCache(false); + } + + public function testGetAllCachedSiteUrls_ShouldReadFromTheCacheFile() + { + $urlsToFake = array(1 => 'Whatever'); + $cache = new CacheFile('tracker', 600); + $cache->set('allSiteUrlsPerSite', $urlsToFake); + + $actual = $this->siteUrls->getAllCachedSiteUrls(); + + $this->assertEquals($urlsToFake, $actual); + } + + private function assertSiteUrls($expectedUrls) + { + $urls = $this->siteUrls->getAllSiteUrls(); + $this->assertEquals($expectedUrls, $urls); + } + + private function assertCachedSiteUrls($expectedUrls) + { + $urls = $this->siteUrls->getAllCachedSiteUrls(); + $this->assertEquals($expectedUrls, $urls); + } + + private function addSite($urls) + { + $this->api->addSite('siteName', func_get_args()); + } + + private function assertValueInCache($value) + { + $cache = new CacheFile('tracker', 600); + $siteUrls = $cache->get('allSiteUrlsPerSite'); + + $this->assertEquals($value, $siteUrls); + } +} diff --git a/plugins/SitesManager/tests/Integration/SitesManagerTest.php b/plugins/SitesManager/tests/Integration/SitesManagerTest.php new file mode 100644 index 0000000000..dc8ab0713c --- /dev/null +++ b/plugins/SitesManager/tests/Integration/SitesManagerTest.php @@ -0,0 +1,1000 @@ + exception + * + * @group Plugins + */ + public function testAddSiteEmptyName() + { + try { + API::getInstance()->addSite("", array("http://piwik.net")); + } catch (Exception $e) { + return; + } + $this->fail('Expected exception not raised'); + } + + /** + * DataProvider for testAddSiteWrongUrls + */ + public function getInvalidUrlData() + { + return array( + array(array()), // no urls + array(array("")), + array(""), + array("httpww://piwik.net"), + array("httpww://piwik.net/gqg~#"), + ); + } + + /** + * wrong urls -> exception + * + * @dataProvider getInvalidUrlData + * @group Plugins + */ + public function testAddSiteWrongUrls($url) + { + try { + API::getInstance()->addSite("name", $url); + } catch (Exception $e) { + return; + } + $this->fail('Expected exception not raised'); + } + + /** + * Test with valid IPs + * + * @group Plugins + */ + public function testAddSiteExcludedIpsAndtimezoneAndCurrencyAndExcludedQueryParametersValid() + { + $ips = '1.2.3.4,1.1.1.*,1.2.*.*,1.*.*.*'; + $timezone = 'Europe/Paris'; + $currency = 'EUR'; + $excludedQueryParameters = 'p1,P2, P33333'; + $expectedExcludedQueryParameters = 'p1,P2,P33333'; + $excludedUserAgents = " p1,P2, \nP3333 "; + $expectedExcludedUserAgents = "p1,P2,P3333"; + $expectedWebsiteType = 'mobile-\'app'; + $keepUrlFragment = 1; + $idsite = API::getInstance()->addSite("name", "http://piwik.net/", $ecommerce = 1, + $siteSearch = 1, $searchKeywordParameters = 'search,param', $searchCategoryParameters = 'cat,category', + $ips, $excludedQueryParameters, $timezone, $currency, $group = null, $startDate = null, $excludedUserAgents, + $keepUrlFragment, $expectedWebsiteType); + $siteInfo = API::getInstance()->getSiteFromId($idsite); + $this->assertEquals($ips, $siteInfo['excluded_ips']); + $this->assertEquals($timezone, $siteInfo['timezone']); + $this->assertEquals($currency, $siteInfo['currency']); + $this->assertEquals($ecommerce, $siteInfo['ecommerce']); + $this->assertTrue(Site::isEcommerceEnabledFor($idsite)); + $this->assertEquals($siteSearch, $siteInfo['sitesearch']); + $this->assertTrue(Site::isSiteSearchEnabledFor($idsite)); + $this->assertEquals($expectedWebsiteType, $siteInfo['type']); + $this->assertEquals($expectedWebsiteType, Site::getTypeFor($idsite)); + + $this->assertEquals($searchKeywordParameters, $siteInfo['sitesearch_keyword_parameters']); + $this->assertEquals($searchCategoryParameters, $siteInfo['sitesearch_category_parameters']); + $this->assertEquals($expectedExcludedQueryParameters, $siteInfo['excluded_parameters']); + $this->assertEquals($expectedExcludedUserAgents, $siteInfo['excluded_user_agents']); + } + + /** + * dataProvider for testAddSiteExcludedIpsNotValid + */ + public function getInvalidIPsData() + { + return array( + array('35817587341'), + array('ieagieha'), + array('1.2.3'), + array('*.1.1.1'), + array('*.*.1.1'), + array('*.*.*.1'), + array('1.1.1.1.1'), + ); + } + + /** + * Test with invalid IPs + * + * @dataProvider getInvalidIPsData + * @group Plugins + */ + public function testAddSiteExcludedIpsNotValid($ip) + { + try { + API::getInstance()->addSite("name", "http://piwik.net/", $ecommerce = 0, + $siteSearch = 1, $searchKeywordParameters = null, $searchCategoryParameters = null, $ip); + } catch (Exception $e) { + return; + } + $this->fail('Expected exception not raised'); + } + + /** + * one url -> one main_url and nothing inserted as alias urls + * + * @group Plugins + */ + public function testAddSiteOneUrl() + { + $url = "http://piwik.net/"; + $urlOK = "http://piwik.net"; + $idsite = API::getInstance()->addSite("name", $url); + $this->assertInternalType(PHPUnit_Framework_Constraint_IsType::TYPE_INT, $idsite); + + $siteInfo = API::getInstance()->getSiteFromId($idsite); + $this->assertEquals($urlOK, $siteInfo['main_url']); + $this->assertEquals(date('Y-m-d'), date('Y-m-d', strtotime($siteInfo['ts_created']))); + + $siteUrls = API::getInstance()->getSiteUrlsFromId($idsite); + $this->assertEquals(1, count($siteUrls)); + } + + /** + * several urls -> one main_url and others as alias urls + * + * @group Plugins + */ + public function testAddSiteSeveralUrls() + { + $urls = array("http://piwik.net/", "http://piwik.com", "https://piwik.net/test/"); + $urlsOK = array("http://piwik.net", "http://piwik.com", "https://piwik.net/test"); + $idsite = API::getInstance()->addSite("super website", $urls); + $this->assertInternalType(PHPUnit_Framework_Constraint_IsType::TYPE_INT, $idsite); + + $siteInfo = API::getInstance()->getSiteFromId($idsite); + $this->assertEquals($urlsOK[0], $siteInfo['main_url']); + + $siteUrls = API::getInstance()->getSiteUrlsFromId($idsite); + $this->assertEquals($urlsOK, $siteUrls); + } + + /** + * strange name + * + * @group Plugins + */ + public function testAddSiteStrangeName() + { + $name = "supertest(); ~@@()''!£\$'%%^'!£ போ"; + $idsite = API::getInstance()->addSite($name, "http://piwik.net"); + $this->assertInternalType(PHPUnit_Framework_Constraint_IsType::TYPE_INT, $idsite); + + $siteInfo = API::getInstance()->getSiteFromId($idsite); + $this->assertEquals($name, $siteInfo['name']); + + } + + /** + * adds a site + * use by several other unit tests + */ + protected function _addSite() + { + $name = "website "; + $idsite = API::getInstance()->addSite($name, array("http://piwik.net", "http://piwik.com/test/")); + $this->assertInternalType(PHPUnit_Framework_Constraint_IsType::TYPE_INT, $idsite); + + $siteInfo = API::getInstance()->getSiteFromId($idsite); + $this->assertEquals($name, $siteInfo['name']); + $this->assertEquals("http://piwik.net", $siteInfo['main_url']); + + $siteUrls = API::getInstance()->getSiteUrlsFromId($idsite); + $this->assertEquals(array("http://piwik.net", "http://piwik.com/test"), $siteUrls); + + return $idsite; + } + + /** + * no duplicate -> all the urls are saved + * + * @group Plugins + */ + public function testAddSiteUrlsnoDuplicate() + { + $idsite = $this->_addSite(); + + $siteUrlsBefore = API::getInstance()->getSiteUrlsFromId($idsite); + + $toAdd = array("http://piwik1.net", + "http://piwik2.net", + "http://piwik3.net/test/", + "http://localhost/test", + "http://localho5.st/test", + "http://l42578gqege.f4", + "http://super.com/test/test/atqata675675/te" + ); + $toAddValid = array("http://piwik1.net", + "http://piwik2.net", + "http://piwik3.net/test", + "http://localhost/test", + "http://localho5.st/test", + "http://l42578gqege.f4", + "http://super.com/test/test/atqata675675/te"); + + $insertedUrls = API::getInstance()->addSiteAliasUrls($idsite, $toAdd); + $this->assertEquals(count($toAdd), $insertedUrls); + + $siteUrlsAfter = API::getInstance()->getSiteUrlsFromId($idsite); + + $shouldHave = array_merge($siteUrlsBefore, $toAddValid); + sort($shouldHave); + + sort($siteUrlsAfter); + + $this->assertEquals($shouldHave, $siteUrlsAfter); + } + + /** + * duplicate -> don't save the already existing URLs + * + * @group Plugins + */ + public function testAddSiteUrlsDuplicate() + { + $idsite = $this->_addSite(); + + $siteUrlsBefore = API::getInstance()->getSiteUrlsFromId($idsite); + + $toAdd = array_merge($siteUrlsBefore, array("http://piwik1.net", "http://piwik2.net")); + + $insertedUrls = API::getInstance()->addSiteAliasUrls($idsite, $toAdd); + $this->assertEquals(count($toAdd) - count($siteUrlsBefore), $insertedUrls); + + $siteUrlsAfter = API::getInstance()->getSiteUrlsFromId($idsite); + + $shouldHave = $toAdd; + sort($shouldHave); + + sort($siteUrlsAfter); + + $this->assertEquals($shouldHave, $siteUrlsAfter); + } + + /** + * case empty array => nothing happens + * + * @group Plugins + */ + public function testAddSiteUrlsNoUrlsToAdd1() + { + $idsite = $this->_addSite(); + + $siteUrlsBefore = API::getInstance()->getSiteUrlsFromId($idsite); + + $toAdd = array(); + + $insertedUrls = API::getInstance()->addSiteAliasUrls($idsite, $toAdd); + $this->assertEquals(count($toAdd), $insertedUrls); + + $siteUrlsAfter = API::getInstance()->getSiteUrlsFromId($idsite); + + $shouldHave = $siteUrlsBefore; + sort($shouldHave); + + sort($siteUrlsAfter); + + $this->assertEquals($shouldHave, $siteUrlsAfter); + } + + /** + * case array only duplicate => nothing happens + * + * @group Plugins + */ + public function testAddSiteUrlsNoUrlsToAdd2() + { + $idsite = $this->_addSite(); + + $siteUrlsBefore = API::getInstance()->getSiteUrlsFromId($idsite); + + $toAdd = $siteUrlsBefore; + + $insertedUrls = API::getInstance()->addSiteAliasUrls($idsite, $toAdd); + $this->assertEquals(0, $insertedUrls); + + $siteUrlsAfter = API::getInstance()->getSiteUrlsFromId($idsite); + + $shouldHave = $siteUrlsBefore; + sort($shouldHave); + + sort($siteUrlsAfter); + + $this->assertEquals($shouldHave, $siteUrlsAfter); + } + + /** + * wrong format urls => exception + * + * @group Plugins + */ + public function testAddSiteUrlsWrongUrlsFormat3() + { + try { + $idsite = $this->_addSite(); + $toAdd = array("http:mpigeq"); + API::getInstance()->addSiteAliasUrls($idsite, $toAdd); + } catch (Exception $e) { + return; + } + $this->fail('Expected exception not raised'); + } + + /** + * wrong idsite => no exception because simply no access to this resource + * + * @group Plugins + */ + public function testAddSiteUrlsWrongIdSite1() + { + try { + $toAdd = array("http://pigeq.com/test"); + API::getInstance()->addSiteAliasUrls(-1, $toAdd); + } catch (Exception $e) { + return; + } + $this->fail('Expected exception not raised'); + } + + /** + * wrong idsite => exception + * + * @group Plugins + */ + public function testAddSiteUrlsWrongIdSite2() + { + try { + $toAdd = array("http://pigeq.com/test"); + API::getInstance()->addSiteAliasUrls(155, $toAdd); + } catch (Exception $e) { + return; + } + $this->fail('Expected exception not raised'); + } + + /** + * no Id -> empty array + * + * @group Plugins + */ + public function testGetAllSitesIdNoId() + { + $ids = API::getInstance()->getAllSitesId(); + $this->assertEquals(array(), $ids); + } + + /** + * several Id -> normal array + * + * @group Plugins + */ + public function testGetAllSitesIdSeveralId() + { + $name = "tetq"; + $idsites = array( + API::getInstance()->addSite($name, array("http://piwik.net", "http://piwik.com/test/")), + API::getInstance()->addSite($name, array("http://piwik.net", "http://piwik.com/test/")), + API::getInstance()->addSite($name, array("http://piwik.net", "http://piwik.com/test/")), + API::getInstance()->addSite($name, array("http://piwik.net", "http://piwik.com/test/")), + API::getInstance()->addSite($name, array("http://piwik.net", "http://piwik.com/test/")), + ); + + $ids = API::getInstance()->getAllSitesId(); + $this->assertEquals($idsites, $ids); + } + + /** + * wrong id => exception + * + * @group Plugins + */ + public function testGetSiteFromIdWrongId1() + { + try { + API::getInstance()->getSiteFromId(0); + } catch (Exception $e) { + return; + } + $this->fail('Expected exception not raised'); + } + + /** + * wrong id => exception + * + * @group Plugins + */ + public function testGetSiteFromIdWrongId2() + { + try { + API::getInstance()->getSiteFromId("x1"); + } catch (Exception $e) { + return; + } + $this->fail('Expected exception not raised'); + } + + /** + * wrong id : no access => exception + * + * @group Plugins + */ + public function testGetSiteFromIdWrongId3() + { + $idsite = API::getInstance()->addSite("site", array("http://piwik.net", "http://piwik.com/test/")); + $this->assertEquals(1, $idsite); + + // set noaccess to site 1 + FakeAccess::setIdSitesView(array(2)); + FakeAccess::setIdSitesAdmin(array()); + + try { + API::getInstance()->getSiteFromId(1); + } catch (Exception $e) { + return; + } + $this->fail('Expected exception not raised'); + } + + /** + * normal case + * + * @group Plugins + */ + public function testGetSiteFromIdNormalId() + { + $name = "website ''"; + $idsite = API::getInstance()->addSite($name, array("http://piwik.net", "http://piwik.com/test/")); + $this->assertInternalType(PHPUnit_Framework_Constraint_IsType::TYPE_INT, $idsite); + + $siteInfo = API::getInstance()->getSiteFromId($idsite); + $this->assertEquals($name, $siteInfo['name']); + $this->assertEquals("http://piwik.net", $siteInfo['main_url']); + } + + /** + * there is no admin site available -> array() + * + * @group Plugins + */ + public function testGetSitesWithAdminAccessNoResult() + { + FakeAccess::setIdSitesAdmin(array()); + + $sites = API::getInstance()->getSitesWithAdminAccess(); + $this->assertEquals(array(), $sites); + } + + /** + * normal case, admin and view and noaccess website => return only admin + * + * @group Plugins + */ + public function testGetSitesWithAdminAccess() + { + API::getInstance()->addSite("site1", array("http://piwik.net", "http://piwik.com/test/")); + API::getInstance()->addSite("site2", array("http://piwik.com/test/")); + API::getInstance()->addSite("site3", array("http://piwik.org")); + + $resultWanted = array( + 0 => array("idsite" => 1, "name" => "site1", "main_url" => "http://piwik.net", "ecommerce" => 0, "excluded_ips" => "", 'sitesearch' => 1, 'sitesearch_keyword_parameters' => '', 'sitesearch_category_parameters' => '', 'excluded_parameters' => '', 'excluded_user_agents' => '', 'timezone' => 'UTC', 'currency' => 'USD', 'group' => '', 'keep_url_fragment' => 0, 'type' => 'website'), + 1 => array("idsite" => 3, "name" => "site3", "main_url" => "http://piwik.org", "ecommerce" => 0, "excluded_ips" => "", 'sitesearch' => 1, 'sitesearch_keyword_parameters' => '', 'sitesearch_category_parameters' => '', 'excluded_parameters' => '', 'excluded_user_agents' => '', 'timezone' => 'UTC', 'currency' => 'USD', 'group' => '', 'keep_url_fragment' => 0, 'type' => 'website'), + ); + + FakeAccess::setIdSitesAdmin(array(1, 3)); + + $sites = API::getInstance()->getSitesWithAdminAccess(); + + // we dont test the ts_created + unset($sites[0]['ts_created']); + unset($sites[1]['ts_created']); + $this->assertEquals($resultWanted, $sites); + } + + /** + * there is no admin site available -> array() + * + * @group Plugins + */ + public function testGetSitesWithViewAccessNoResult() + { + FakeAccess::setIdSitesView(array()); + FakeAccess::setIdSitesAdmin(array()); + + $sites = API::getInstance()->getSitesWithViewAccess(); + $this->assertEquals(array(), $sites); + } + + /** + * normal case, admin and view and noaccess website => return only admin + * + * @group Plugins + */ + public function testGetSitesWithViewAccess() + { + API::getInstance()->addSite("site1", array("http://piwik.net", "http://piwik.com/test/")); + API::getInstance()->addSite("site2", array("http://piwik.com/test/")); + API::getInstance()->addSite("site3", array("http://piwik.org")); + + $resultWanted = array( + 0 => array("idsite" => 1, "name" => "site1", "main_url" => "http://piwik.net", "ecommerce" => 0, 'sitesearch' => 1, 'sitesearch_keyword_parameters' => '', 'sitesearch_category_parameters' => '', "excluded_ips" => "", 'excluded_parameters' => '', 'excluded_user_agents' => '', 'timezone' => 'UTC', 'currency' => 'USD', 'group' => '', 'keep_url_fragment' => 0, 'type' => 'website'), + 1 => array("idsite" => 3, "name" => "site3", "main_url" => "http://piwik.org", "ecommerce" => 0, 'sitesearch' => 1, 'sitesearch_keyword_parameters' => '', 'sitesearch_category_parameters' => '', "excluded_ips" => "", 'excluded_parameters' => '', 'excluded_user_agents' => '', 'timezone' => 'UTC', 'currency' => 'USD', 'group' => '', 'keep_url_fragment' => 0, 'type' => 'website'), + ); + + FakeAccess::setIdSitesView(array(1, 3)); + FakeAccess::setIdSitesAdmin(array()); + + $sites = API::getInstance()->getSitesWithViewAccess(); + // we dont test the ts_created + unset($sites[0]['ts_created']); + unset($sites[1]['ts_created']); + $this->assertEquals($resultWanted, $sites); + } + + /** + * there is no admin site available -> array() + * + * @group Plugins + */ + public function testGetSitesWithAtLeastViewAccessNoResult() + { + FakeAccess::setIdSitesView(array()); + FakeAccess::setIdSitesAdmin(array()); + + $sites = API::getInstance()->getSitesWithAtLeastViewAccess(); + $this->assertEquals(array(), $sites); + } + + /** + * normal case, admin and view and noaccess website => return only admin + * + * @group Plugins + */ + public function testGetSitesWithAtLeastViewAccess() + { + API::getInstance()->addSite("site1", array("http://piwik.net", "http://piwik.com/test/"), $ecommerce = 1); + API::getInstance()->addSite("site2", array("http://piwik.com/test/")); + API::getInstance()->addSite("site3", array("http://piwik.org")); + + $resultWanted = array( + 0 => array("idsite" => 1, "name" => "site1", "main_url" => "http://piwik.net", "ecommerce" => 1, "excluded_ips" => "", 'sitesearch' => 1, 'sitesearch_keyword_parameters' => '', 'sitesearch_category_parameters' => '', 'excluded_parameters' => '', 'excluded_user_agents' => '', 'timezone' => 'UTC', 'currency' => 'USD', 'group' => '', 'keep_url_fragment' => 0, 'type' => 'website'), + 1 => array("idsite" => 3, "name" => "site3", "main_url" => "http://piwik.org", "ecommerce" => 0, "excluded_ips" => "", 'sitesearch' => 1, 'sitesearch_keyword_parameters' => '', 'sitesearch_category_parameters' => '', 'excluded_parameters' => '', 'excluded_user_agents' => '', 'timezone' => 'UTC', 'currency' => 'USD', 'group' => '', 'keep_url_fragment' => 0, 'type' => 'website'), + ); + + FakeAccess::setIdSitesView(array(1, 3)); + FakeAccess::setIdSitesAdmin(array()); + + $sites = API::getInstance()->getSitesWithAtLeastViewAccess(); + // we dont test the ts_created + unset($sites[0]['ts_created']); + unset($sites[1]['ts_created']); + $this->assertEquals($resultWanted, $sites); + } + + /** + * no urls for this site => array() + * + * @group Plugins + */ + public function testGetSiteUrlsFromIdNoUrls() + { + $idsite = API::getInstance()->addSite("site1", array("http://piwik.net")); + + $urls = API::getInstance()->getSiteUrlsFromId($idsite); + $this->assertEquals(array("http://piwik.net"), $urls); + } + + /** + * normal case + * + * @group Plugins + */ + public function testGetSiteUrlsFromIdManyUrls() + { + $site = array("http://piwik.net", + "http://piwik.org", + "http://piwik.org", + "http://piwik.com"); + sort($site); + + $idsite = API::getInstance()->addSite("site1", $site); + + $siteWanted = array("http://piwik.net", + "http://piwik.org", + "http://piwik.com"); + sort($siteWanted); + $urls = API::getInstance()->getSiteUrlsFromId($idsite); + + $this->assertEquals($siteWanted, $urls); + } + + /** + * wrongId => exception + * + * @group Plugins + */ + public function testGetSiteUrlsFromIdWrongId() + { + try { + FakeAccess::setIdSitesView(array(3)); + FakeAccess::setIdSitesAdmin(array()); + API::getInstance()->getSiteUrlsFromId(1); + } catch (Exception $e) { + return; + } + $this->fail('Expected exception not raised'); + } + + /** + * one url => no change to alias urls + * + * @group Plugins + */ + public function testUpdateSiteOneUrl() + { + $urls = array("http://piwiknew.com", + "http://piwiknew.net", + "http://piwiknew.org", + "http://piwiknew.fr"); + $idsite = API::getInstance()->addSite("site1", $urls); + + $newMainUrl = "http://main.url"; + + // Also test that the group was set to empty, and is searchable + $websites = API::getInstance()->getSitesFromGroup(''); + $this->assertEquals(1, count($websites)); + + // the Update doesn't change the group field + API::getInstance()->updateSite($idsite, "test toto@{}", $newMainUrl); + $websites = API::getInstance()->getSitesFromGroup(''); + $this->assertEquals(1, count($websites)); + + // Updating the group to something + $group = 'something'; + API::getInstance()->updateSite($idsite, "test toto@{}", $newMainUrl, $ecommerce = 0, $ss = true, $ss_kwd = null, $ss_cat = '', $ips = null, $parametersExclude = null, $timezone = null, $currency = null, $group); + $websites = API::getInstance()->getSitesFromGroup($group); + $this->assertEquals(1, count($websites)); + $this->assertEquals(date('Y-m-d'), date('Y-m-d', strtotime($websites[0]['ts_created']))); + + // Updating the group to nothing + $group = ''; + $type = 'mobileAppTest'; + API::getInstance()->updateSite($idsite, "test toto@{}", $newMainUrl, $ecommerce = 0, $ss = false, $ss_kwd = '', $ss_cat = null, $ips = null, $parametersExclude = null, $timezone = null, $currency = null, $group, $startDate = '2010-01-01', $excludedUserAgent = null, $keepUrlFragment = 1, $type); + $websites = API::getInstance()->getSitesFromGroup($group); + $this->assertEquals(1, count($websites)); + $this->assertEquals('2010-01-01', date('Y-m-d', strtotime($websites[0]['ts_created']))); + + // Test setting the website type + $this->assertEquals($type, Site::getTypeFor($idsite)); + + // Check Alias URLs contain only main url + $allUrls = API::getInstance()->getSiteUrlsFromId($idsite); + $this->assertEquals($newMainUrl, $allUrls[0]); + $aliasUrls = array_slice($allUrls, 1); + $this->assertEquals(array(), $aliasUrls); + + } + + /** + * strange name and NO URL => name ok, main_url not updated + * + * @group Plugins + */ + public function testUpdateSiteStrangeNameNoUrl() + { + $idsite = API::getInstance()->addSite("site1", "http://main.url"); + $newName = "test toto@{'786'}"; + + API::getInstance()->updateSite($idsite, $newName); + + $site = API::getInstance()->getSiteFromId($idsite); + + $this->assertEquals($newName, $site['name']); + // url didn't change because parameter url NULL in updateSite + $this->assertEquals("http://main.url", $site['main_url']); + } + + /** + * several urls => both main and alias are updated + * also test the update of group field + * + * @group Plugins + */ + public function testUpdateSiteSeveralUrlsAndGroup() + { + $urls = array("http://piwiknew.com", + "http://piwiknew.net", + "http://piwiknew.org", + "http://piwiknew.fr"); + + $group = 'GROUP Before'; + $idsite = API::getInstance()->addSite("site1", $urls, $ecommerce = 1, + $siteSearch = 1, $searchKeywordParameters = null, $searchCategoryParameters = null, + $excludedIps = null, $excludedQueryParameters = null, $timezone = null, $currency = null, $group, $startDate = '2011-01-01'); + + $websites = API::getInstance()->getSitesFromGroup($group); + $this->assertEquals(1, count($websites)); + + $newurls = array("http://piwiknew2.com", + "http://piwiknew2.net", + "http://piwiknew2.org", + "http://piwiknew2.fr"); + + $groupAfter = ' GROUP After'; + API::getInstance()->updateSite($idsite, "test toto@{}", $newurls, $ecommerce = 0, + $siteSearch = 1, $searchKeywordParameters = null, $searchCategoryParameters = null, + $excludedIps = null, $excludedQueryParameters = null, $timezone = null, $currency = null, $groupAfter); + + // no result for the group before update + $websites = API::getInstance()->getSitesFromGroup($group); + $this->assertEquals(0, count($websites)); + + // Testing that the group was updated properly (and testing that the group value is trimmed before inserted/searched) + $websites = API::getInstance()->getSitesFromGroup($groupAfter . ' '); + $this->assertEquals(1, count($websites)); + $this->assertEquals('2011-01-01', date('Y-m-d', strtotime($websites[0]['ts_created']))); + + // Test fetch website groups + $expectedGroups = array(trim($groupAfter)); + $fetched = API::getInstance()->getSitesGroups(); + $this->assertEquals($expectedGroups, $fetched); + + $allUrls = API::getInstance()->getSiteUrlsFromId($idsite); + sort($allUrls); + sort($newurls); + $this->assertEquals($newurls, $allUrls); + } + + /** + * @group Plugins + */ + public function testGetSitesGroups() + { + $groups = array('group1', ' group1 ', '', 'group2'); + $expectedGroups = array('group1', '', 'group2'); + foreach ($groups as $group) { + API::getInstance()->addSite("test toto@{}", 'http://example.org', $ecommerce = 1, $siteSearch = null, $searchKeywordParameters = null, $searchCategoryParameters = null, $excludedIps = null, $excludedQueryParameters = null, $timezone = null, $currency = null, $group); + } + + $this->assertEquals($expectedGroups, API::getInstance()->getSitesGroups()); + } + + public function getInvalidTimezoneData() + { + return array( + array('UTC+15'), + array('Paris'), + ); + } + + /** + * + * @dataProvider getInvalidTimezoneData + * @group Plugins + */ + public function testAddSitesInvalidTimezone($timezone) + { + try { + API::getInstance()->addSite("site1", array('http://example.org'), $ecommerce = 0, + $siteSearch = 1, $searchKeywordParameters = null, $searchCategoryParameters = null, $ip = '', $params = '', $timezone); + } catch (Exception $e) { + return; + } + $this->fail('Expected exception not raised'); + } + + /** + * @group Plugins + */ + public function testAddSitesInvalidCurrency() + { + try { + $invalidCurrency = '€'; + API::getInstance()->addSite("site1", array('http://example.org'), $ecommerce = 0, + $siteSearch = 1, $searchKeywordParameters = null, $searchCategoryParameters = null, '', 'UTC', $invalidCurrency); + } catch (Exception $e) { + return; + } + $this->fail('Expected exception not raised'); + } + + /** + * @group Plugins + */ + public function testSetDefaultTimezoneAndCurrencyAndExcludedQueryParametersAndExcludedIps() + { + // test that they return default values + $defaultTimezone = API::getInstance()->getDefaultTimezone(); + $this->assertEquals('UTC', $defaultTimezone); + $defaultCurrency = API::getInstance()->getDefaultCurrency(); + $this->assertEquals('USD', $defaultCurrency); + $excludedIps = API::getInstance()->getExcludedIpsGlobal(); + $this->assertEquals('', $excludedIps); + $excludedQueryParameters = API::getInstance()->getExcludedQueryParametersGlobal(); + $this->assertEquals('', $excludedQueryParameters); + + // test that when not specified, defaults are set as expected + $idsite = API::getInstance()->addSite("site1", array('http://example.org')); + $site = new Site($idsite); + $this->assertEquals('UTC', $site->getTimezone()); + $this->assertEquals('USD', $site->getCurrency()); + $this->assertEquals('', $site->getExcludedQueryParameters()); + $this->assertEquals('', $site->getExcludedIps()); + $this->assertEquals(false, $site->isEcommerceEnabled()); + + // set the global timezone and get it + $newDefaultTimezone = 'UTC+5.5'; + API::getInstance()->setDefaultTimezone($newDefaultTimezone); + $defaultTimezone = API::getInstance()->getDefaultTimezone(); + $this->assertEquals($newDefaultTimezone, $defaultTimezone); + + // set the default currency and get it + $newDefaultCurrency = 'EUR'; + API::getInstance()->setDefaultCurrency($newDefaultCurrency); + $defaultCurrency = API::getInstance()->getDefaultCurrency(); + $this->assertEquals($newDefaultCurrency, $defaultCurrency); + + // set the global IPs to exclude and get it + $newGlobalExcludedIps = '1.1.1.*,1.1.*.*,150.1.1.1'; + API::getInstance()->setGlobalExcludedIps($newGlobalExcludedIps); + $globalExcludedIps = API::getInstance()->getExcludedIpsGlobal(); + $this->assertEquals($newGlobalExcludedIps, $globalExcludedIps); + + // set the global URL query params to exclude and get it + $newGlobalExcludedQueryParameters = 'PHPSESSID,blabla, TesT'; + // removed the space + $expectedGlobalExcludedQueryParameters = 'PHPSESSID,blabla,TesT'; + API::getInstance()->setGlobalExcludedQueryParameters($newGlobalExcludedQueryParameters); + $globalExcludedQueryParameters = API::getInstance()->getExcludedQueryParametersGlobal(); + $this->assertEquals($expectedGlobalExcludedQueryParameters, $globalExcludedQueryParameters); + + // create a website and check that default currency and default timezone are set + // however, excluded IPs and excluded query Params are not returned + $idsite = API::getInstance()->addSite("site1", array('http://example.org'), $ecommerce = 0, + $siteSearch = 0, $searchKeywordParameters = 'test1,test2', $searchCategoryParameters = 'test2,test1', + '', '', $newDefaultTimezone); + $site = new Site($idsite); + $this->assertEquals($newDefaultTimezone, $site->getTimezone()); + $this->assertEquals(date('Y-m-d'), $site->getCreationDate()->toString()); + $this->assertEquals($newDefaultCurrency, $site->getCurrency()); + $this->assertEquals('', $site->getExcludedIps()); + $this->assertEquals('', $site->getExcludedQueryParameters()); + $this->assertEquals('test1,test2', $site->getSearchKeywordParameters()); + $this->assertEquals('test2,test1', $site->getSearchCategoryParameters()); + $this->assertFalse($site->isSiteSearchEnabled()); + $this->assertFalse(Site::isSiteSearchEnabledFor($idsite)); + $this->assertFalse($site->isEcommerceEnabled()); + $this->assertFalse(Site::isEcommerceEnabledFor($idsite)); + } + + /** + * @group Plugins + */ + public function testGetSitesIdFromSiteUrlSuperUser() + { + API::getInstance()->addSite("site1", array("http://piwik.net", "http://piwik.com")); + API::getInstance()->addSite("site2", array("http://piwik.com", "http://piwik.net")); + API::getInstance()->addSite("site3", array("http://piwik.com", "http://piwik.org")); + + $idsites = API::getInstance()->getSitesIdFromSiteUrl('http://piwik.org'); + $this->assertTrue(count($idsites) == 1); + + $idsites = API::getInstance()->getSitesIdFromSiteUrl('http://www.piwik.org'); + $this->assertTrue(count($idsites) == 1); + + $idsites = API::getInstance()->getSitesIdFromSiteUrl('http://piwik.net'); + $this->assertTrue(count($idsites) == 2); + + $idsites = API::getInstance()->getSitesIdFromSiteUrl('http://piwik.com'); + $this->assertTrue(count($idsites) == 3); + } + + /** + * @group Plugins + */ + public function testGetSitesIdFromSiteUrlUser() + { + API::getInstance()->addSite("site1", array("http://www.piwik.net", "http://piwik.com")); + API::getInstance()->addSite("site2", array("http://piwik.com", "http://piwik.net")); + API::getInstance()->addSite("site3", array("http://piwik.com", "http://piwik.org")); + + $saveAccess = Access::getInstance(); + + APIUsersManager::getInstance()->addUser("user1", "geqgegagae", "tegst@tesgt.com", "alias"); + APIUsersManager::getInstance()->setUserAccess("user1", "view", array(1)); + + APIUsersManager::getInstance()->addUser("user2", "geqgegagae", "tegst2@tesgt.com", "alias"); + APIUsersManager::getInstance()->setUserAccess("user2", "view", array(1)); + APIUsersManager::getInstance()->setUserAccess("user2", "admin", array(3)); + + APIUsersManager::getInstance()->addUser("user3", "geqgegagae", "tegst3@tesgt.com", "alias"); + APIUsersManager::getInstance()->setUserAccess("user3", "view", array(1, 2)); + APIUsersManager::getInstance()->setUserAccess("user3", "admin", array(3)); + + $pseudoMockAccess = new FakeAccess; + FakeAccess::$superUser = false; + FakeAccess::$identity = 'user1'; + FakeAccess::setIdSitesView(array(1)); + FakeAccess::setIdSitesAdmin(array()); + Access::setSingletonInstance($pseudoMockAccess); + $idsites = API::getInstance()->getSitesIdFromSiteUrl('http://piwik.com'); + $this->assertEquals(1, count($idsites)); + + // testing URL normalization + $idsites = API::getInstance()->getSitesIdFromSiteUrl('http://www.piwik.com'); + $this->assertEquals(1, count($idsites)); + $idsites = API::getInstance()->getSitesIdFromSiteUrl('http://piwik.net'); + $this->assertEquals(1, count($idsites)); + + $pseudoMockAccess = new FakeAccess; + FakeAccess::$superUser = false; + FakeAccess::$identity = 'user2'; + FakeAccess::setIdSitesView(array(1)); + FakeAccess::setIdSitesAdmin(array(3)); + Access::setSingletonInstance($pseudoMockAccess); + $idsites = API::getInstance()->getSitesIdFromSiteUrl('http://piwik.com'); + $this->assertEquals(2, count($idsites)); + + $pseudoMockAccess = new FakeAccess; + FakeAccess::$superUser = false; + FakeAccess::$identity = 'user3'; + FakeAccess::setIdSitesView(array(1, 2)); + FakeAccess::setIdSitesAdmin(array(3)); + Access::setSingletonInstance($pseudoMockAccess); + $idsites = API::getInstance()->getSitesIdFromSiteUrl('http://piwik.com'); + $this->assertEquals(3, count($idsites)); + + Access::setSingletonInstance($saveAccess); + } + + /** + * @group Plugins + */ + public function testGetSitesFromTimezones() + { + API::getInstance()->addSite("site3", array("http://piwik.org"), null, $siteSearch = 1, $searchKeywordParameters = null, $searchCategoryParameters = null, null, null, 'UTC'); + $idsite2 = API::getInstance()->addSite("site3", array("http://piwik.org"), null, $siteSearch = 1, $searchKeywordParameters = null, $searchCategoryParameters = null, null, null, 'Pacific/Auckland'); + $idsite3 = API::getInstance()->addSite("site3", array("http://piwik.org"), null, $siteSearch = 1, $searchKeywordParameters = null, $searchCategoryParameters = null, null, null, 'Pacific/Auckland'); + $idsite4 = API::getInstance()->addSite("site3", array("http://piwik.org"), null, $siteSearch = 1, $searchKeywordParameters = null, $searchCategoryParameters = null, null, null, 'UTC+10'); + $result = API::getInstance()->getSitesIdFromTimezones(array('UTC+10', 'Pacific/Auckland')); + $this->assertEquals(array($idsite2, $idsite3, $idsite4), $result); + } +} diff --git a/plugins/SitesManager/tests/SiteUrlsTest.php b/plugins/SitesManager/tests/SiteUrlsTest.php deleted file mode 100644 index 588b3c08f2..0000000000 --- a/plugins/SitesManager/tests/SiteUrlsTest.php +++ /dev/null @@ -1,145 +0,0 @@ -siteUrls = new SiteUrls(); - $this->api = API::getInstance(); - - SiteUrls::clearSitesCache(); - } - - public function testGetAllSiteUrls_shouldReturnAnEmptyArray_IfThereAreNoSites() - { - $this->assertSiteUrls(array()); - } - - public function testGetAllSiteUrls_shouldReturnUrlsForEachSiteId() - { - $this->addSite('http://www.example.com'); // only one main URL - $this->assertSiteUrls(array(1 => array('http://www.example.com'))); - - $this->addSite('http://www.example.com', 'http://www.piwik.org'); // main URL and alias URL - $this->assertSiteUrls(array(1 => array('http://www.example.com'), 2 => array('http://www.example.com', 'http://www.piwik.org'))); - - $this->api->addSiteAliasUrls(2, 'http://piwik.org'); - $this->assertSiteUrls(array(1 => array('http://www.example.com'), 2 => array('http://www.example.com', 'http://piwik.org', 'http://www.piwik.org'))); - - $this->api->setSiteAliasUrls(2, array()); - $this->assertSiteUrls(array(1 => array('http://www.example.com'), 2 => array('http://www.example.com'))); - } - - public function testGetAllCachedSiteUrls_shouldReturnAnEmptyArray_IfThereAreNoSites() - { - $this->assertCachedSiteUrls(array()); - } - - public function testGetAllCachedSiteUrls_ShouldReturnCorrectResultEvenIfItIsCachedAsWeClearTheCacheOnAnyChange() - { - $this->addSite('http://www.example.com'); // only one main URL - $this->assertCachedSiteUrls(array(1 => array('http://www.example.com'))); - - $this->addSite('http://www.example.com', 'http://www.piwik.org'); // main URL and alias URL - $this->assertCachedSiteUrls(array(1 => array('http://www.example.com'), 2 => array('http://www.example.com', 'http://www.piwik.org'))); - - $this->api->addSiteAliasUrls(2, 'http://piwik.org'); - $this->assertCachedSiteUrls(array(1 => array('http://www.example.com'), 2 => array('http://www.example.com', 'http://piwik.org', 'http://www.piwik.org'))); - - $this->api->setSiteAliasUrls(2, array()); - $this->assertCachedSiteUrls(array(1 => array('http://www.example.com'), 2 => array('http://www.example.com'))); - - $this->api->updateSite(1, 'siteName3', array('http://updated.example.com', 'http://2.example.com')); - $this->assertCachedSiteUrls(array(1 => array('http://updated.example.com', 'http://2.example.com'), 2 => array('http://www.example.com'))); - } - - public function testGetAllCachedSiteUrls_ShouldWriteACacheFile() - { - // make sure cache is empty - $this->assertValueInCache(false); - - $this->addSite('http://www.example.com'); - $this->siteUrls->getAllCachedSiteUrls(); - - // make sure we have a cached result - $this->assertValueInCache(array(1 => array('http://www.example.com'))); - } - - public function test_clearSitesCache_ShouldActuallyDeleteACache() - { - $this->addSite('http://www.example.com'); - $this->siteUrls->getAllCachedSiteUrls(); - - // make sure we have a cached result - $this->assertValueInCache(array(1 => array('http://www.example.com'))); - - SiteUrls::clearSitesCache(); - - // make sure is empty now - $this->assertValueInCache(false); - } - - public function testGetAllCachedSiteUrls_ShouldReadFromTheCacheFile() - { - $urlsToFake = array(1 => 'Whatever'); - $cache = new CacheFile('tracker', 600); - $cache->set('allSiteUrlsPerSite', $urlsToFake); - - $actual = $this->siteUrls->getAllCachedSiteUrls(); - - $this->assertEquals($urlsToFake, $actual); - } - - private function assertSiteUrls($expectedUrls) - { - $urls = $this->siteUrls->getAllSiteUrls(); - $this->assertEquals($expectedUrls, $urls); - } - - private function assertCachedSiteUrls($expectedUrls) - { - $urls = $this->siteUrls->getAllCachedSiteUrls(); - $this->assertEquals($expectedUrls, $urls); - } - - private function addSite($urls) - { - $this->api->addSite('siteName', func_get_args()); - } - - private function assertValueInCache($value) - { - $cache = new CacheFile('tracker', 600); - $siteUrls = $cache->get('allSiteUrlsPerSite'); - - $this->assertEquals($value, $siteUrls); - } -} diff --git a/plugins/SitesManager/tests/SitesManagerTest.php b/plugins/SitesManager/tests/SitesManagerTest.php deleted file mode 100644 index 6d08f0de20..0000000000 --- a/plugins/SitesManager/tests/SitesManagerTest.php +++ /dev/null @@ -1,1000 +0,0 @@ - exception - * - * @group Plugins - */ - public function testAddSiteEmptyName() - { - try { - API::getInstance()->addSite("", array("http://piwik.net")); - } catch (Exception $e) { - return; - } - $this->fail('Expected exception not raised'); - } - - /** - * DataProvider for testAddSiteWrongUrls - */ - public function getInvalidUrlData() - { - return array( - array(array()), // no urls - array(array("")), - array(""), - array("httpww://piwik.net"), - array("httpww://piwik.net/gqg~#"), - ); - } - - /** - * wrong urls -> exception - * - * @dataProvider getInvalidUrlData - * @group Plugins - */ - public function testAddSiteWrongUrls($url) - { - try { - API::getInstance()->addSite("name", $url); - } catch (Exception $e) { - return; - } - $this->fail('Expected exception not raised'); - } - - /** - * Test with valid IPs - * - * @group Plugins - */ - public function testAddSiteExcludedIpsAndtimezoneAndCurrencyAndExcludedQueryParametersValid() - { - $ips = '1.2.3.4,1.1.1.*,1.2.*.*,1.*.*.*'; - $timezone = 'Europe/Paris'; - $currency = 'EUR'; - $excludedQueryParameters = 'p1,P2, P33333'; - $expectedExcludedQueryParameters = 'p1,P2,P33333'; - $excludedUserAgents = " p1,P2, \nP3333 "; - $expectedExcludedUserAgents = "p1,P2,P3333"; - $expectedWebsiteType = 'mobile-\'app'; - $keepUrlFragment = 1; - $idsite = API::getInstance()->addSite("name", "http://piwik.net/", $ecommerce = 1, - $siteSearch = 1, $searchKeywordParameters = 'search,param', $searchCategoryParameters = 'cat,category', - $ips, $excludedQueryParameters, $timezone, $currency, $group = null, $startDate = null, $excludedUserAgents, - $keepUrlFragment, $expectedWebsiteType); - $siteInfo = API::getInstance()->getSiteFromId($idsite); - $this->assertEquals($ips, $siteInfo['excluded_ips']); - $this->assertEquals($timezone, $siteInfo['timezone']); - $this->assertEquals($currency, $siteInfo['currency']); - $this->assertEquals($ecommerce, $siteInfo['ecommerce']); - $this->assertTrue(Site::isEcommerceEnabledFor($idsite)); - $this->assertEquals($siteSearch, $siteInfo['sitesearch']); - $this->assertTrue(Site::isSiteSearchEnabledFor($idsite)); - $this->assertEquals($expectedWebsiteType, $siteInfo['type']); - $this->assertEquals($expectedWebsiteType, Site::getTypeFor($idsite)); - - $this->assertEquals($searchKeywordParameters, $siteInfo['sitesearch_keyword_parameters']); - $this->assertEquals($searchCategoryParameters, $siteInfo['sitesearch_category_parameters']); - $this->assertEquals($expectedExcludedQueryParameters, $siteInfo['excluded_parameters']); - $this->assertEquals($expectedExcludedUserAgents, $siteInfo['excluded_user_agents']); - } - - /** - * dataProvider for testAddSiteExcludedIpsNotValid - */ - public function getInvalidIPsData() - { - return array( - array('35817587341'), - array('ieagieha'), - array('1.2.3'), - array('*.1.1.1'), - array('*.*.1.1'), - array('*.*.*.1'), - array('1.1.1.1.1'), - ); - } - - /** - * Test with invalid IPs - * - * @dataProvider getInvalidIPsData - * @group Plugins - */ - public function testAddSiteExcludedIpsNotValid($ip) - { - try { - API::getInstance()->addSite("name", "http://piwik.net/", $ecommerce = 0, - $siteSearch = 1, $searchKeywordParameters = null, $searchCategoryParameters = null, $ip); - } catch (Exception $e) { - return; - } - $this->fail('Expected exception not raised'); - } - - /** - * one url -> one main_url and nothing inserted as alias urls - * - * @group Plugins - */ - public function testAddSiteOneUrl() - { - $url = "http://piwik.net/"; - $urlOK = "http://piwik.net"; - $idsite = API::getInstance()->addSite("name", $url); - $this->assertInternalType(PHPUnit_Framework_Constraint_IsType::TYPE_INT, $idsite); - - $siteInfo = API::getInstance()->getSiteFromId($idsite); - $this->assertEquals($urlOK, $siteInfo['main_url']); - $this->assertEquals(date('Y-m-d'), date('Y-m-d', strtotime($siteInfo['ts_created']))); - - $siteUrls = API::getInstance()->getSiteUrlsFromId($idsite); - $this->assertEquals(1, count($siteUrls)); - } - - /** - * several urls -> one main_url and others as alias urls - * - * @group Plugins - */ - public function testAddSiteSeveralUrls() - { - $urls = array("http://piwik.net/", "http://piwik.com", "https://piwik.net/test/"); - $urlsOK = array("http://piwik.net", "http://piwik.com", "https://piwik.net/test"); - $idsite = API::getInstance()->addSite("super website", $urls); - $this->assertInternalType(PHPUnit_Framework_Constraint_IsType::TYPE_INT, $idsite); - - $siteInfo = API::getInstance()->getSiteFromId($idsite); - $this->assertEquals($urlsOK[0], $siteInfo['main_url']); - - $siteUrls = API::getInstance()->getSiteUrlsFromId($idsite); - $this->assertEquals($urlsOK, $siteUrls); - } - - /** - * strange name - * - * @group Plugins - */ - public function testAddSiteStrangeName() - { - $name = "supertest(); ~@@()''!£\$'%%^'!£ போ"; - $idsite = API::getInstance()->addSite($name, "http://piwik.net"); - $this->assertInternalType(PHPUnit_Framework_Constraint_IsType::TYPE_INT, $idsite); - - $siteInfo = API::getInstance()->getSiteFromId($idsite); - $this->assertEquals($name, $siteInfo['name']); - - } - - /** - * adds a site - * use by several other unit tests - */ - protected function _addSite() - { - $name = "website "; - $idsite = API::getInstance()->addSite($name, array("http://piwik.net", "http://piwik.com/test/")); - $this->assertInternalType(PHPUnit_Framework_Constraint_IsType::TYPE_INT, $idsite); - - $siteInfo = API::getInstance()->getSiteFromId($idsite); - $this->assertEquals($name, $siteInfo['name']); - $this->assertEquals("http://piwik.net", $siteInfo['main_url']); - - $siteUrls = API::getInstance()->getSiteUrlsFromId($idsite); - $this->assertEquals(array("http://piwik.net", "http://piwik.com/test"), $siteUrls); - - return $idsite; - } - - /** - * no duplicate -> all the urls are saved - * - * @group Plugins - */ - public function testAddSiteUrlsnoDuplicate() - { - $idsite = $this->_addSite(); - - $siteUrlsBefore = API::getInstance()->getSiteUrlsFromId($idsite); - - $toAdd = array("http://piwik1.net", - "http://piwik2.net", - "http://piwik3.net/test/", - "http://localhost/test", - "http://localho5.st/test", - "http://l42578gqege.f4", - "http://super.com/test/test/atqata675675/te" - ); - $toAddValid = array("http://piwik1.net", - "http://piwik2.net", - "http://piwik3.net/test", - "http://localhost/test", - "http://localho5.st/test", - "http://l42578gqege.f4", - "http://super.com/test/test/atqata675675/te"); - - $insertedUrls = API::getInstance()->addSiteAliasUrls($idsite, $toAdd); - $this->assertEquals(count($toAdd), $insertedUrls); - - $siteUrlsAfter = API::getInstance()->getSiteUrlsFromId($idsite); - - $shouldHave = array_merge($siteUrlsBefore, $toAddValid); - sort($shouldHave); - - sort($siteUrlsAfter); - - $this->assertEquals($shouldHave, $siteUrlsAfter); - } - - /** - * duplicate -> don't save the already existing URLs - * - * @group Plugins - */ - public function testAddSiteUrlsDuplicate() - { - $idsite = $this->_addSite(); - - $siteUrlsBefore = API::getInstance()->getSiteUrlsFromId($idsite); - - $toAdd = array_merge($siteUrlsBefore, array("http://piwik1.net", "http://piwik2.net")); - - $insertedUrls = API::getInstance()->addSiteAliasUrls($idsite, $toAdd); - $this->assertEquals(count($toAdd) - count($siteUrlsBefore), $insertedUrls); - - $siteUrlsAfter = API::getInstance()->getSiteUrlsFromId($idsite); - - $shouldHave = $toAdd; - sort($shouldHave); - - sort($siteUrlsAfter); - - $this->assertEquals($shouldHave, $siteUrlsAfter); - } - - /** - * case empty array => nothing happens - * - * @group Plugins - */ - public function testAddSiteUrlsNoUrlsToAdd1() - { - $idsite = $this->_addSite(); - - $siteUrlsBefore = API::getInstance()->getSiteUrlsFromId($idsite); - - $toAdd = array(); - - $insertedUrls = API::getInstance()->addSiteAliasUrls($idsite, $toAdd); - $this->assertEquals(count($toAdd), $insertedUrls); - - $siteUrlsAfter = API::getInstance()->getSiteUrlsFromId($idsite); - - $shouldHave = $siteUrlsBefore; - sort($shouldHave); - - sort($siteUrlsAfter); - - $this->assertEquals($shouldHave, $siteUrlsAfter); - } - - /** - * case array only duplicate => nothing happens - * - * @group Plugins - */ - public function testAddSiteUrlsNoUrlsToAdd2() - { - $idsite = $this->_addSite(); - - $siteUrlsBefore = API::getInstance()->getSiteUrlsFromId($idsite); - - $toAdd = $siteUrlsBefore; - - $insertedUrls = API::getInstance()->addSiteAliasUrls($idsite, $toAdd); - $this->assertEquals(0, $insertedUrls); - - $siteUrlsAfter = API::getInstance()->getSiteUrlsFromId($idsite); - - $shouldHave = $siteUrlsBefore; - sort($shouldHave); - - sort($siteUrlsAfter); - - $this->assertEquals($shouldHave, $siteUrlsAfter); - } - - /** - * wrong format urls => exception - * - * @group Plugins - */ - public function testAddSiteUrlsWrongUrlsFormat3() - { - try { - $idsite = $this->_addSite(); - $toAdd = array("http:mpigeq"); - API::getInstance()->addSiteAliasUrls($idsite, $toAdd); - } catch (Exception $e) { - return; - } - $this->fail('Expected exception not raised'); - } - - /** - * wrong idsite => no exception because simply no access to this resource - * - * @group Plugins - */ - public function testAddSiteUrlsWrongIdSite1() - { - try { - $toAdd = array("http://pigeq.com/test"); - API::getInstance()->addSiteAliasUrls(-1, $toAdd); - } catch (Exception $e) { - return; - } - $this->fail('Expected exception not raised'); - } - - /** - * wrong idsite => exception - * - * @group Plugins - */ - public function testAddSiteUrlsWrongIdSite2() - { - try { - $toAdd = array("http://pigeq.com/test"); - API::getInstance()->addSiteAliasUrls(155, $toAdd); - } catch (Exception $e) { - return; - } - $this->fail('Expected exception not raised'); - } - - /** - * no Id -> empty array - * - * @group Plugins - */ - public function testGetAllSitesIdNoId() - { - $ids = API::getInstance()->getAllSitesId(); - $this->assertEquals(array(), $ids); - } - - /** - * several Id -> normal array - * - * @group Plugins - */ - public function testGetAllSitesIdSeveralId() - { - $name = "tetq"; - $idsites = array( - API::getInstance()->addSite($name, array("http://piwik.net", "http://piwik.com/test/")), - API::getInstance()->addSite($name, array("http://piwik.net", "http://piwik.com/test/")), - API::getInstance()->addSite($name, array("http://piwik.net", "http://piwik.com/test/")), - API::getInstance()->addSite($name, array("http://piwik.net", "http://piwik.com/test/")), - API::getInstance()->addSite($name, array("http://piwik.net", "http://piwik.com/test/")), - ); - - $ids = API::getInstance()->getAllSitesId(); - $this->assertEquals($idsites, $ids); - } - - /** - * wrong id => exception - * - * @group Plugins - */ - public function testGetSiteFromIdWrongId1() - { - try { - API::getInstance()->getSiteFromId(0); - } catch (Exception $e) { - return; - } - $this->fail('Expected exception not raised'); - } - - /** - * wrong id => exception - * - * @group Plugins - */ - public function testGetSiteFromIdWrongId2() - { - try { - API::getInstance()->getSiteFromId("x1"); - } catch (Exception $e) { - return; - } - $this->fail('Expected exception not raised'); - } - - /** - * wrong id : no access => exception - * - * @group Plugins - */ - public function testGetSiteFromIdWrongId3() - { - $idsite = API::getInstance()->addSite("site", array("http://piwik.net", "http://piwik.com/test/")); - $this->assertEquals(1, $idsite); - - // set noaccess to site 1 - FakeAccess::setIdSitesView(array(2)); - FakeAccess::setIdSitesAdmin(array()); - - try { - API::getInstance()->getSiteFromId(1); - } catch (Exception $e) { - return; - } - $this->fail('Expected exception not raised'); - } - - /** - * normal case - * - * @group Plugins - */ - public function testGetSiteFromIdNormalId() - { - $name = "website ''"; - $idsite = API::getInstance()->addSite($name, array("http://piwik.net", "http://piwik.com/test/")); - $this->assertInternalType(PHPUnit_Framework_Constraint_IsType::TYPE_INT, $idsite); - - $siteInfo = API::getInstance()->getSiteFromId($idsite); - $this->assertEquals($name, $siteInfo['name']); - $this->assertEquals("http://piwik.net", $siteInfo['main_url']); - } - - /** - * there is no admin site available -> array() - * - * @group Plugins - */ - public function testGetSitesWithAdminAccessNoResult() - { - FakeAccess::setIdSitesAdmin(array()); - - $sites = API::getInstance()->getSitesWithAdminAccess(); - $this->assertEquals(array(), $sites); - } - - /** - * normal case, admin and view and noaccess website => return only admin - * - * @group Plugins - */ - public function testGetSitesWithAdminAccess() - { - API::getInstance()->addSite("site1", array("http://piwik.net", "http://piwik.com/test/")); - API::getInstance()->addSite("site2", array("http://piwik.com/test/")); - API::getInstance()->addSite("site3", array("http://piwik.org")); - - $resultWanted = array( - 0 => array("idsite" => 1, "name" => "site1", "main_url" => "http://piwik.net", "ecommerce" => 0, "excluded_ips" => "", 'sitesearch' => 1, 'sitesearch_keyword_parameters' => '', 'sitesearch_category_parameters' => '', 'excluded_parameters' => '', 'excluded_user_agents' => '', 'timezone' => 'UTC', 'currency' => 'USD', 'group' => '', 'keep_url_fragment' => 0, 'type' => 'website'), - 1 => array("idsite" => 3, "name" => "site3", "main_url" => "http://piwik.org", "ecommerce" => 0, "excluded_ips" => "", 'sitesearch' => 1, 'sitesearch_keyword_parameters' => '', 'sitesearch_category_parameters' => '', 'excluded_parameters' => '', 'excluded_user_agents' => '', 'timezone' => 'UTC', 'currency' => 'USD', 'group' => '', 'keep_url_fragment' => 0, 'type' => 'website'), - ); - - FakeAccess::setIdSitesAdmin(array(1, 3)); - - $sites = API::getInstance()->getSitesWithAdminAccess(); - - // we dont test the ts_created - unset($sites[0]['ts_created']); - unset($sites[1]['ts_created']); - $this->assertEquals($resultWanted, $sites); - } - - /** - * there is no admin site available -> array() - * - * @group Plugins - */ - public function testGetSitesWithViewAccessNoResult() - { - FakeAccess::setIdSitesView(array()); - FakeAccess::setIdSitesAdmin(array()); - - $sites = API::getInstance()->getSitesWithViewAccess(); - $this->assertEquals(array(), $sites); - } - - /** - * normal case, admin and view and noaccess website => return only admin - * - * @group Plugins - */ - public function testGetSitesWithViewAccess() - { - API::getInstance()->addSite("site1", array("http://piwik.net", "http://piwik.com/test/")); - API::getInstance()->addSite("site2", array("http://piwik.com/test/")); - API::getInstance()->addSite("site3", array("http://piwik.org")); - - $resultWanted = array( - 0 => array("idsite" => 1, "name" => "site1", "main_url" => "http://piwik.net", "ecommerce" => 0, 'sitesearch' => 1, 'sitesearch_keyword_parameters' => '', 'sitesearch_category_parameters' => '', "excluded_ips" => "", 'excluded_parameters' => '', 'excluded_user_agents' => '', 'timezone' => 'UTC', 'currency' => 'USD', 'group' => '', 'keep_url_fragment' => 0, 'type' => 'website'), - 1 => array("idsite" => 3, "name" => "site3", "main_url" => "http://piwik.org", "ecommerce" => 0, 'sitesearch' => 1, 'sitesearch_keyword_parameters' => '', 'sitesearch_category_parameters' => '', "excluded_ips" => "", 'excluded_parameters' => '', 'excluded_user_agents' => '', 'timezone' => 'UTC', 'currency' => 'USD', 'group' => '', 'keep_url_fragment' => 0, 'type' => 'website'), - ); - - FakeAccess::setIdSitesView(array(1, 3)); - FakeAccess::setIdSitesAdmin(array()); - - $sites = API::getInstance()->getSitesWithViewAccess(); - // we dont test the ts_created - unset($sites[0]['ts_created']); - unset($sites[1]['ts_created']); - $this->assertEquals($resultWanted, $sites); - } - - /** - * there is no admin site available -> array() - * - * @group Plugins - */ - public function testGetSitesWithAtLeastViewAccessNoResult() - { - FakeAccess::setIdSitesView(array()); - FakeAccess::setIdSitesAdmin(array()); - - $sites = API::getInstance()->getSitesWithAtLeastViewAccess(); - $this->assertEquals(array(), $sites); - } - - /** - * normal case, admin and view and noaccess website => return only admin - * - * @group Plugins - */ - public function testGetSitesWithAtLeastViewAccess() - { - API::getInstance()->addSite("site1", array("http://piwik.net", "http://piwik.com/test/"), $ecommerce = 1); - API::getInstance()->addSite("site2", array("http://piwik.com/test/")); - API::getInstance()->addSite("site3", array("http://piwik.org")); - - $resultWanted = array( - 0 => array("idsite" => 1, "name" => "site1", "main_url" => "http://piwik.net", "ecommerce" => 1, "excluded_ips" => "", 'sitesearch' => 1, 'sitesearch_keyword_parameters' => '', 'sitesearch_category_parameters' => '', 'excluded_parameters' => '', 'excluded_user_agents' => '', 'timezone' => 'UTC', 'currency' => 'USD', 'group' => '', 'keep_url_fragment' => 0, 'type' => 'website'), - 1 => array("idsite" => 3, "name" => "site3", "main_url" => "http://piwik.org", "ecommerce" => 0, "excluded_ips" => "", 'sitesearch' => 1, 'sitesearch_keyword_parameters' => '', 'sitesearch_category_parameters' => '', 'excluded_parameters' => '', 'excluded_user_agents' => '', 'timezone' => 'UTC', 'currency' => 'USD', 'group' => '', 'keep_url_fragment' => 0, 'type' => 'website'), - ); - - FakeAccess::setIdSitesView(array(1, 3)); - FakeAccess::setIdSitesAdmin(array()); - - $sites = API::getInstance()->getSitesWithAtLeastViewAccess(); - // we dont test the ts_created - unset($sites[0]['ts_created']); - unset($sites[1]['ts_created']); - $this->assertEquals($resultWanted, $sites); - } - - /** - * no urls for this site => array() - * - * @group Plugins - */ - public function testGetSiteUrlsFromIdNoUrls() - { - $idsite = API::getInstance()->addSite("site1", array("http://piwik.net")); - - $urls = API::getInstance()->getSiteUrlsFromId($idsite); - $this->assertEquals(array("http://piwik.net"), $urls); - } - - /** - * normal case - * - * @group Plugins - */ - public function testGetSiteUrlsFromIdManyUrls() - { - $site = array("http://piwik.net", - "http://piwik.org", - "http://piwik.org", - "http://piwik.com"); - sort($site); - - $idsite = API::getInstance()->addSite("site1", $site); - - $siteWanted = array("http://piwik.net", - "http://piwik.org", - "http://piwik.com"); - sort($siteWanted); - $urls = API::getInstance()->getSiteUrlsFromId($idsite); - - $this->assertEquals($siteWanted, $urls); - } - - /** - * wrongId => exception - * - * @group Plugins - */ - public function testGetSiteUrlsFromIdWrongId() - { - try { - FakeAccess::setIdSitesView(array(3)); - FakeAccess::setIdSitesAdmin(array()); - API::getInstance()->getSiteUrlsFromId(1); - } catch (Exception $e) { - return; - } - $this->fail('Expected exception not raised'); - } - - /** - * one url => no change to alias urls - * - * @group Plugins - */ - public function testUpdateSiteOneUrl() - { - $urls = array("http://piwiknew.com", - "http://piwiknew.net", - "http://piwiknew.org", - "http://piwiknew.fr"); - $idsite = API::getInstance()->addSite("site1", $urls); - - $newMainUrl = "http://main.url"; - - // Also test that the group was set to empty, and is searchable - $websites = API::getInstance()->getSitesFromGroup(''); - $this->assertEquals(1, count($websites)); - - // the Update doesn't change the group field - API::getInstance()->updateSite($idsite, "test toto@{}", $newMainUrl); - $websites = API::getInstance()->getSitesFromGroup(''); - $this->assertEquals(1, count($websites)); - - // Updating the group to something - $group = 'something'; - API::getInstance()->updateSite($idsite, "test toto@{}", $newMainUrl, $ecommerce = 0, $ss = true, $ss_kwd = null, $ss_cat = '', $ips = null, $parametersExclude = null, $timezone = null, $currency = null, $group); - $websites = API::getInstance()->getSitesFromGroup($group); - $this->assertEquals(1, count($websites)); - $this->assertEquals(date('Y-m-d'), date('Y-m-d', strtotime($websites[0]['ts_created']))); - - // Updating the group to nothing - $group = ''; - $type = 'mobileAppTest'; - API::getInstance()->updateSite($idsite, "test toto@{}", $newMainUrl, $ecommerce = 0, $ss = false, $ss_kwd = '', $ss_cat = null, $ips = null, $parametersExclude = null, $timezone = null, $currency = null, $group, $startDate = '2010-01-01', $excludedUserAgent = null, $keepUrlFragment = 1, $type); - $websites = API::getInstance()->getSitesFromGroup($group); - $this->assertEquals(1, count($websites)); - $this->assertEquals('2010-01-01', date('Y-m-d', strtotime($websites[0]['ts_created']))); - - // Test setting the website type - $this->assertEquals($type, Site::getTypeFor($idsite)); - - // Check Alias URLs contain only main url - $allUrls = API::getInstance()->getSiteUrlsFromId($idsite); - $this->assertEquals($newMainUrl, $allUrls[0]); - $aliasUrls = array_slice($allUrls, 1); - $this->assertEquals(array(), $aliasUrls); - - } - - /** - * strange name and NO URL => name ok, main_url not updated - * - * @group Plugins - */ - public function testUpdateSiteStrangeNameNoUrl() - { - $idsite = API::getInstance()->addSite("site1", "http://main.url"); - $newName = "test toto@{'786'}"; - - API::getInstance()->updateSite($idsite, $newName); - - $site = API::getInstance()->getSiteFromId($idsite); - - $this->assertEquals($newName, $site['name']); - // url didn't change because parameter url NULL in updateSite - $this->assertEquals("http://main.url", $site['main_url']); - } - - /** - * several urls => both main and alias are updated - * also test the update of group field - * - * @group Plugins - */ - public function testUpdateSiteSeveralUrlsAndGroup() - { - $urls = array("http://piwiknew.com", - "http://piwiknew.net", - "http://piwiknew.org", - "http://piwiknew.fr"); - - $group = 'GROUP Before'; - $idsite = API::getInstance()->addSite("site1", $urls, $ecommerce = 1, - $siteSearch = 1, $searchKeywordParameters = null, $searchCategoryParameters = null, - $excludedIps = null, $excludedQueryParameters = null, $timezone = null, $currency = null, $group, $startDate = '2011-01-01'); - - $websites = API::getInstance()->getSitesFromGroup($group); - $this->assertEquals(1, count($websites)); - - $newurls = array("http://piwiknew2.com", - "http://piwiknew2.net", - "http://piwiknew2.org", - "http://piwiknew2.fr"); - - $groupAfter = ' GROUP After'; - API::getInstance()->updateSite($idsite, "test toto@{}", $newurls, $ecommerce = 0, - $siteSearch = 1, $searchKeywordParameters = null, $searchCategoryParameters = null, - $excludedIps = null, $excludedQueryParameters = null, $timezone = null, $currency = null, $groupAfter); - - // no result for the group before update - $websites = API::getInstance()->getSitesFromGroup($group); - $this->assertEquals(0, count($websites)); - - // Testing that the group was updated properly (and testing that the group value is trimmed before inserted/searched) - $websites = API::getInstance()->getSitesFromGroup($groupAfter . ' '); - $this->assertEquals(1, count($websites)); - $this->assertEquals('2011-01-01', date('Y-m-d', strtotime($websites[0]['ts_created']))); - - // Test fetch website groups - $expectedGroups = array(trim($groupAfter)); - $fetched = API::getInstance()->getSitesGroups(); - $this->assertEquals($expectedGroups, $fetched); - - $allUrls = API::getInstance()->getSiteUrlsFromId($idsite); - sort($allUrls); - sort($newurls); - $this->assertEquals($newurls, $allUrls); - } - - /** - * @group Plugins - */ - public function testGetSitesGroups() - { - $groups = array('group1', ' group1 ', '', 'group2'); - $expectedGroups = array('group1', '', 'group2'); - foreach ($groups as $group) { - API::getInstance()->addSite("test toto@{}", 'http://example.org', $ecommerce = 1, $siteSearch = null, $searchKeywordParameters = null, $searchCategoryParameters = null, $excludedIps = null, $excludedQueryParameters = null, $timezone = null, $currency = null, $group); - } - - $this->assertEquals($expectedGroups, API::getInstance()->getSitesGroups()); - } - - public function getInvalidTimezoneData() - { - return array( - array('UTC+15'), - array('Paris'), - ); - } - - /** - * - * @dataProvider getInvalidTimezoneData - * @group Plugins - */ - public function testAddSitesInvalidTimezone($timezone) - { - try { - API::getInstance()->addSite("site1", array('http://example.org'), $ecommerce = 0, - $siteSearch = 1, $searchKeywordParameters = null, $searchCategoryParameters = null, $ip = '', $params = '', $timezone); - } catch (Exception $e) { - return; - } - $this->fail('Expected exception not raised'); - } - - /** - * @group Plugins - */ - public function testAddSitesInvalidCurrency() - { - try { - $invalidCurrency = '€'; - API::getInstance()->addSite("site1", array('http://example.org'), $ecommerce = 0, - $siteSearch = 1, $searchKeywordParameters = null, $searchCategoryParameters = null, '', 'UTC', $invalidCurrency); - } catch (Exception $e) { - return; - } - $this->fail('Expected exception not raised'); - } - - /** - * @group Plugins - */ - public function testSetDefaultTimezoneAndCurrencyAndExcludedQueryParametersAndExcludedIps() - { - // test that they return default values - $defaultTimezone = API::getInstance()->getDefaultTimezone(); - $this->assertEquals('UTC', $defaultTimezone); - $defaultCurrency = API::getInstance()->getDefaultCurrency(); - $this->assertEquals('USD', $defaultCurrency); - $excludedIps = API::getInstance()->getExcludedIpsGlobal(); - $this->assertEquals('', $excludedIps); - $excludedQueryParameters = API::getInstance()->getExcludedQueryParametersGlobal(); - $this->assertEquals('', $excludedQueryParameters); - - // test that when not specified, defaults are set as expected - $idsite = API::getInstance()->addSite("site1", array('http://example.org')); - $site = new Site($idsite); - $this->assertEquals('UTC', $site->getTimezone()); - $this->assertEquals('USD', $site->getCurrency()); - $this->assertEquals('', $site->getExcludedQueryParameters()); - $this->assertEquals('', $site->getExcludedIps()); - $this->assertEquals(false, $site->isEcommerceEnabled()); - - // set the global timezone and get it - $newDefaultTimezone = 'UTC+5.5'; - API::getInstance()->setDefaultTimezone($newDefaultTimezone); - $defaultTimezone = API::getInstance()->getDefaultTimezone(); - $this->assertEquals($newDefaultTimezone, $defaultTimezone); - - // set the default currency and get it - $newDefaultCurrency = 'EUR'; - API::getInstance()->setDefaultCurrency($newDefaultCurrency); - $defaultCurrency = API::getInstance()->getDefaultCurrency(); - $this->assertEquals($newDefaultCurrency, $defaultCurrency); - - // set the global IPs to exclude and get it - $newGlobalExcludedIps = '1.1.1.*,1.1.*.*,150.1.1.1'; - API::getInstance()->setGlobalExcludedIps($newGlobalExcludedIps); - $globalExcludedIps = API::getInstance()->getExcludedIpsGlobal(); - $this->assertEquals($newGlobalExcludedIps, $globalExcludedIps); - - // set the global URL query params to exclude and get it - $newGlobalExcludedQueryParameters = 'PHPSESSID,blabla, TesT'; - // removed the space - $expectedGlobalExcludedQueryParameters = 'PHPSESSID,blabla,TesT'; - API::getInstance()->setGlobalExcludedQueryParameters($newGlobalExcludedQueryParameters); - $globalExcludedQueryParameters = API::getInstance()->getExcludedQueryParametersGlobal(); - $this->assertEquals($expectedGlobalExcludedQueryParameters, $globalExcludedQueryParameters); - - // create a website and check that default currency and default timezone are set - // however, excluded IPs and excluded query Params are not returned - $idsite = API::getInstance()->addSite("site1", array('http://example.org'), $ecommerce = 0, - $siteSearch = 0, $searchKeywordParameters = 'test1,test2', $searchCategoryParameters = 'test2,test1', - '', '', $newDefaultTimezone); - $site = new Site($idsite); - $this->assertEquals($newDefaultTimezone, $site->getTimezone()); - $this->assertEquals(date('Y-m-d'), $site->getCreationDate()->toString()); - $this->assertEquals($newDefaultCurrency, $site->getCurrency()); - $this->assertEquals('', $site->getExcludedIps()); - $this->assertEquals('', $site->getExcludedQueryParameters()); - $this->assertEquals('test1,test2', $site->getSearchKeywordParameters()); - $this->assertEquals('test2,test1', $site->getSearchCategoryParameters()); - $this->assertFalse($site->isSiteSearchEnabled()); - $this->assertFalse(Site::isSiteSearchEnabledFor($idsite)); - $this->assertFalse($site->isEcommerceEnabled()); - $this->assertFalse(Site::isEcommerceEnabledFor($idsite)); - } - - /** - * @group Plugins - */ - public function testGetSitesIdFromSiteUrlSuperUser() - { - API::getInstance()->addSite("site1", array("http://piwik.net", "http://piwik.com")); - API::getInstance()->addSite("site2", array("http://piwik.com", "http://piwik.net")); - API::getInstance()->addSite("site3", array("http://piwik.com", "http://piwik.org")); - - $idsites = API::getInstance()->getSitesIdFromSiteUrl('http://piwik.org'); - $this->assertTrue(count($idsites) == 1); - - $idsites = API::getInstance()->getSitesIdFromSiteUrl('http://www.piwik.org'); - $this->assertTrue(count($idsites) == 1); - - $idsites = API::getInstance()->getSitesIdFromSiteUrl('http://piwik.net'); - $this->assertTrue(count($idsites) == 2); - - $idsites = API::getInstance()->getSitesIdFromSiteUrl('http://piwik.com'); - $this->assertTrue(count($idsites) == 3); - } - - /** - * @group Plugins - */ - public function testGetSitesIdFromSiteUrlUser() - { - API::getInstance()->addSite("site1", array("http://www.piwik.net", "http://piwik.com")); - API::getInstance()->addSite("site2", array("http://piwik.com", "http://piwik.net")); - API::getInstance()->addSite("site3", array("http://piwik.com", "http://piwik.org")); - - $saveAccess = Access::getInstance(); - - APIUsersManager::getInstance()->addUser("user1", "geqgegagae", "tegst@tesgt.com", "alias"); - APIUsersManager::getInstance()->setUserAccess("user1", "view", array(1)); - - APIUsersManager::getInstance()->addUser("user2", "geqgegagae", "tegst2@tesgt.com", "alias"); - APIUsersManager::getInstance()->setUserAccess("user2", "view", array(1)); - APIUsersManager::getInstance()->setUserAccess("user2", "admin", array(3)); - - APIUsersManager::getInstance()->addUser("user3", "geqgegagae", "tegst3@tesgt.com", "alias"); - APIUsersManager::getInstance()->setUserAccess("user3", "view", array(1, 2)); - APIUsersManager::getInstance()->setUserAccess("user3", "admin", array(3)); - - $pseudoMockAccess = new FakeAccess; - FakeAccess::$superUser = false; - FakeAccess::$identity = 'user1'; - FakeAccess::setIdSitesView(array(1)); - FakeAccess::setIdSitesAdmin(array()); - Access::setSingletonInstance($pseudoMockAccess); - $idsites = API::getInstance()->getSitesIdFromSiteUrl('http://piwik.com'); - $this->assertEquals(1, count($idsites)); - - // testing URL normalization - $idsites = API::getInstance()->getSitesIdFromSiteUrl('http://www.piwik.com'); - $this->assertEquals(1, count($idsites)); - $idsites = API::getInstance()->getSitesIdFromSiteUrl('http://piwik.net'); - $this->assertEquals(1, count($idsites)); - - $pseudoMockAccess = new FakeAccess; - FakeAccess::$superUser = false; - FakeAccess::$identity = 'user2'; - FakeAccess::setIdSitesView(array(1)); - FakeAccess::setIdSitesAdmin(array(3)); - Access::setSingletonInstance($pseudoMockAccess); - $idsites = API::getInstance()->getSitesIdFromSiteUrl('http://piwik.com'); - $this->assertEquals(2, count($idsites)); - - $pseudoMockAccess = new FakeAccess; - FakeAccess::$superUser = false; - FakeAccess::$identity = 'user3'; - FakeAccess::setIdSitesView(array(1, 2)); - FakeAccess::setIdSitesAdmin(array(3)); - Access::setSingletonInstance($pseudoMockAccess); - $idsites = API::getInstance()->getSitesIdFromSiteUrl('http://piwik.com'); - $this->assertEquals(3, count($idsites)); - - Access::setSingletonInstance($saveAccess); - } - - /** - * @group Plugins - */ - public function testGetSitesFromTimezones() - { - API::getInstance()->addSite("site3", array("http://piwik.org"), null, $siteSearch = 1, $searchKeywordParameters = null, $searchCategoryParameters = null, null, null, 'UTC'); - $idsite2 = API::getInstance()->addSite("site3", array("http://piwik.org"), null, $siteSearch = 1, $searchKeywordParameters = null, $searchCategoryParameters = null, null, null, 'Pacific/Auckland'); - $idsite3 = API::getInstance()->addSite("site3", array("http://piwik.org"), null, $siteSearch = 1, $searchKeywordParameters = null, $searchCategoryParameters = null, null, null, 'Pacific/Auckland'); - $idsite4 = API::getInstance()->addSite("site3", array("http://piwik.org"), null, $siteSearch = 1, $searchKeywordParameters = null, $searchCategoryParameters = null, null, null, 'UTC+10'); - $result = API::getInstance()->getSitesIdFromTimezones(array('UTC+10', 'Pacific/Auckland')); - $this->assertEquals(array($idsite2, $idsite3, $idsite4), $result); - } -} diff --git a/plugins/UserCountry/tests/Unit/UserCountryTest.php b/plugins/UserCountry/tests/Unit/UserCountryTest.php new file mode 100644 index 0000000000..540be65d70 --- /dev/null +++ b/plugins/UserCountry/tests/Unit/UserCountryTest.php @@ -0,0 +1,185 @@ +assertEquals(basename($flag), "us.png"); + } + + /** + * @group Plugins + */ + public function testGetFlagFromInvalidCode() + { + $flag = \Piwik\Plugins\UserCountry\getFlagFromCode("foo"); + $this->assertEquals(basename($flag), "xx.png"); + } + + /** + * @group Plugins + */ + public function testFlagsAndContinents() + { + require PIWIK_PATH_TEST_TO_ROOT . '/core/DataFiles/Countries.php'; + + $continents = $GLOBALS['Piwik_ContinentList']; + $countries = array_merge($GLOBALS['Piwik_CountryList'], $GLOBALS['Piwik_CountryList_Extras']); + + // Get list of existing flag icons + $flags = scandir(PIWIK_PATH_TEST_TO_ROOT . '/plugins/UserCountry/images/flags/'); + + // Get list of countries + foreach ($countries as $country => $continent) { + // test continent + $this->assertContains($continent, $continents); + + // test flag + $this->assertContains($country . '.png', $flags); + } + + foreach ($flags as $filename) { + if ($filename == '.' || $filename == '..') { + continue; + } + + $country = substr($filename, 0, strpos($filename, '.png')); + + // test country + $this->assertArrayHasKey($country, $countries, $filename); + } + } + + /** + * Test that redundant checks work. + * + * @group Plugins + */ + public function testGeoIpUpdaterRedundantChecks() + { + GeoIp::$geoIPDatabaseDir = 'tests/lib/geoip-files'; + LocationProvider::$providers = null; + + // create empty ISP & Org files + $this->createEmptyISPOrgFiles(); + + // run redundant checks + $updater = new Piwik_UserCountry_GeoIPAutoUpdater_publictest(); + $updater->performRedundantDbChecks(); + + // check that files are renamed correctly + $this->checkBrokenGeoIPState(); + + // create empty files again & run checks again + $this->createEmptyISPOrgFiles(); + $updater->performRedundantDbChecks(); + + // check that w/ broken files already there, redundant checks still work correctly + $this->checkBrokenGeoIPState(); + } + + /** + * @group Plugins + * + * @dataProvider getInvalidGeoIpUrlsToTest + */ + public function testGeoIpDownloadInvalidUrl($url) + { + $updater = new Piwik_UserCountry_GeoIPAutoUpdater_publictest(); + try { + $updater->downloadFile('loc', $url); + $this->fail("Downloading invalid url succeeded!"); + } catch (Exception $ex) { + $this->assertEquals("UserCountry_UnsupportedArchiveType", $ex->getMessage()); + } + } + + public function getInvalidGeoIpUrlsToTest() + { + return array(array("http://localhost/tests/resources/geoip.tar"), + array("http://localhost/tests/resources/geoip.tar.bz2"), + array("http://localhost/tests/resources/geoip.dat")); + } + + public function setUp() + { + // empty + } + + public function tearDown() + { + $geoIpDirPath = PIWIK_INCLUDE_PATH . '/tests/lib/geoip-files'; + $filesToRemove = array('GeoIPISP.dat.broken', 'GeoIPOrg.dat.broken', 'GeoIPISP.dat', 'GeoIPOrg.dat'); + + foreach ($filesToRemove as $name) { + $path = $geoIpDirPath . '/' . $name; + if (file_exists($path)) { + unlink($path); + } + } + } + + private function createEmptyISPOrgFiles() + { + $geoIpDir = PIWIK_INCLUDE_PATH . '/tests/lib/geoip-files'; + + $fd = fopen($geoIpDir . '/GeoIPISP.dat', 'w'); + fclose($fd); + + $fd = fopen($geoIpDir . '/GeoIPOrg.dat', 'w'); + fclose($fd); + } + + private function checkBrokenGeoIPState() + { + $geoIpDir = PIWIK_INCLUDE_PATH . '/tests/lib/geoip-files'; + + $this->assertFalse(file_exists($geoIpDir . '/GeoIPCity.dat.broken')); + + $this->assertFalse(file_exists($geoIpDir . '/GeoIPISP.dat')); + $this->assertTrue(file_exists($geoIpDir . '/GeoIPISP.dat.broken')); + + $this->assertFalse(file_exists($geoIpDir . '/GeoIPOrg.dat')); + $this->assertTrue(file_exists($geoIpDir . '/GeoIPOrg.dat.broken')); + } +} + +class Piwik_UserCountry_GeoIPAutoUpdater_publictest extends GeoIPAutoUpdater +{ + public function __construct() + { + // empty + } + + public function performRedundantDbChecks() + { + parent::performRedundantDbChecks(); + } + + public function downloadFile($type, $url) + { + parent::downloadFile($type, $url); + } +} diff --git a/plugins/UserCountry/tests/UserCountryTest.php b/plugins/UserCountry/tests/UserCountryTest.php deleted file mode 100644 index 4dc6b9b497..0000000000 --- a/plugins/UserCountry/tests/UserCountryTest.php +++ /dev/null @@ -1,185 +0,0 @@ -assertEquals(basename($flag), "us.png"); - } - - /** - * @group Plugins - */ - public function testGetFlagFromInvalidCode() - { - $flag = \Piwik\Plugins\UserCountry\getFlagFromCode("foo"); - $this->assertEquals(basename($flag), "xx.png"); - } - - /** - * @group Plugins - */ - public function testFlagsAndContinents() - { - require PIWIK_PATH_TEST_TO_ROOT . '/core/DataFiles/Countries.php'; - - $continents = $GLOBALS['Piwik_ContinentList']; - $countries = array_merge($GLOBALS['Piwik_CountryList'], $GLOBALS['Piwik_CountryList_Extras']); - - // Get list of existing flag icons - $flags = scandir(PIWIK_PATH_TEST_TO_ROOT . '/plugins/UserCountry/images/flags/'); - - // Get list of countries - foreach ($countries as $country => $continent) { - // test continent - $this->assertContains($continent, $continents); - - // test flag - $this->assertContains($country . '.png', $flags); - } - - foreach ($flags as $filename) { - if ($filename == '.' || $filename == '..') { - continue; - } - - $country = substr($filename, 0, strpos($filename, '.png')); - - // test country - $this->assertArrayHasKey($country, $countries, $filename); - } - } - - /** - * Test that redundant checks work. - * - * @group Plugins - */ - public function testGeoIpUpdaterRedundantChecks() - { - GeoIp::$geoIPDatabaseDir = 'tests/lib/geoip-files'; - LocationProvider::$providers = null; - - // create empty ISP & Org files - $this->createEmptyISPOrgFiles(); - - // run redundant checks - $updater = new Piwik_UserCountry_GeoIPAutoUpdater_publictest(); - $updater->performRedundantDbChecks(); - - // check that files are renamed correctly - $this->checkBrokenGeoIPState(); - - // create empty files again & run checks again - $this->createEmptyISPOrgFiles(); - $updater->performRedundantDbChecks(); - - // check that w/ broken files already there, redundant checks still work correctly - $this->checkBrokenGeoIPState(); - } - - /** - * @group Plugins - * - * @dataProvider getInvalidGeoIpUrlsToTest - */ - public function testGeoIpDownloadInvalidUrl($url) - { - $updater = new Piwik_UserCountry_GeoIPAutoUpdater_publictest(); - try { - $updater->downloadFile('loc', $url); - $this->fail("Downloading invalid url succeeded!"); - } catch (Exception $ex) { - $this->assertEquals("UserCountry_UnsupportedArchiveType", $ex->getMessage()); - } - } - - public function getInvalidGeoIpUrlsToTest() - { - return array(array("http://localhost/tests/resources/geoip.tar"), - array("http://localhost/tests/resources/geoip.tar.bz2"), - array("http://localhost/tests/resources/geoip.dat")); - } - - public function setUp() - { - // empty - } - - public function tearDown() - { - $geoIpDirPath = PIWIK_INCLUDE_PATH . '/tests/lib/geoip-files'; - $filesToRemove = array('GeoIPISP.dat.broken', 'GeoIPOrg.dat.broken', 'GeoIPISP.dat', 'GeoIPOrg.dat'); - - foreach ($filesToRemove as $name) { - $path = $geoIpDirPath . '/' . $name; - if (file_exists($path)) { - unlink($path); - } - } - } - - private function createEmptyISPOrgFiles() - { - $geoIpDir = PIWIK_INCLUDE_PATH . '/tests/lib/geoip-files'; - - $fd = fopen($geoIpDir . '/GeoIPISP.dat', 'w'); - fclose($fd); - - $fd = fopen($geoIpDir . '/GeoIPOrg.dat', 'w'); - fclose($fd); - } - - private function checkBrokenGeoIPState() - { - $geoIpDir = PIWIK_INCLUDE_PATH . '/tests/lib/geoip-files'; - - $this->assertFalse(file_exists($geoIpDir . '/GeoIPCity.dat.broken')); - - $this->assertFalse(file_exists($geoIpDir . '/GeoIPISP.dat')); - $this->assertTrue(file_exists($geoIpDir . '/GeoIPISP.dat.broken')); - - $this->assertFalse(file_exists($geoIpDir . '/GeoIPOrg.dat')); - $this->assertTrue(file_exists($geoIpDir . '/GeoIPOrg.dat.broken')); - } -} - -class Piwik_UserCountry_GeoIPAutoUpdater_publictest extends GeoIPAutoUpdater -{ - public function __construct() - { - // empty - } - - public function performRedundantDbChecks() - { - parent::performRedundantDbChecks(); - } - - public function downloadFile($type, $url) - { - parent::downloadFile($type, $url); - } -} diff --git a/plugins/UserSettings/.gitignore b/plugins/UserSettings/.gitignore new file mode 100644 index 0000000000..c8c9480010 --- /dev/null +++ b/plugins/UserSettings/.gitignore @@ -0,0 +1 @@ +tests/System/processed/*xml \ No newline at end of file diff --git a/plugins/UserSettings/tests/GetLanguageSystemTest.php b/plugins/UserSettings/tests/GetLanguageSystemTest.php deleted file mode 100644 index e757becb14..0000000000 --- a/plugins/UserSettings/tests/GetLanguageSystemTest.php +++ /dev/null @@ -1,74 +0,0 @@ -runApiTests($api, $params); - } - - /** - * @return array - */ - public function getApiForTesting() - { - $apiToCall = array( - "UserSettings.getLanguage", - "UserSettings.getLanguageCode" - ); - - $apiToTest = array(); - - $apiToTest[] = array( - $apiToCall, - array( - 'idSite' => self::$fixture->idSite, - 'date' => self::$fixture->dateTime, - 'periods' => array('day') - ) - ); - - return $apiToTest; - } - - - public static function getPathToTestDirectory() - { - return dirname(__FILE__); - } - -} - -GetLanguageSystemTest::$fixture = new LanguageFixture(); \ No newline at end of file diff --git a/plugins/UserSettings/tests/System/GetLanguageSystemTest.php b/plugins/UserSettings/tests/System/GetLanguageSystemTest.php new file mode 100644 index 0000000000..cb87f88d1f --- /dev/null +++ b/plugins/UserSettings/tests/System/GetLanguageSystemTest.php @@ -0,0 +1,74 @@ +runApiTests($api, $params); + } + + /** + * @return array + */ + public function getApiForTesting() + { + $apiToCall = array( + "UserSettings.getLanguage", + "UserSettings.getLanguageCode" + ); + + $apiToTest = array(); + + $apiToTest[] = array( + $apiToCall, + array( + 'idSite' => self::$fixture->idSite, + 'date' => self::$fixture->dateTime, + 'periods' => array('day') + ) + ); + + return $apiToTest; + } + + + public static function getPathToTestDirectory() + { + return dirname(__FILE__); + } + +} + +GetLanguageSystemTest::$fixture = new LanguageFixture(); \ No newline at end of file diff --git a/plugins/UserSettings/tests/System/expected/test___UserSettings.getLanguageCode_day.xml b/plugins/UserSettings/tests/System/expected/test___UserSettings.getLanguageCode_day.xml new file mode 100644 index 0000000000..689e3d7d37 --- /dev/null +++ b/plugins/UserSettings/tests/System/expected/test___UserSettings.getLanguageCode_day.xml @@ -0,0 +1,157 @@ + + + + + 2 + 3 + 3 + 0 + 1 + 0 + 3 + 0 + + + + 1 + 2 + 2 + 0 + 1 + 0 + 2 + 0 + + + + 1 + 2 + 2 + 0 + 1 + 0 + 2 + 0 + + + + 1 + 1 + 1 + 0 + 1 + 0 + 1 + 0 + + + + 1 + 1 + 1 + 0 + 1 + 0 + 1 + 0 + + + + 1 + 1 + 1 + 0 + 1 + 0 + 1 + 0 + + + + 1 + 1 + 1 + 0 + 1 + 0 + 1 + 0 + + + + 1 + 1 + 1 + 0 + 1 + 0 + 1 + 0 + + + + 1 + 1 + 1 + 0 + 1 + 0 + 1 + 0 + + + + 1 + 1 + 1 + 0 + 1 + 0 + 1 + 0 + + + + 1 + 1 + 1 + 0 + 1 + 0 + 1 + 0 + + + + 1 + 1 + 1 + 0 + 1 + 0 + 1 + 0 + + + + 1 + 1 + 1 + 0 + 1 + 0 + 1 + 0 + + + + 1 + 1 + 1 + 0 + 1 + 0 + 1 + 0 + + \ No newline at end of file diff --git a/plugins/UserSettings/tests/System/expected/test___UserSettings.getLanguage_day.xml b/plugins/UserSettings/tests/System/expected/test___UserSettings.getLanguage_day.xml new file mode 100644 index 0000000000..6bb328c660 --- /dev/null +++ b/plugins/UserSettings/tests/System/expected/test___UserSettings.getLanguage_day.xml @@ -0,0 +1,135 @@ + + + + + 2 + 3 + 3 + 0 + 1 + 0 + 3 + 0 + + + + 1 + 2 + 2 + 0 + 1 + 0 + 2 + 0 + + + + 3 + 4 + 4 + 0 + 1 + 0 + 4 + 0 + + + + 1 + 1 + 1 + 0 + 1 + 0 + 1 + 0 + + + + 1 + 1 + 1 + 0 + 1 + 0 + 1 + 0 + + + + 1 + 1 + 1 + 0 + 1 + 0 + 1 + 0 + + + + 1 + 1 + 1 + 0 + 1 + 0 + 1 + 0 + + + + 1 + 1 + 1 + 0 + 1 + 0 + 1 + 0 + + + + 1 + 1 + 1 + 0 + 1 + 0 + 1 + 0 + + + + 1 + 1 + 1 + 0 + 1 + 0 + 1 + 0 + + + + 1 + 1 + 1 + 0 + 1 + 0 + 1 + 0 + + + + 1 + 1 + 1 + 0 + 1 + 0 + 1 + 0 + + \ No newline at end of file diff --git a/plugins/UserSettings/tests/System/processed/.gitkeep b/plugins/UserSettings/tests/System/processed/.gitkeep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/plugins/UserSettings/tests/System/processed/test___UserSettings.getLanguageCode_day.xml b/plugins/UserSettings/tests/System/processed/test___UserSettings.getLanguageCode_day.xml new file mode 100644 index 0000000000..689e3d7d37 --- /dev/null +++ b/plugins/UserSettings/tests/System/processed/test___UserSettings.getLanguageCode_day.xml @@ -0,0 +1,157 @@ + + + + + 2 + 3 + 3 + 0 + 1 + 0 + 3 + 0 + + + + 1 + 2 + 2 + 0 + 1 + 0 + 2 + 0 + + + + 1 + 2 + 2 + 0 + 1 + 0 + 2 + 0 + + + + 1 + 1 + 1 + 0 + 1 + 0 + 1 + 0 + + + + 1 + 1 + 1 + 0 + 1 + 0 + 1 + 0 + + + + 1 + 1 + 1 + 0 + 1 + 0 + 1 + 0 + + + + 1 + 1 + 1 + 0 + 1 + 0 + 1 + 0 + + + + 1 + 1 + 1 + 0 + 1 + 0 + 1 + 0 + + + + 1 + 1 + 1 + 0 + 1 + 0 + 1 + 0 + + + + 1 + 1 + 1 + 0 + 1 + 0 + 1 + 0 + + + + 1 + 1 + 1 + 0 + 1 + 0 + 1 + 0 + + + + 1 + 1 + 1 + 0 + 1 + 0 + 1 + 0 + + + + 1 + 1 + 1 + 0 + 1 + 0 + 1 + 0 + + + + 1 + 1 + 1 + 0 + 1 + 0 + 1 + 0 + + \ No newline at end of file diff --git a/plugins/UserSettings/tests/System/processed/test___UserSettings.getLanguage_day.xml b/plugins/UserSettings/tests/System/processed/test___UserSettings.getLanguage_day.xml new file mode 100644 index 0000000000..6bb328c660 --- /dev/null +++ b/plugins/UserSettings/tests/System/processed/test___UserSettings.getLanguage_day.xml @@ -0,0 +1,135 @@ + + + + + 2 + 3 + 3 + 0 + 1 + 0 + 3 + 0 + + + + 1 + 2 + 2 + 0 + 1 + 0 + 2 + 0 + + + + 3 + 4 + 4 + 0 + 1 + 0 + 4 + 0 + + + + 1 + 1 + 1 + 0 + 1 + 0 + 1 + 0 + + + + 1 + 1 + 1 + 0 + 1 + 0 + 1 + 0 + + + + 1 + 1 + 1 + 0 + 1 + 0 + 1 + 0 + + + + 1 + 1 + 1 + 0 + 1 + 0 + 1 + 0 + + + + 1 + 1 + 1 + 0 + 1 + 0 + 1 + 0 + + + + 1 + 1 + 1 + 0 + 1 + 0 + 1 + 0 + + + + 1 + 1 + 1 + 0 + 1 + 0 + 1 + 0 + + + + 1 + 1 + 1 + 0 + 1 + 0 + 1 + 0 + + + + 1 + 1 + 1 + 0 + 1 + 0 + 1 + 0 + + \ No newline at end of file diff --git a/plugins/UserSettings/tests/Unit/UserSettingsTest.php b/plugins/UserSettings/tests/Unit/UserSettingsTest.php new file mode 100644 index 0000000000..408420ed6f --- /dev/null +++ b/plugins/UserSettings/tests/Unit/UserSettingsTest.php @@ -0,0 +1,1036 @@ +assertFalse($expected[0]); + else { + $family = \Piwik\Plugins\UserSettings\getBrowserFamily($res['id']); + $this->assertEquals($expected[0][0], $res['id']); + $this->assertEquals($expected[0][1], $res['name']); + $this->assertEquals($expected[0][2], $res['short_name']); + $this->assertEquals($expected[0][3], $res['version']); + $this->assertEquals($expected[0][4], $res['major_number']); + $this->assertEquals($expected[0][5], $res['minor_number']); + $this->assertEquals($expected[0][6], $family); + } + } + + /** + * Test getOperatingSystem() + * + * @dataProvider getUserAgents + * @group Plugins + */ + public function testGetOperatingSystem($userAgent, $expected) + { + $res = UserAgentParser::getOperatingSystem($userAgent); + + $this->assertEquals($expected[1][0], $res['id']); + $this->assertEquals($expected[1][1], $res['name']); + $this->assertEquals($expected[1][2], $res['short_name']); + } +} diff --git a/plugins/UserSettings/tests/UserSettingsTest.php b/plugins/UserSettings/tests/UserSettingsTest.php deleted file mode 100644 index 95188a15e4..0000000000 --- a/plugins/UserSettings/tests/UserSettingsTest.php +++ /dev/null @@ -1,1036 +0,0 @@ -assertFalse($expected[0]); - else { - $family = \Piwik\Plugins\UserSettings\getBrowserFamily($res['id']); - $this->assertEquals($expected[0][0], $res['id']); - $this->assertEquals($expected[0][1], $res['name']); - $this->assertEquals($expected[0][2], $res['short_name']); - $this->assertEquals($expected[0][3], $res['version']); - $this->assertEquals($expected[0][4], $res['major_number']); - $this->assertEquals($expected[0][5], $res['minor_number']); - $this->assertEquals($expected[0][6], $family); - } - } - - /** - * Test getOperatingSystem() - * - * @dataProvider getUserAgents - * @group Plugins - */ - public function testGetOperatingSystem($userAgent, $expected) - { - $res = UserAgentParser::getOperatingSystem($userAgent); - - $this->assertEquals($expected[1][0], $res['id']); - $this->assertEquals($expected[1][1], $res['name']); - $this->assertEquals($expected[1][2], $res['short_name']); - } -} diff --git a/plugins/UserSettings/tests/expected/test___UserSettings.getLanguageCode_day.xml b/plugins/UserSettings/tests/expected/test___UserSettings.getLanguageCode_day.xml deleted file mode 100644 index 689e3d7d37..0000000000 --- a/plugins/UserSettings/tests/expected/test___UserSettings.getLanguageCode_day.xml +++ /dev/null @@ -1,157 +0,0 @@ - - - - - 2 - 3 - 3 - 0 - 1 - 0 - 3 - 0 - - - - 1 - 2 - 2 - 0 - 1 - 0 - 2 - 0 - - - - 1 - 2 - 2 - 0 - 1 - 0 - 2 - 0 - - - - 1 - 1 - 1 - 0 - 1 - 0 - 1 - 0 - - - - 1 - 1 - 1 - 0 - 1 - 0 - 1 - 0 - - - - 1 - 1 - 1 - 0 - 1 - 0 - 1 - 0 - - - - 1 - 1 - 1 - 0 - 1 - 0 - 1 - 0 - - - - 1 - 1 - 1 - 0 - 1 - 0 - 1 - 0 - - - - 1 - 1 - 1 - 0 - 1 - 0 - 1 - 0 - - - - 1 - 1 - 1 - 0 - 1 - 0 - 1 - 0 - - - - 1 - 1 - 1 - 0 - 1 - 0 - 1 - 0 - - - - 1 - 1 - 1 - 0 - 1 - 0 - 1 - 0 - - - - 1 - 1 - 1 - 0 - 1 - 0 - 1 - 0 - - - - 1 - 1 - 1 - 0 - 1 - 0 - 1 - 0 - - \ No newline at end of file diff --git a/plugins/UserSettings/tests/expected/test___UserSettings.getLanguage_day.xml b/plugins/UserSettings/tests/expected/test___UserSettings.getLanguage_day.xml deleted file mode 100644 index 6bb328c660..0000000000 --- a/plugins/UserSettings/tests/expected/test___UserSettings.getLanguage_day.xml +++ /dev/null @@ -1,135 +0,0 @@ - - - - - 2 - 3 - 3 - 0 - 1 - 0 - 3 - 0 - - - - 1 - 2 - 2 - 0 - 1 - 0 - 2 - 0 - - - - 3 - 4 - 4 - 0 - 1 - 0 - 4 - 0 - - - - 1 - 1 - 1 - 0 - 1 - 0 - 1 - 0 - - - - 1 - 1 - 1 - 0 - 1 - 0 - 1 - 0 - - - - 1 - 1 - 1 - 0 - 1 - 0 - 1 - 0 - - - - 1 - 1 - 1 - 0 - 1 - 0 - 1 - 0 - - - - 1 - 1 - 1 - 0 - 1 - 0 - 1 - 0 - - - - 1 - 1 - 1 - 0 - 1 - 0 - 1 - 0 - - - - 1 - 1 - 1 - 0 - 1 - 0 - 1 - 0 - - - - 1 - 1 - 1 - 0 - 1 - 0 - 1 - 0 - - - - 1 - 1 - 1 - 0 - 1 - 0 - 1 - 0 - - \ No newline at end of file diff --git a/plugins/UserSettings/tests/processed/.gitkeep b/plugins/UserSettings/tests/processed/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/plugins/UserSettings/tests/processed/test___UserSettings.getLanguageCode_day.xml b/plugins/UserSettings/tests/processed/test___UserSettings.getLanguageCode_day.xml deleted file mode 100644 index 689e3d7d37..0000000000 --- a/plugins/UserSettings/tests/processed/test___UserSettings.getLanguageCode_day.xml +++ /dev/null @@ -1,157 +0,0 @@ - - - - - 2 - 3 - 3 - 0 - 1 - 0 - 3 - 0 - - - - 1 - 2 - 2 - 0 - 1 - 0 - 2 - 0 - - - - 1 - 2 - 2 - 0 - 1 - 0 - 2 - 0 - - - - 1 - 1 - 1 - 0 - 1 - 0 - 1 - 0 - - - - 1 - 1 - 1 - 0 - 1 - 0 - 1 - 0 - - - - 1 - 1 - 1 - 0 - 1 - 0 - 1 - 0 - - - - 1 - 1 - 1 - 0 - 1 - 0 - 1 - 0 - - - - 1 - 1 - 1 - 0 - 1 - 0 - 1 - 0 - - - - 1 - 1 - 1 - 0 - 1 - 0 - 1 - 0 - - - - 1 - 1 - 1 - 0 - 1 - 0 - 1 - 0 - - - - 1 - 1 - 1 - 0 - 1 - 0 - 1 - 0 - - - - 1 - 1 - 1 - 0 - 1 - 0 - 1 - 0 - - - - 1 - 1 - 1 - 0 - 1 - 0 - 1 - 0 - - - - 1 - 1 - 1 - 0 - 1 - 0 - 1 - 0 - - \ No newline at end of file diff --git a/plugins/UserSettings/tests/processed/test___UserSettings.getLanguage_day.xml b/plugins/UserSettings/tests/processed/test___UserSettings.getLanguage_day.xml deleted file mode 100644 index 6bb328c660..0000000000 --- a/plugins/UserSettings/tests/processed/test___UserSettings.getLanguage_day.xml +++ /dev/null @@ -1,135 +0,0 @@ - - - - - 2 - 3 - 3 - 0 - 1 - 0 - 3 - 0 - - - - 1 - 2 - 2 - 0 - 1 - 0 - 2 - 0 - - - - 3 - 4 - 4 - 0 - 1 - 0 - 4 - 0 - - - - 1 - 1 - 1 - 0 - 1 - 0 - 1 - 0 - - - - 1 - 1 - 1 - 0 - 1 - 0 - 1 - 0 - - - - 1 - 1 - 1 - 0 - 1 - 0 - 1 - 0 - - - - 1 - 1 - 1 - 0 - 1 - 0 - 1 - 0 - - - - 1 - 1 - 1 - 0 - 1 - 0 - 1 - 0 - - - - 1 - 1 - 1 - 0 - 1 - 0 - 1 - 0 - - - - 1 - 1 - 1 - 0 - 1 - 0 - 1 - 0 - - - - 1 - 1 - 1 - 0 - 1 - 0 - 1 - 0 - - - - 1 - 1 - 1 - 0 - 1 - 0 - 1 - 0 - - \ No newline at end of file diff --git a/plugins/UsersManager/tests/APITest.php b/plugins/UsersManager/tests/APITest.php deleted file mode 100644 index 3d77ee7a83..0000000000 --- a/plugins/UsersManager/tests/APITest.php +++ /dev/null @@ -1,71 +0,0 @@ -api = API::getInstance(); - - $pseudoMockAccess = new FakeAccess(); - FakeAccess::$superUser = true; - Access::setSingletonInstance($pseudoMockAccess); - - Fixture::createWebsite('2014-01-01 00:00:00'); - Fixture::createWebsite('2014-01-01 00:00:00'); - Fixture::createWebsite('2014-01-01 00:00:00'); - $this->api->addUser('userLogin', 'password', 'userlogin@password.de'); - } - - public function test_setUserAccess_ShouldTriggerRemoveSiteAccessEvent_IfAccessToAWebsiteIsRemoved() - { - $eventTriggered = false; - $self = $this; - Piwik::addAction('UsersManager.removeSiteAccess', function ($login, $idSites) use (&$eventTriggered, $self) { - $eventTriggered = true; - $self->assertEquals('userLogin', $login); - $self->assertEquals(array(1, 2), $idSites); - }); - - $this->api->setUserAccess('userLogin', 'noaccess', array(1, 2)); - - $this->assertTrue($eventTriggered, 'UsersManager.removeSiteAccess event was not triggered'); - } - - public function test_setUserAccess_ShouldNotTriggerRemoveSiteAccessEvent_IfAccessIsAdded() - { - $eventTriggered = false; - Piwik::addAction('UsersManager.removeSiteAccess', function () use (&$eventTriggered) { - $eventTriggered = true; - }); - - $this->api->setUserAccess('userLogin', 'admin', array(1, 2)); - - $this->assertFalse($eventTriggered, 'UsersManager.removeSiteAccess event was triggered but should not'); - } - -} diff --git a/plugins/UsersManager/tests/Integration/APITest.php b/plugins/UsersManager/tests/Integration/APITest.php new file mode 100644 index 0000000000..3d77ee7a83 --- /dev/null +++ b/plugins/UsersManager/tests/Integration/APITest.php @@ -0,0 +1,71 @@ +api = API::getInstance(); + + $pseudoMockAccess = new FakeAccess(); + FakeAccess::$superUser = true; + Access::setSingletonInstance($pseudoMockAccess); + + Fixture::createWebsite('2014-01-01 00:00:00'); + Fixture::createWebsite('2014-01-01 00:00:00'); + Fixture::createWebsite('2014-01-01 00:00:00'); + $this->api->addUser('userLogin', 'password', 'userlogin@password.de'); + } + + public function test_setUserAccess_ShouldTriggerRemoveSiteAccessEvent_IfAccessToAWebsiteIsRemoved() + { + $eventTriggered = false; + $self = $this; + Piwik::addAction('UsersManager.removeSiteAccess', function ($login, $idSites) use (&$eventTriggered, $self) { + $eventTriggered = true; + $self->assertEquals('userLogin', $login); + $self->assertEquals(array(1, 2), $idSites); + }); + + $this->api->setUserAccess('userLogin', 'noaccess', array(1, 2)); + + $this->assertTrue($eventTriggered, 'UsersManager.removeSiteAccess event was not triggered'); + } + + public function test_setUserAccess_ShouldNotTriggerRemoveSiteAccessEvent_IfAccessIsAdded() + { + $eventTriggered = false; + Piwik::addAction('UsersManager.removeSiteAccess', function () use (&$eventTriggered) { + $eventTriggered = true; + }); + + $this->api->setUserAccess('userLogin', 'admin', array(1, 2)); + + $this->assertFalse($eventTriggered, 'UsersManager.removeSiteAccess event was triggered but should not'); + } + +} diff --git a/plugins/UsersManager/tests/Integration/UserPreferencesTest.php b/plugins/UsersManager/tests/Integration/UserPreferencesTest.php new file mode 100644 index 0000000000..50658e46e2 --- /dev/null +++ b/plugins/UsersManager/tests/Integration/UserPreferencesTest.php @@ -0,0 +1,117 @@ +userPreferences = new UserPreferences(); + + $this->setSuperUser(); + } + + public function test_getDefaultReport_ShouldReturnFalseByDefault() + { + $this->assertEquals(false, $this->userPreferences->getDefaultReport()); + } + + public function test_getDefaultReport_ShouldReturnTheRawValueIfNotNumeric() + { + $this->setDefaultReport('MultiSites'); + $this->assertEquals('MultiSites', $this->userPreferences->getDefaultReport()); + } + + public function test_getDefaultReport_ShouldNotReturnSiteIdIfNoPermissionForSite() + { + $this->createSite(); + $this->setDefaultReport(1); + $this->setAnonymous(); + $this->assertEquals(false, $this->userPreferences->getDefaultReport()); + } + + public function test_getDefaultReport_ShouldReturnSiteIdIfPermissionForSite() + { + $this->createSite(); + $this->setDefaultReport(1); + $this->assertEquals(1, $this->userPreferences->getDefaultReport()); + } + + public function test_getDefaultWebsiteId_ShouldReturnFalseByDefault() + { + $this->assertEquals(false, $this->userPreferences->getDefaultWebsiteId()); + } + + public function test_getDefaultWebsiteId_ShouldReturnASiteIfOneExistsAndHasAccess() + { + $this->createSite(); + $this->assertEquals(1, $this->userPreferences->getDefaultWebsiteId()); + } + + public function test_getDefaultWebsiteId_ShouldReturnFalseIfASiteExistsButHasNoAccess() + { + $this->createSite(); + $this->setAnonymous(); + $this->assertEquals(false, $this->userPreferences->getDefaultWebsiteId()); + } + + public function test_getDefaultWebsiteId_ShouldReturnASiteEvenIfMultiSitesIsDefaultReport() + { + $this->setDefaultReport('MultiSites'); + $this->createSite(); + $this->assertEquals(1, $this->userPreferences->getDefaultWebsiteId()); + } + + private function setSuperUser() + { + $pseudoMockAccess = new FakeAccess(); + FakeAccess::$superUser = true; + Access::setSingletonInstance($pseudoMockAccess); + } + + private function setAnonymous() + { + $pseudoMockAccess = new FakeAccess(); + FakeAccess::$superUser = false; + Access::setSingletonInstance($pseudoMockAccess); + } + + private function createSite() + { + Fixture::createWebsite('2013-01-23 01:23:45'); + } + + private function setDefaultReport($defaultReport) + { + APIUsersManager::getInstance()->setUserPreference(Piwik::getCurrentUserLogin(), + APIUsersManager::PREFERENCE_DEFAULT_REPORT, + $defaultReport); + } + +} diff --git a/plugins/UsersManager/tests/Integration/UsersManagerTest.php b/plugins/UsersManager/tests/Integration/UsersManagerTest.php new file mode 100644 index 0000000000..115df6c0bb --- /dev/null +++ b/plugins/UsersManager/tests/Integration/UsersManagerTest.php @@ -0,0 +1,919 @@ +loadPlugin('UsersManager'); + \Piwik\Plugin\Manager::getInstance()->installLoadedPlugins(); + + // setup the access layer + $pseudoMockAccess = new FakeAccess; + FakeAccess::setIdSitesView(array(1, 2)); + FakeAccess::setIdSitesAdmin(array(3, 4)); + + //finally we set the user as a Super User by default + FakeAccess::$superUser = true; + FakeAccess::$superUserLogin = 'superusertest'; + Access::setSingletonInstance($pseudoMockAccess); + + $this->api = API::getInstance(); + $this->model = new Model(); + } + + private function _flatten($sitesAccess) + { + $result = array(); + + foreach ($sitesAccess as $siteAccess) { + $result[$siteAccess['site']] = $siteAccess['access']; + } + + return $result; + } + + private function _checkUserHasNotChanged($user, $newPassword, $newEmail = null, $newAlias = null) + { + if (is_null($newEmail)) { + $newEmail = $user['email']; + } + if (is_null($newAlias)) { + $newAlias = $user['alias']; + } + $userAfter = $this->api->getUser($user["login"]); + unset($userAfter['date_registered']); + + // we now compute what the token auth should be, it should always be a hash of the login and the current password + // if the password has changed then the token_auth has changed! + $user['token_auth'] = $this->api->getTokenAuth($user["login"], md5($newPassword)); + $user['password'] = md5($newPassword); + $user['email'] = $newEmail; + $user['alias'] = $newAlias; + $user['superuser_access'] = 0; + $this->assertEquals($user, $userAfter); + } + + /** + * bad password => exception# + * @expectedException \Exception + * @expectedExceptionMessage UsersManager_ExceptionInvalidPassword + */ + public function testUpdateUserBadpasswd() + { + $login = "login"; + $user = array('login' => $login, + 'password' => "geqgeagae", + 'email' => "test@test.com", + 'alias' => "alias"); + + $this->api->addUser($user['login'], $user['password'], $user['email'], $user['alias']); + + try { + $this->api->updateUser($login, "pas"); + } catch (Exception $expected) { + $this->_checkUserHasNotChanged($user, $user['password']); + throw $expected; + } + } + + /** + * Dataprovider + */ + public function getAddUserInvalidLoginData() + { + return array( + array(12, "password", "email@email.com", "alias"), // wrong login / integer => exception + array("gegag'ggea'", "password", "email@email.com", "alias"), // wrong login / too short => exception + array("gegag11gge&", "password", "email@email.com", "alias"), // wrong login / too long => exception + array("geg'ag11gge@", "password", "email@email.com", "alias"), // wrong login / bad characters => exception + ); + } + + /** + * @dataProvider getAddUserInvalidLoginData + * @expectedException \Exception + * @expectedExceptionMessage UsersManager_ExceptionInvalidLogin + */ + public function testAddUserWrongLogin($userLogin, $password, $email, $alias) + { + $this->api->addUser($userLogin, $password, $email, $alias); + } + + /** + * @expectedException \Exception + * @expectedExceptionMessage UsersManager_ExceptionLoginExists + */ + public function testAddUserExistingLogin() + { + $this->api->addUser("test", "password", "email@email.com", "alias"); + $this->api->addUser("test", "password2", "em2ail@email.com", "al2ias"); + } + + /** + * Dataprovider for wrong password tests + */ + public function getWrongPasswordTestData() + { + return array( + array("geggeqgeqag", "pas", "email@email.com", "alias"), // too short -> exception + array("ghqgeggg", "gegageqqqqqqqgeqgqeg84897897897897g122", "email@email.com", "alias"), // too long -> exception + array("geggeqgeqag", "", "email@email.com", "alias"), // empty -> exception + ); + } + + /** + * @dataProvider getWrongPasswordTestData + * @expectedException \Exception + * @expectedExceptionMessage UsersManager_ExceptionInvalidPassword + */ + public function testAddUserWrongPassword($userLogin, $password, $email, $alias) + { + $this->api->addUser($userLogin, $password, $email, $alias); + } + + /** + * Dataprovider for wrong email tests + */ + public function getWrongEmailTestData() + { + return array( + array("geggeqgeqag", "geqgeagae", "ema'il@email.com", "alias"), + array("geggeqgeqag", "geqgeagae", "@email.com", "alias"), + array("geggeqgeqag", "geqgeagae", "email@.com", "alias"), + array("geggeqgeqag", "geqgeagae", "email@4.", "alias"), + array("geggeqgeqag", "geqgeagae", "", "alias"), + ); + } + + /** + * @dataProvider getWrongEmailTestData + * @expectedException \Exception + * @expectedExceptionMessage mail + */ + public function testAddUserWrongEmail($userLogin, $password, $email, $alias) + { + $this->api->addUser($userLogin, $password, $email, $alias); + } + + /** + * empty alias => use login + */ + public function testAddUserEmptyAlias() + { + $login = "geggeqgeqag"; + $this->api->addUser($login, "geqgeagae", "mgeagi@geq.com", ""); + $user = $this->api->getUser($login); + $this->assertEquals($login, $user['alias']); + $this->assertEquals($login, $user['login']); + } + + /** + * no alias => use login + */ + public function testAddUserNoAliasSpecified() + { + $login = "geggeqg455eqag"; + $this->api->addUser($login, "geqgeagae", "mgeagi@geq.com"); + $user = $this->api->getUser($login); + $this->assertEquals($login, $user['alias']); + $this->assertEquals($login, $user['login']); + } + + /** + * normal test case + */ + public function testAddUser() + { + $login = "geggeq55eqag"; + $password = "mypassword"; + $email = "mgeag4544i@geq.com"; + $alias = "her is my alias )(&|\" '£%*(&%+))"; + + $time = time(); + $this->api->addUser($login, $password, $email, $alias); + $user = $this->api->getUser($login); + + // check that the date registered is correct + $this->assertTrue($time <= strtotime($user['date_registered']) && strtotime($user['date_registered']) <= time(), + "the date_registered " . strtotime($user['date_registered']) . " is different from the time() " . time()); + $this->assertTrue($user['date_registered'] <= time()); + + // check that token is 32 chars + $this->assertEquals(32, strlen($user['password'])); + + // that the password has been md5 + $this->assertEquals(md5($login . md5($password)), $user['token_auth']); + + // check that all fields are the same + $this->assertEquals($login, $user['login']); + $this->assertEquals(md5($password), $user['password']); + $this->assertEquals($email, $user['email']); + $this->assertEquals($alias, $user['alias']); + } + + /** + * @expectedException \Exception + * @expectedExceptionMessage UsersManager_ExceptionDeleteDoesNotExist + */ + public function testSeleteUserDoesntExist() + { + $this->api->addUser("geggeqgeqag", "geqgeagae", "test@test.com", "alias"); + $this->api->deleteUser("geggeqggnew"); + } + + /** + * @expectedException \Exception + * @expectedExceptionMessage UsersManager_ExceptionDeleteDoesNotExist + */ + public function testDeleteUserEmptyUser() + { + $this->api->deleteUser(""); + } + + /** + * @expectedException \Exception + * @expectedExceptionMessage UsersManager_ExceptionDeleteDoesNotExist + */ + public function testDeleteUserNullUser() + { + $this->api->deleteUser(null); + } + + /** + * @expectedException \Exception + * @expectedExceptionMessage UsersManager_ExceptionDeleteOnlyUserWithSuperUserAccess + */ + public function testDeleteUser_ShouldFail_InCaseTheUserIsTheOnlyRemainingSuperUser() + { + //add user and set some rights + $this->api->addUser("regularuser", "geqgeagae1", "test1@test.com", "alias1"); + $this->api->addUser("superuser", "geqgeagae2", "test2@test.com", "alias2"); + $this->api->setSuperUserAccess('superuser', true); + + // delete the user + $this->api->deleteUser("superuser"); + } + + /** + * normal case, user deleted + */ + public function testDeleteUser() + { + $this->addSites(3); + + //add user and set some rights + $this->api->addUser("geggeqgeqag", "geqgeagae", "test@test.com", "alias"); + $this->api->setUserAccess("geggeqgeqag", "view", array(1, 2)); + $this->api->setUserAccess("geggeqgeqag", "admin", array(1, 3)); + + // check rights are set + $this->assertNotEquals(array(), $this->api->getSitesAccessFromUser("geggeqgeqag")); + + // delete the user + $this->api->deleteUser("geggeqgeqag"); + + // try to get it, it should raise an exception + try { + $this->api->getUser("geggeqgeqag"); + $this->fail("Exception not raised."); + } catch (Exception $expected) { + $this->assertRegExp("(UsersManager_ExceptionUserDoesNotExist)", $expected->getMessage()); + } + + // add the same user + $this->api->addUser("geggeqgeqag", "geqgeagae", "test@test.com", "alias"); + + //checks access have been deleted + //to do so we recreate the same user login and check if the rights are still there + $this->assertEquals(array(), $this->api->getSitesAccessFromUser("geggeqgeqag")); + } + + /** + * @expectedException \Exception + * @expectedExceptionMessage UsersManager_ExceptionUserDoesNotExist + */ + public function testGetUserNoUser() + { + // try to get it, it should raise an exception + $this->api->getUser("geggeqgeqag"); + } + + /** + * normal case + */ + public function test_GetUser() + { + $login = "geggeq55eqag"; + $password = "mypassword"; + $email = "mgeag4544i@geq.com"; + $alias = ""; + + $this->api->addUser($login, $password, $email, $alias); + $user = $this->api->getUser($login); + + // check that all fields are the same + $this->assertEquals($login, $user['login']); + $this->assertInternalType('string', $user['password']); + $this->assertInternalType('string', $user['date_registered']); + $this->assertEquals($email, $user['email']); + + //alias shouldnt be empty even if no alias specified + $this->assertGreaterThan(0, strlen($user['alias'])); + } + + /** + * no user => empty array + */ + public function testGetUsersNoUser() + { + $this->assertEquals($this->api->getUsers(), array()); + } + + /** + * normal case + * as well as selecting specific user names, comma separated + */ + public function testGetUsers() + { + $this->api->addUser("gegg4564eqgeqag", "geqgegagae", "tegst@tesgt.com", "alias"); + $this->api->addUser("geggeqge632ge56a4qag", "geqgegeagae", "tesggt@tesgt.com", "alias"); + $this->api->addUser("geggeqgeqagqegg", "geqgeaggggae", "tesgggt@tesgt.com"); + + $users = $this->api->getUsers(); + $users = $this->_removeNonTestableFieldsFromUsers($users); + $user1 = array('login' => "gegg4564eqgeqag", 'password' => md5("geqgegagae"), 'alias' => "alias", 'email' => "tegst@tesgt.com", 'superuser_access' => 0); + $user2 = array('login' => "geggeqge632ge56a4qag", 'password' => md5("geqgegeagae"), 'alias' => "alias", 'email' => "tesggt@tesgt.com", 'superuser_access' => 0); + $user3 = array('login' => "geggeqgeqagqegg", 'password' => md5("geqgeaggggae"), 'alias' => 'geggeqgeqagqegg', 'email' => "tesgggt@tesgt.com", 'superuser_access' => 0); + $expectedUsers = array($user1, $user2, $user3); + $this->assertEquals($expectedUsers, $users); + $this->assertEquals(array($user1), $this->_removeNonTestableFieldsFromUsers($this->api->getUsers('gegg4564eqgeqag'))); + $this->assertEquals(array($user1, $user2), $this->_removeNonTestableFieldsFromUsers($this->api->getUsers('gegg4564eqgeqag,geggeqge632ge56a4qag'))); + } + + protected function _removeNonTestableFieldsFromUsers($users) + { + foreach ($users as &$user) { + unset($user['token_auth']); + unset($user['date_registered']); + } + return $users; + } + + /** + * normal case + */ + public function testGetUsersLogin() + { + $this->api->addUser('gegg4564eqgeqag', 'geqgegagae', 'tegst@tesgt.com', 'alias'); + $this->api->addUser("geggeqge632ge56a4qag", "geqgegeagae", "tesggt@tesgt.com", "alias"); + $this->api->addUser("geggeqgeqagqegg", "geqgeaggggae", "tesgggt@tesgt.com"); + + $logins = $this->api->getUsersLogin(); + + $this->assertEquals(array("gegg4564eqgeqag", "geggeqge632ge56a4qag", "geggeqgeqagqegg"), $logins); + } + + /** + * @expectedException \Exception + * @expectedExceptionMessage UsersManager_ExceptionUserDoesNotExist + */ + public function testSetUserAccessNoLogin() + { + $this->api->setUserAccess("nologin", "view", 1); + } + + /** + * @expectedException \Exception + * @expectedExceptionMessage UsersManager_ExceptionAccessValues + */ + public function testSetUserAccessWrongAccessSpecified() + { + $this->api->addUser("gegg4564eqgeqag", "geqgegagae", "tegst@tesgt.com", "alias"); + $this->api->setUserAccess("gegg4564eqgeqag", "viewnotknown", 1); + } + + /** + * @expectedException \Exception + * @expectedExceptionMessage UsersManager_ExceptionAccessValues + */ + public function testSetUserAccess_ShouldFail_SuperUserAccessIsNotAllowed() + { + $this->api->addUser("gegg4564eqgeqag", "geqgegagae", "tegst@tesgt.com", "alias"); + $this->api->setUserAccess("gegg4564eqgeqag", "superuser", 1); + } + + /** + * @expectedException \Exception + * @expectedExceptionMessage UsersManager_ExceptionUserDoesNotExist + */ + public function testSetUserAccess_ShouldFail_IfLoginIsConfigSuperUserLogin() + { + $this->api->setUserAccess('superusertest', 'view', 1); + } + + /** + * @expectedException \Exception + * @expectedExceptionMessage UsersManager_ExceptionSuperUserAccess + */ + public function testSetUserAccess_ShouldFail_IfLoginIsUserWithSuperUserAccess() + { + $this->api->addUser("gegg4564eqgeqag", "geqgegagae", "tegst@tesgt.com", "alias"); + $this->api->setSuperUserAccess('gegg4564eqgeqag', true); + + $this->api->setUserAccess('gegg4564eqgeqag', 'view', 1); + } + + /** + * idsites = all => apply access to all websites with admin access + */ + public function testSetUserAccessIdsitesIsAll() + { + $this->api->addUser("gegg4564eqgeqag", "geqgegagae", "tegst@tesgt.com", "alias"); + + FakeAccess::$superUser = false; + + $this->api->setUserAccess("gegg4564eqgeqag", "view", "all"); + + FakeAccess::$superUser = true; + $access = $this->api->getSitesAccessFromUser("gegg4564eqgeqag"); + $access = $this->_flatten($access); + + FakeAccess::$superUser = false; + $this->assertEquals(array_keys($access), FakeAccess::getSitesIdWithAdminAccess()); + + // we want to test the case for which we have actually set some rights + // if this is not OK then change the setUp method and add some admin rights for some websites + $this->assertGreaterThan(0, count(array_keys($access))); + } + + /** + * idsites = all AND user is superuser=> apply access to all websites + */ + public function testSetUserAccessIdsitesIsAllSuperuser() + { + FakeAccess::$superUser = true; + + $idSites = $this->addSites(5); + + $this->api->addUser("gegg4564eqgeqag", "geqgegagae", "tegst@tesgt.com", "alias"); + $this->api->setUserAccess("gegg4564eqgeqag", "view", "all"); + + $access = $this->api->getSitesAccessFromUser("gegg4564eqgeqag"); + $access = $this->_flatten($access); + $this->assertEquals($idSites, array_keys($access)); + } + + /** + * @expectedException \Exception + */ + public function testSetUserAccess_ShouldNotBeAbleToSetAnyAccess_IfIdSitesIsEmpty() + { + $this->api->addUser("gegg4564eqgeqag", "geqgegagae", "tegst@tesgt.com", "alias"); + + $this->api->setUserAccess("gegg4564eqgeqag", "view", array()); + } + + /** + * normal case, access set for only one site + */ + public function testSetUserAccessIdsitesOneSite() + { + $this->api->addUser("gegg4564eqgeqag", "geqgegagae", "tegst@tesgt.com", "alias"); + $idSites = $this->addSites(1); + + $this->api->setUserAccess("gegg4564eqgeqag", "view", $idSites); + + $access = $this->api->getSitesAccessFromUser("gegg4564eqgeqag"); + $access = $this->_flatten($access); + $this->assertEquals($idSites, array_keys($access)); + } + + /** + * normal case, access set for multiple sites + */ + public function testSetUserAccessIdsitesMultipleSites() + { + $this->api->addUser("gegg4564eqgeqag", "geqgegagae", "tegst@tesgt.com", "alias"); + list($id1, $id2, $id3) = $this->addSites(3); + + $this->api->setUserAccess("gegg4564eqgeqag", "view", array($id1, $id3)); + + $access = $this->api->getSitesAccessFromUser("gegg4564eqgeqag"); + $access = $this->_flatten($access); + $this->assertEquals(array($id1, $id3), array_keys($access)); + } + + /** + * normal case, string idSites comma separated access set for multiple sites + */ + public function testSetUserAccessWithIdSitesIsStringCommaSeparated() + { + $this->api->addUser("gegg4564eqgeqag", "geqgegagae", "tegst@tesgt.com", "alias"); + list($id1, $id2, $id3) = $this->addSites(3); + + $this->api->setUserAccess("gegg4564eqgeqag", "view", "1,3"); + + $access = $this->api->getSitesAccessFromUser("gegg4564eqgeqag"); + $access = $this->_flatten($access); + $this->assertEquals(array($id1, $id3), array_keys($access)); + } + + /** + * normal case, set different acccess to different websites for one user + */ + public function testSetUserAccessMultipleCallDistinctAccessSameUser() + { + $this->api->addUser("gegg4564eqgeqag", "geqgegagae", "tegst@tesgt.com", "alias"); + + list($id1, $id2) = $this->addSites(2); + + $this->api->setUserAccess("gegg4564eqgeqag", "view", array($id1)); + $this->api->setUserAccess("gegg4564eqgeqag", "admin", array($id2)); + + $access = $this->api->getSitesAccessFromUser("gegg4564eqgeqag"); + $access = $this->_flatten($access); + $this->assertEquals(array($id1 => 'view', $id2 => 'admin'), $access); + } + + /** + * normal case, set different access to different websites for multiple users + */ + public function testSetUserAccessMultipleCallDistinctAccessMultipleUser() + { + $this->api->addUser("user1", "geqgegagae", "tegst@tesgt.com", "alias"); + $this->api->addUser("user2", "geqgegagae", "tegst2@tesgt.com", "alias"); + + list($id1, $id2, $id3) = $this->addSites(3); + + $this->api->setUserAccess("user1", "view", array($id1, $id2)); + $this->api->setUserAccess("user2", "admin", array($id1)); + $this->api->setUserAccess("user2", "view", array($id3, $id2)); + + $access1 = $this->api->getSitesAccessFromUser("user1"); + $access1 = $this->_flatten($access1); + $access2 = $this->api->getSitesAccessFromUser("user2"); + $access2 = $this->_flatten($access2); + $wanted1 = array($id1 => 'view', $id2 => 'view',); + $wanted2 = array($id1 => 'admin', $id2 => 'view', $id3 => 'view'); + + $this->assertEquals($wanted1, $access1); + $this->assertEquals($wanted2, $access2); + + $access1 = $this->api->getUsersAccessFromSite($id1); + $access2 = $this->api->getUsersAccessFromSite($id2); + $access3 = $this->api->getUsersAccessFromSite($id3); + $wanted1 = array('user1' => 'view', 'user2' => 'admin',); + $wanted2 = array('user1' => 'view', 'user2' => 'view'); + $wanted3 = array('user2' => 'view'); + + $this->assertEquals($wanted1, $access1); + $this->assertEquals($wanted2, $access2); + $this->assertEquals($wanted3, $access3); + + $access1 = $this->api->getUsersSitesFromAccess('view'); + $access2 = $this->api->getUsersSitesFromAccess('admin'); + $wanted1 = array('user1' => array($id1, $id2), 'user2' => array($id2, $id3)); + $wanted2 = array('user2' => array($id1)); + + $this->assertEquals($wanted1, $access1); + $this->assertEquals($wanted2, $access2); + + // Test getUsersWithSiteAccess + $users = $this->api->getUsersWithSiteAccess($id1, $access = 'view'); + $this->assertEquals(1, count($users)); + $this->assertEquals('user1', $users[0]['login']); + $users = $this->api->getUsersWithSiteAccess($id2, $access = 'view'); + $this->assertEquals(2, count($users)); + $users = $this->api->getUsersWithSiteAccess($id1, $access = 'admin'); + $this->assertEquals(1, count($users)); + $this->assertEquals('user2', $users[0]['login']); + $users = $this->api->getUsersWithSiteAccess($id3, $access = 'admin'); + $this->assertEquals(0, count($users)); + } + + /** + * we set access for one user for one site several times and check that it is updated + */ + public function testSetUserAccessMultipleCallOverwriteSingleUserOneSite() + { + $this->api->addUser("user1", "geqgegagae", "tegst@tesgt.com", "alias"); + + list($id1, $id2) = $this->addSites(2); + + $this->api->setUserAccess("user1", "view", array($id1, $id2)); + $this->api->setUserAccess("user1", "admin", array($id1)); + + $access1 = $this->api->getSitesAccessFromUser("user1"); + $access1 = $this->_flatten($access1); + $wanted1 = array($id1 => 'admin', $id2 => 'view',); + + $this->assertEquals($wanted1, $access1); + } + + /** + * @expectedException \Exception + * @expectedExceptionMessage checkUserHasSuperUserAccess Fake exception + */ + public function testSetSuperUserAccess_ShouldFail_IfUserHasNotSuperUserPermission() + { + FakeAccess::setSuperUserAccess(false); + $this->api->setSuperUserAccess('nologin', false); + } + + /** + * @expectedException \Exception + * @expectedExceptionMessage UsersManager_ExceptionUserDoesNotExist + */ + public function testSetSuperUserAccess_ShouldFail_IfUserWithGivenLoginDoesNotExist() + { + $this->api->setSuperUserAccess('nologin', false); + } + + /** + * @expectedException \Exception + * @expectedExceptionMessage UsersManager_ExceptionEditAnonymous + */ + public function testSetSuperUserAccess_ShouldFail_IfUserIsAnonymous() + { + $this->api->setSuperUserAccess('anonymous', true); + } + + /** + * @expectedException \Exception + * @expectedExceptionMessage UsersManager_ExceptionRemoveSuperUserAccessOnlySuperUser + */ + public function testSetSuperUserAccess_ShouldFail_IfUserIsOnlyRemainingUserWithSuperUserAccess() + { + $this->api->addUser('login1', 'password1', 'test@example.com', false); + $this->api->setSuperUserAccess('login1', true); + + $this->api->setSuperUserAccess('login1', false); + } + + public function testSetSuperUserAccess_ShouldDeleteAllExistingAccessEntries() + { + list($id1, $id2) = $this->addSites(2); + $this->api->addUser('login1', 'password1', 'test@example.com', false); + $this->api->setUserAccess('login1', 'view', array($id1)); + $this->api->setUserAccess('login1', 'admin', array($id2)); + + // verify user has access before setting Super User access + $access = $this->_flatten($this->api->getSitesAccessFromUser('login1')); + $this->assertEquals(array($id1 => 'view', $id2 => 'admin'), $access); + + $this->api->setSuperUserAccess('login1', true); + + // verify no longer any access + $this->assertEquals(array(), $this->model->getSitesAccessFromUser('login1')); + } + + public function testSetSuperUserAccess_ShouldAddAndRemoveSuperUserAccessOnlyForGivenLogin() + { + $this->api->addUser('login1', 'password1', 'test1@example.com', false); + $this->api->addUser('login2', 'password2', 'test2@example.com', false); + $this->api->addUser('login3', 'password3', 'test3@example.com', false); + + $this->api->setSuperUserAccess('login2', true); + + // test add Super User access + $users = $this->api->getUsers(); + + $this->assertEquals(0, $users[0]['superuser_access']); + $this->assertEquals(1, $users[1]['superuser_access']); + $this->assertEquals('login2', $users[1]['login']); + $this->assertEquals(0, $users[2]['superuser_access']); + + // should also accept string '1' to add Super User access + $this->api->setSuperUserAccess('login1', '1'); + // test remove Super User access + $this->api->setSuperUserAccess('login2', false); + + $users = $this->api->getUsers(); + $this->assertEquals(1, $users[0]['superuser_access']); + $this->assertEquals('login1', $users[0]['login']); + $this->assertEquals(0, $users[1]['superuser_access']); + $this->assertEquals(0, $users[2]['superuser_access']); + + $this->api->setSuperUserAccess('login3', true); + // should also accept string '0' to remove Super User access + $this->api->setSuperUserAccess('login1', '0'); + + $users = $this->api->getUsers(); + $this->assertEquals(0, $users[0]['superuser_access']); + $this->assertEquals(0, $users[1]['superuser_access']); + $this->assertEquals('login3', $users[2]['login']); + $this->assertEquals(1, $users[2]['superuser_access']); + } + + /** + * @expectedException \Exception + * @expectedExceptionMessage UsersManager_ExceptionUserDoesNotExist + */ + public function testGetSitesAccessFromUserWrongUser() + { + $this->api->getSitesAccessFromUser("user1"); + } + + /** + * @expectedException \Exception + */ + public function testGetUsersAccessFromSiteWrongIdSite() + { + $this->api->getUsersAccessFromSite(1); + } + + /** + * @expectedException \Exception + * @expectedExceptionMessage UsersManager_ExceptionAccessValues + */ + public function testGetUsersSitesFromAccessWrongSite() + { + $this->api->getUsersSitesFromAccess('unknown'); + } + + /** + * @expectedException \Exception + * @expectedExceptionMessage UsersManager_ExceptionUserDoesNotExist + */ + public function testUpdateUserNonExistingLogin() + { + $this->api->updateUser("lolgin", "password"); + } + + /** + * no email no alias => keep old ones + */ + public function testUpdateUserNoEmailNoAlias() + { + $login = "login"; + $user = array('login' => $login, + 'password' => "geqgeagae", + 'email' => "test@test.com", + 'alias' => "alias"); + + $this->api->addUser($user['login'], $user['password'], $user['email'], $user['alias']); + $this->api->updateUser($login, "passowordOK"); + + $this->_checkUserHasNotChanged($user, "passowordOK"); + } + + /** + * no email => keep old ones + */ + public function testUpdateUserNoEmail() + { + $login = "login"; + $user = array('login' => $login, + 'password' => "geqgeagae", + 'email' => "test@test.com", + 'alias' => "alias"); + + $this->api->addUser($user['login'], $user['password'], $user['email'], $user['alias']); + $this->api->updateUser($login, "passowordOK", null, "newalias"); + + $this->_checkUserHasNotChanged($user, "passowordOK", null, "newalias"); + } + + /** + * no alias => keep old ones + */ + public function testUpdateUserNoAlias() + { + $login = "login"; + $user = array('login' => $login, + 'password' => "geqgeagae", + 'email' => "test@test.com", + 'alias' => "alias"); + + $this->api->addUser($user['login'], $user['password'], $user['email'], $user['alias']); + $this->api->updateUser($login, "passowordOK", "email@geaga.com"); + + $this->_checkUserHasNotChanged($user, "passowordOK", "email@geaga.com"); + } + + /** + * check to modify as the user + * @expectedException \Exception + * @expectedExceptionMessage UsersManager_ExceptionLoginExists + */ + public function testAddUserIAmTheUser() + { + FakeAccess::$identity = 'login'; + $this->testUpdateUserNoEmailNoAlias(); + } + + /** + * check to modify as being another user => exception + * + * @expectedException \Exception + */ + public function testUpdateUserIAmNotTheUser() + { + FakeAccess::$identity = 'login2'; + FakeAccess::$superUser = false; + $this->testUpdateUserNoEmailNoAlias(); + } + + /** + * normal case, reused in other tests + */ + public function testUpdateUser() + { + $login = "login"; + $user = array('login' => $login, + 'password' => "geqgeagae", + 'email' => "test@test.com", + 'alias' => "alias"); + + $this->api->addUser($user['login'], $user['password'], $user['email'], $user['alias']); + $this->api->updateUser($login, "passowordOK", "email@geaga.com", "NEW ALIAS"); + + $this->_checkUserHasNotChanged($user, "passowordOK", "email@geaga.com", "NEW ALIAS"); + } + + /** + * @expectedException \Exception + */ + public function testGetUserByEmailInvalidMail() + { + $this->api->getUserByEmail('email@test.com'); + } + + public function testGetUserByEmail() + { + $user = array('login' => "login", + 'password' => "geqgeagae", + 'email' => "test@test.com", + 'alias' => "alias"); + + $this->api->addUser($user['login'], $user['password'], $user['email'], $user['alias']); + + $userByMail = $this->api->getUserByEmail($user['email']); + + $this->assertEquals($user['login'], $userByMail['login']); + $this->assertEquals($user['email'], $userByMail['email']); + $this->assertEquals($user['alias'], $userByMail['alias']); + } + + public function testGetUserPreferenceDefault() + { + $this->addSites(1); + $defaultReportPref = API::PREFERENCE_DEFAULT_REPORT; + $defaultReportDatePref = API::PREFERENCE_DEFAULT_REPORT_DATE; + + $this->assertEquals(1, $this->api->getUserPreference('someUser', $defaultReportPref)); + $this->assertEquals('yesterday', $this->api->getUserPreference('someUser', $defaultReportDatePref)); + } + + private function addSites($numberOfSites) + { + $idSites = array(); + + for ($index = 0; $index < $numberOfSites; $index++) { + $name = "test" . ($index + 1); + $idSites[] = APISitesManager::getInstance()->addSite($name, array("http://piwik.net", "http://piwik.com/test/")); + } + + return $idSites; + } +} diff --git a/plugins/UsersManager/tests/UserPreferencesTest.php b/plugins/UsersManager/tests/UserPreferencesTest.php deleted file mode 100644 index 50658e46e2..0000000000 --- a/plugins/UsersManager/tests/UserPreferencesTest.php +++ /dev/null @@ -1,117 +0,0 @@ -userPreferences = new UserPreferences(); - - $this->setSuperUser(); - } - - public function test_getDefaultReport_ShouldReturnFalseByDefault() - { - $this->assertEquals(false, $this->userPreferences->getDefaultReport()); - } - - public function test_getDefaultReport_ShouldReturnTheRawValueIfNotNumeric() - { - $this->setDefaultReport('MultiSites'); - $this->assertEquals('MultiSites', $this->userPreferences->getDefaultReport()); - } - - public function test_getDefaultReport_ShouldNotReturnSiteIdIfNoPermissionForSite() - { - $this->createSite(); - $this->setDefaultReport(1); - $this->setAnonymous(); - $this->assertEquals(false, $this->userPreferences->getDefaultReport()); - } - - public function test_getDefaultReport_ShouldReturnSiteIdIfPermissionForSite() - { - $this->createSite(); - $this->setDefaultReport(1); - $this->assertEquals(1, $this->userPreferences->getDefaultReport()); - } - - public function test_getDefaultWebsiteId_ShouldReturnFalseByDefault() - { - $this->assertEquals(false, $this->userPreferences->getDefaultWebsiteId()); - } - - public function test_getDefaultWebsiteId_ShouldReturnASiteIfOneExistsAndHasAccess() - { - $this->createSite(); - $this->assertEquals(1, $this->userPreferences->getDefaultWebsiteId()); - } - - public function test_getDefaultWebsiteId_ShouldReturnFalseIfASiteExistsButHasNoAccess() - { - $this->createSite(); - $this->setAnonymous(); - $this->assertEquals(false, $this->userPreferences->getDefaultWebsiteId()); - } - - public function test_getDefaultWebsiteId_ShouldReturnASiteEvenIfMultiSitesIsDefaultReport() - { - $this->setDefaultReport('MultiSites'); - $this->createSite(); - $this->assertEquals(1, $this->userPreferences->getDefaultWebsiteId()); - } - - private function setSuperUser() - { - $pseudoMockAccess = new FakeAccess(); - FakeAccess::$superUser = true; - Access::setSingletonInstance($pseudoMockAccess); - } - - private function setAnonymous() - { - $pseudoMockAccess = new FakeAccess(); - FakeAccess::$superUser = false; - Access::setSingletonInstance($pseudoMockAccess); - } - - private function createSite() - { - Fixture::createWebsite('2013-01-23 01:23:45'); - } - - private function setDefaultReport($defaultReport) - { - APIUsersManager::getInstance()->setUserPreference(Piwik::getCurrentUserLogin(), - APIUsersManager::PREFERENCE_DEFAULT_REPORT, - $defaultReport); - } - -} diff --git a/plugins/UsersManager/tests/UsersManagerTest.php b/plugins/UsersManager/tests/UsersManagerTest.php deleted file mode 100644 index da73e142d3..0000000000 --- a/plugins/UsersManager/tests/UsersManagerTest.php +++ /dev/null @@ -1,917 +0,0 @@ -loadPlugin('UsersManager'); - \Piwik\Plugin\Manager::getInstance()->installLoadedPlugins(); - - // setup the access layer - $pseudoMockAccess = new FakeAccess; - FakeAccess::setIdSitesView(array(1, 2)); - FakeAccess::setIdSitesAdmin(array(3, 4)); - - //finally we set the user as a Super User by default - FakeAccess::$superUser = true; - FakeAccess::$superUserLogin = 'superusertest'; - Access::setSingletonInstance($pseudoMockAccess); - - $this->api = API::getInstance(); - $this->model = new Model(); - } - - private function _flatten($sitesAccess) - { - $result = array(); - - foreach ($sitesAccess as $siteAccess) { - $result[$siteAccess['site']] = $siteAccess['access']; - } - - return $result; - } - - private function _checkUserHasNotChanged($user, $newPassword, $newEmail = null, $newAlias = null) - { - if (is_null($newEmail)) { - $newEmail = $user['email']; - } - if (is_null($newAlias)) { - $newAlias = $user['alias']; - } - $userAfter = $this->api->getUser($user["login"]); - unset($userAfter['date_registered']); - - // we now compute what the token auth should be, it should always be a hash of the login and the current password - // if the password has changed then the token_auth has changed! - $user['token_auth'] = $this->api->getTokenAuth($user["login"], md5($newPassword)); - $user['password'] = md5($newPassword); - $user['email'] = $newEmail; - $user['alias'] = $newAlias; - $user['superuser_access'] = 0; - $this->assertEquals($user, $userAfter); - } - - /** - * bad password => exception# - * @expectedException \Exception - * @expectedExceptionMessage UsersManager_ExceptionInvalidPassword - */ - public function testUpdateUserBadpasswd() - { - $login = "login"; - $user = array('login' => $login, - 'password' => "geqgeagae", - 'email' => "test@test.com", - 'alias' => "alias"); - - $this->api->addUser($user['login'], $user['password'], $user['email'], $user['alias']); - - try { - $this->api->updateUser($login, "pas"); - } catch (Exception $expected) { - $this->_checkUserHasNotChanged($user, $user['password']); - throw $expected; - } - } - - /** - * Dataprovider - */ - public function getAddUserInvalidLoginData() - { - return array( - array(12, "password", "email@email.com", "alias"), // wrong login / integer => exception - array("gegag'ggea'", "password", "email@email.com", "alias"), // wrong login / too short => exception - array("gegag11gge&", "password", "email@email.com", "alias"), // wrong login / too long => exception - array("geg'ag11gge@", "password", "email@email.com", "alias"), // wrong login / bad characters => exception - ); - } - - /** - * @dataProvider getAddUserInvalidLoginData - * @expectedException \Exception - * @expectedExceptionMessage UsersManager_ExceptionInvalidLogin - */ - public function testAddUserWrongLogin($userLogin, $password, $email, $alias) - { - $this->api->addUser($userLogin, $password, $email, $alias); - } - - /** - * @expectedException \Exception - * @expectedExceptionMessage UsersManager_ExceptionLoginExists - */ - public function testAddUserExistingLogin() - { - $this->api->addUser("test", "password", "email@email.com", "alias"); - $this->api->addUser("test", "password2", "em2ail@email.com", "al2ias"); - } - - /** - * Dataprovider for wrong password tests - */ - public function getWrongPasswordTestData() - { - return array( - array("geggeqgeqag", "pas", "email@email.com", "alias"), // too short -> exception - array("ghqgeggg", "gegageqqqqqqqgeqgqeg84897897897897g122", "email@email.com", "alias"), // too long -> exception - array("geggeqgeqag", "", "email@email.com", "alias"), // empty -> exception - ); - } - - /** - * @dataProvider getWrongPasswordTestData - * @expectedException \Exception - * @expectedExceptionMessage UsersManager_ExceptionInvalidPassword - */ - public function testAddUserWrongPassword($userLogin, $password, $email, $alias) - { - $this->api->addUser($userLogin, $password, $email, $alias); - } - - /** - * Dataprovider for wrong email tests - */ - public function getWrongEmailTestData() - { - return array( - array("geggeqgeqag", "geqgeagae", "ema'il@email.com", "alias"), - array("geggeqgeqag", "geqgeagae", "@email.com", "alias"), - array("geggeqgeqag", "geqgeagae", "email@.com", "alias"), - array("geggeqgeqag", "geqgeagae", "email@4.", "alias"), - array("geggeqgeqag", "geqgeagae", "", "alias"), - ); - } - - /** - * @dataProvider getWrongEmailTestData - * @expectedException \Exception - * @expectedExceptionMessage mail - */ - public function testAddUserWrongEmail($userLogin, $password, $email, $alias) - { - $this->api->addUser($userLogin, $password, $email, $alias); - } - - /** - * empty alias => use login - */ - public function testAddUserEmptyAlias() - { - $login = "geggeqgeqag"; - $this->api->addUser($login, "geqgeagae", "mgeagi@geq.com", ""); - $user = $this->api->getUser($login); - $this->assertEquals($login, $user['alias']); - $this->assertEquals($login, $user['login']); - } - - /** - * no alias => use login - */ - public function testAddUserNoAliasSpecified() - { - $login = "geggeqg455eqag"; - $this->api->addUser($login, "geqgeagae", "mgeagi@geq.com"); - $user = $this->api->getUser($login); - $this->assertEquals($login, $user['alias']); - $this->assertEquals($login, $user['login']); - } - - /** - * normal test case - */ - public function testAddUser() - { - $login = "geggeq55eqag"; - $password = "mypassword"; - $email = "mgeag4544i@geq.com"; - $alias = "her is my alias )(&|\" '£%*(&%+))"; - - $time = time(); - $this->api->addUser($login, $password, $email, $alias); - $user = $this->api->getUser($login); - - // check that the date registered is correct - $this->assertTrue($time <= strtotime($user['date_registered']) && strtotime($user['date_registered']) <= time(), - "the date_registered " . strtotime($user['date_registered']) . " is different from the time() " . time()); - $this->assertTrue($user['date_registered'] <= time()); - - // check that token is 32 chars - $this->assertEquals(32, strlen($user['password'])); - - // that the password has been md5 - $this->assertEquals(md5($login . md5($password)), $user['token_auth']); - - // check that all fields are the same - $this->assertEquals($login, $user['login']); - $this->assertEquals(md5($password), $user['password']); - $this->assertEquals($email, $user['email']); - $this->assertEquals($alias, $user['alias']); - } - - /** - * @expectedException \Exception - * @expectedExceptionMessage UsersManager_ExceptionDeleteDoesNotExist - */ - public function testSeleteUserDoesntExist() - { - $this->api->addUser("geggeqgeqag", "geqgeagae", "test@test.com", "alias"); - $this->api->deleteUser("geggeqggnew"); - } - - /** - * @expectedException \Exception - * @expectedExceptionMessage UsersManager_ExceptionDeleteDoesNotExist - */ - public function testDeleteUserEmptyUser() - { - $this->api->deleteUser(""); - } - - /** - * @expectedException \Exception - * @expectedExceptionMessage UsersManager_ExceptionDeleteDoesNotExist - */ - public function testDeleteUserNullUser() - { - $this->api->deleteUser(null); - } - - /** - * @expectedException \Exception - * @expectedExceptionMessage UsersManager_ExceptionDeleteOnlyUserWithSuperUserAccess - */ - public function testDeleteUser_ShouldFail_InCaseTheUserIsTheOnlyRemainingSuperUser() - { - //add user and set some rights - $this->api->addUser("regularuser", "geqgeagae1", "test1@test.com", "alias1"); - $this->api->addUser("superuser", "geqgeagae2", "test2@test.com", "alias2"); - $this->api->setSuperUserAccess('superuser', true); - - // delete the user - $this->api->deleteUser("superuser"); - } - - /** - * normal case, user deleted - */ - public function testDeleteUser() - { - $this->addSites(3); - - //add user and set some rights - $this->api->addUser("geggeqgeqag", "geqgeagae", "test@test.com", "alias"); - $this->api->setUserAccess("geggeqgeqag", "view", array(1, 2)); - $this->api->setUserAccess("geggeqgeqag", "admin", array(1, 3)); - - // check rights are set - $this->assertNotEquals(array(), $this->api->getSitesAccessFromUser("geggeqgeqag")); - - // delete the user - $this->api->deleteUser("geggeqgeqag"); - - // try to get it, it should raise an exception - try { - $this->api->getUser("geggeqgeqag"); - $this->fail("Exception not raised."); - } catch (Exception $expected) { - $this->assertRegExp("(UsersManager_ExceptionUserDoesNotExist)", $expected->getMessage()); - } - - // add the same user - $this->api->addUser("geggeqgeqag", "geqgeagae", "test@test.com", "alias"); - - //checks access have been deleted - //to do so we recreate the same user login and check if the rights are still there - $this->assertEquals(array(), $this->api->getSitesAccessFromUser("geggeqgeqag")); - } - - /** - * @expectedException \Exception - * @expectedExceptionMessage UsersManager_ExceptionUserDoesNotExist - */ - public function testGetUserNoUser() - { - // try to get it, it should raise an exception - $this->api->getUser("geggeqgeqag"); - } - - /** - * normal case - */ - public function test_GetUser() - { - $login = "geggeq55eqag"; - $password = "mypassword"; - $email = "mgeag4544i@geq.com"; - $alias = ""; - - $this->api->addUser($login, $password, $email, $alias); - $user = $this->api->getUser($login); - - // check that all fields are the same - $this->assertEquals($login, $user['login']); - $this->assertInternalType('string', $user['password']); - $this->assertInternalType('string', $user['date_registered']); - $this->assertEquals($email, $user['email']); - - //alias shouldnt be empty even if no alias specified - $this->assertGreaterThan(0, strlen($user['alias'])); - } - - /** - * no user => empty array - */ - public function testGetUsersNoUser() - { - $this->assertEquals($this->api->getUsers(), array()); - } - - /** - * normal case - * as well as selecting specific user names, comma separated - */ - public function testGetUsers() - { - $this->api->addUser("gegg4564eqgeqag", "geqgegagae", "tegst@tesgt.com", "alias"); - $this->api->addUser("geggeqge632ge56a4qag", "geqgegeagae", "tesggt@tesgt.com", "alias"); - $this->api->addUser("geggeqgeqagqegg", "geqgeaggggae", "tesgggt@tesgt.com"); - - $users = $this->api->getUsers(); - $users = $this->_removeNonTestableFieldsFromUsers($users); - $user1 = array('login' => "gegg4564eqgeqag", 'password' => md5("geqgegagae"), 'alias' => "alias", 'email' => "tegst@tesgt.com", 'superuser_access' => 0); - $user2 = array('login' => "geggeqge632ge56a4qag", 'password' => md5("geqgegeagae"), 'alias' => "alias", 'email' => "tesggt@tesgt.com", 'superuser_access' => 0); - $user3 = array('login' => "geggeqgeqagqegg", 'password' => md5("geqgeaggggae"), 'alias' => 'geggeqgeqagqegg', 'email' => "tesgggt@tesgt.com", 'superuser_access' => 0); - $expectedUsers = array($user1, $user2, $user3); - $this->assertEquals($expectedUsers, $users); - $this->assertEquals(array($user1), $this->_removeNonTestableFieldsFromUsers($this->api->getUsers('gegg4564eqgeqag'))); - $this->assertEquals(array($user1, $user2), $this->_removeNonTestableFieldsFromUsers($this->api->getUsers('gegg4564eqgeqag,geggeqge632ge56a4qag'))); - } - - protected function _removeNonTestableFieldsFromUsers($users) - { - foreach ($users as &$user) { - unset($user['token_auth']); - unset($user['date_registered']); - } - return $users; - } - - /** - * normal case - */ - public function testGetUsersLogin() - { - $this->api->addUser('gegg4564eqgeqag', 'geqgegagae', 'tegst@tesgt.com', 'alias'); - $this->api->addUser("geggeqge632ge56a4qag", "geqgegeagae", "tesggt@tesgt.com", "alias"); - $this->api->addUser("geggeqgeqagqegg", "geqgeaggggae", "tesgggt@tesgt.com"); - - $logins = $this->api->getUsersLogin(); - - $this->assertEquals(array("gegg4564eqgeqag", "geggeqge632ge56a4qag", "geggeqgeqagqegg"), $logins); - } - - /** - * @expectedException \Exception - * @expectedExceptionMessage UsersManager_ExceptionUserDoesNotExist - */ - public function testSetUserAccessNoLogin() - { - $this->api->setUserAccess("nologin", "view", 1); - } - - /** - * @expectedException \Exception - * @expectedExceptionMessage UsersManager_ExceptionAccessValues - */ - public function testSetUserAccessWrongAccessSpecified() - { - $this->api->addUser("gegg4564eqgeqag", "geqgegagae", "tegst@tesgt.com", "alias"); - $this->api->setUserAccess("gegg4564eqgeqag", "viewnotknown", 1); - } - - /** - * @expectedException \Exception - * @expectedExceptionMessage UsersManager_ExceptionAccessValues - */ - public function testSetUserAccess_ShouldFail_SuperUserAccessIsNotAllowed() - { - $this->api->addUser("gegg4564eqgeqag", "geqgegagae", "tegst@tesgt.com", "alias"); - $this->api->setUserAccess("gegg4564eqgeqag", "superuser", 1); - } - - /** - * @expectedException \Exception - * @expectedExceptionMessage UsersManager_ExceptionUserDoesNotExist - */ - public function testSetUserAccess_ShouldFail_IfLoginIsConfigSuperUserLogin() - { - $this->api->setUserAccess('superusertest', 'view', 1); - } - - /** - * @expectedException \Exception - * @expectedExceptionMessage UsersManager_ExceptionSuperUserAccess - */ - public function testSetUserAccess_ShouldFail_IfLoginIsUserWithSuperUserAccess() - { - $this->api->addUser("gegg4564eqgeqag", "geqgegagae", "tegst@tesgt.com", "alias"); - $this->api->setSuperUserAccess('gegg4564eqgeqag', true); - - $this->api->setUserAccess('gegg4564eqgeqag', 'view', 1); - } - - /** - * idsites = all => apply access to all websites with admin access - */ - public function testSetUserAccessIdsitesIsAll() - { - $this->api->addUser("gegg4564eqgeqag", "geqgegagae", "tegst@tesgt.com", "alias"); - - FakeAccess::$superUser = false; - - $this->api->setUserAccess("gegg4564eqgeqag", "view", "all"); - - FakeAccess::$superUser = true; - $access = $this->api->getSitesAccessFromUser("gegg4564eqgeqag"); - $access = $this->_flatten($access); - - FakeAccess::$superUser = false; - $this->assertEquals(array_keys($access), FakeAccess::getSitesIdWithAdminAccess()); - - // we want to test the case for which we have actually set some rights - // if this is not OK then change the setUp method and add some admin rights for some websites - $this->assertGreaterThan(0, count(array_keys($access))); - } - - /** - * idsites = all AND user is superuser=> apply access to all websites - */ - public function testSetUserAccessIdsitesIsAllSuperuser() - { - FakeAccess::$superUser = true; - - $idSites = $this->addSites(5); - - $this->api->addUser("gegg4564eqgeqag", "geqgegagae", "tegst@tesgt.com", "alias"); - $this->api->setUserAccess("gegg4564eqgeqag", "view", "all"); - - $access = $this->api->getSitesAccessFromUser("gegg4564eqgeqag"); - $access = $this->_flatten($access); - $this->assertEquals($idSites, array_keys($access)); - } - - /** - * @expectedException \Exception - */ - public function testSetUserAccess_ShouldNotBeAbleToSetAnyAccess_IfIdSitesIsEmpty() - { - $this->api->addUser("gegg4564eqgeqag", "geqgegagae", "tegst@tesgt.com", "alias"); - - $this->api->setUserAccess("gegg4564eqgeqag", "view", array()); - } - - /** - * normal case, access set for only one site - */ - public function testSetUserAccessIdsitesOneSite() - { - $this->api->addUser("gegg4564eqgeqag", "geqgegagae", "tegst@tesgt.com", "alias"); - $idSites = $this->addSites(1); - - $this->api->setUserAccess("gegg4564eqgeqag", "view", $idSites); - - $access = $this->api->getSitesAccessFromUser("gegg4564eqgeqag"); - $access = $this->_flatten($access); - $this->assertEquals($idSites, array_keys($access)); - } - - /** - * normal case, access set for multiple sites - */ - public function testSetUserAccessIdsitesMultipleSites() - { - $this->api->addUser("gegg4564eqgeqag", "geqgegagae", "tegst@tesgt.com", "alias"); - list($id1, $id2, $id3) = $this->addSites(3); - - $this->api->setUserAccess("gegg4564eqgeqag", "view", array($id1, $id3)); - - $access = $this->api->getSitesAccessFromUser("gegg4564eqgeqag"); - $access = $this->_flatten($access); - $this->assertEquals(array($id1, $id3), array_keys($access)); - } - - /** - * normal case, string idSites comma separated access set for multiple sites - */ - public function testSetUserAccessWithIdSitesIsStringCommaSeparated() - { - $this->api->addUser("gegg4564eqgeqag", "geqgegagae", "tegst@tesgt.com", "alias"); - list($id1, $id2, $id3) = $this->addSites(3); - - $this->api->setUserAccess("gegg4564eqgeqag", "view", "1,3"); - - $access = $this->api->getSitesAccessFromUser("gegg4564eqgeqag"); - $access = $this->_flatten($access); - $this->assertEquals(array($id1, $id3), array_keys($access)); - } - - /** - * normal case, set different acccess to different websites for one user - */ - public function testSetUserAccessMultipleCallDistinctAccessSameUser() - { - $this->api->addUser("gegg4564eqgeqag", "geqgegagae", "tegst@tesgt.com", "alias"); - - list($id1, $id2) = $this->addSites(2); - - $this->api->setUserAccess("gegg4564eqgeqag", "view", array($id1)); - $this->api->setUserAccess("gegg4564eqgeqag", "admin", array($id2)); - - $access = $this->api->getSitesAccessFromUser("gegg4564eqgeqag"); - $access = $this->_flatten($access); - $this->assertEquals(array($id1 => 'view', $id2 => 'admin'), $access); - } - - /** - * normal case, set different access to different websites for multiple users - */ - public function testSetUserAccessMultipleCallDistinctAccessMultipleUser() - { - $this->api->addUser("user1", "geqgegagae", "tegst@tesgt.com", "alias"); - $this->api->addUser("user2", "geqgegagae", "tegst2@tesgt.com", "alias"); - - list($id1, $id2, $id3) = $this->addSites(3); - - $this->api->setUserAccess("user1", "view", array($id1, $id2)); - $this->api->setUserAccess("user2", "admin", array($id1)); - $this->api->setUserAccess("user2", "view", array($id3, $id2)); - - $access1 = $this->api->getSitesAccessFromUser("user1"); - $access1 = $this->_flatten($access1); - $access2 = $this->api->getSitesAccessFromUser("user2"); - $access2 = $this->_flatten($access2); - $wanted1 = array($id1 => 'view', $id2 => 'view',); - $wanted2 = array($id1 => 'admin', $id2 => 'view', $id3 => 'view'); - - $this->assertEquals($wanted1, $access1); - $this->assertEquals($wanted2, $access2); - - $access1 = $this->api->getUsersAccessFromSite($id1); - $access2 = $this->api->getUsersAccessFromSite($id2); - $access3 = $this->api->getUsersAccessFromSite($id3); - $wanted1 = array('user1' => 'view', 'user2' => 'admin',); - $wanted2 = array('user1' => 'view', 'user2' => 'view'); - $wanted3 = array('user2' => 'view'); - - $this->assertEquals($wanted1, $access1); - $this->assertEquals($wanted2, $access2); - $this->assertEquals($wanted3, $access3); - - $access1 = $this->api->getUsersSitesFromAccess('view'); - $access2 = $this->api->getUsersSitesFromAccess('admin'); - $wanted1 = array('user1' => array($id1, $id2), 'user2' => array($id2, $id3)); - $wanted2 = array('user2' => array($id1)); - - $this->assertEquals($wanted1, $access1); - $this->assertEquals($wanted2, $access2); - - // Test getUsersWithSiteAccess - $users = $this->api->getUsersWithSiteAccess($id1, $access = 'view'); - $this->assertEquals(1, count($users)); - $this->assertEquals('user1', $users[0]['login']); - $users = $this->api->getUsersWithSiteAccess($id2, $access = 'view'); - $this->assertEquals(2, count($users)); - $users = $this->api->getUsersWithSiteAccess($id1, $access = 'admin'); - $this->assertEquals(1, count($users)); - $this->assertEquals('user2', $users[0]['login']); - $users = $this->api->getUsersWithSiteAccess($id3, $access = 'admin'); - $this->assertEquals(0, count($users)); - } - - /** - * we set access for one user for one site several times and check that it is updated - */ - public function testSetUserAccessMultipleCallOverwriteSingleUserOneSite() - { - $this->api->addUser("user1", "geqgegagae", "tegst@tesgt.com", "alias"); - - list($id1, $id2) = $this->addSites(2); - - $this->api->setUserAccess("user1", "view", array($id1, $id2)); - $this->api->setUserAccess("user1", "admin", array($id1)); - - $access1 = $this->api->getSitesAccessFromUser("user1"); - $access1 = $this->_flatten($access1); - $wanted1 = array($id1 => 'admin', $id2 => 'view',); - - $this->assertEquals($wanted1, $access1); - } - - /** - * @expectedException \Exception - * @expectedExceptionMessage checkUserHasSuperUserAccess Fake exception - */ - public function testSetSuperUserAccess_ShouldFail_IfUserHasNotSuperUserPermission() - { - FakeAccess::setSuperUserAccess(false); - $this->api->setSuperUserAccess('nologin', false); - } - - /** - * @expectedException \Exception - * @expectedExceptionMessage UsersManager_ExceptionUserDoesNotExist - */ - public function testSetSuperUserAccess_ShouldFail_IfUserWithGivenLoginDoesNotExist() - { - $this->api->setSuperUserAccess('nologin', false); - } - - /** - * @expectedException \Exception - * @expectedExceptionMessage UsersManager_ExceptionEditAnonymous - */ - public function testSetSuperUserAccess_ShouldFail_IfUserIsAnonymous() - { - $this->api->setSuperUserAccess('anonymous', true); - } - - /** - * @expectedException \Exception - * @expectedExceptionMessage UsersManager_ExceptionRemoveSuperUserAccessOnlySuperUser - */ - public function testSetSuperUserAccess_ShouldFail_IfUserIsOnlyRemainingUserWithSuperUserAccess() - { - $this->api->addUser('login1', 'password1', 'test@example.com', false); - $this->api->setSuperUserAccess('login1', true); - - $this->api->setSuperUserAccess('login1', false); - } - - public function testSetSuperUserAccess_ShouldDeleteAllExistingAccessEntries() - { - list($id1, $id2) = $this->addSites(2); - $this->api->addUser('login1', 'password1', 'test@example.com', false); - $this->api->setUserAccess('login1', 'view', array($id1)); - $this->api->setUserAccess('login1', 'admin', array($id2)); - - // verify user has access before setting Super User access - $access = $this->_flatten($this->api->getSitesAccessFromUser('login1')); - $this->assertEquals(array($id1 => 'view', $id2 => 'admin'), $access); - - $this->api->setSuperUserAccess('login1', true); - - // verify no longer any access - $this->assertEquals(array(), $this->model->getSitesAccessFromUser('login1')); - } - - public function testSetSuperUserAccess_ShouldAddAndRemoveSuperUserAccessOnlyForGivenLogin() - { - $this->api->addUser('login1', 'password1', 'test1@example.com', false); - $this->api->addUser('login2', 'password2', 'test2@example.com', false); - $this->api->addUser('login3', 'password3', 'test3@example.com', false); - - $this->api->setSuperUserAccess('login2', true); - - // test add Super User access - $users = $this->api->getUsers(); - - $this->assertEquals(0, $users[0]['superuser_access']); - $this->assertEquals(1, $users[1]['superuser_access']); - $this->assertEquals('login2', $users[1]['login']); - $this->assertEquals(0, $users[2]['superuser_access']); - - // should also accept string '1' to add Super User access - $this->api->setSuperUserAccess('login1', '1'); - // test remove Super User access - $this->api->setSuperUserAccess('login2', false); - - $users = $this->api->getUsers(); - $this->assertEquals(1, $users[0]['superuser_access']); - $this->assertEquals('login1', $users[0]['login']); - $this->assertEquals(0, $users[1]['superuser_access']); - $this->assertEquals(0, $users[2]['superuser_access']); - - $this->api->setSuperUserAccess('login3', true); - // should also accept string '0' to remove Super User access - $this->api->setSuperUserAccess('login1', '0'); - - $users = $this->api->getUsers(); - $this->assertEquals(0, $users[0]['superuser_access']); - $this->assertEquals(0, $users[1]['superuser_access']); - $this->assertEquals('login3', $users[2]['login']); - $this->assertEquals(1, $users[2]['superuser_access']); - } - - /** - * @expectedException \Exception - * @expectedExceptionMessage UsersManager_ExceptionUserDoesNotExist - */ - public function testGetSitesAccessFromUserWrongUser() - { - $this->api->getSitesAccessFromUser("user1"); - } - - /** - * @expectedException \Exception - */ - public function testGetUsersAccessFromSiteWrongIdSite() - { - $this->api->getUsersAccessFromSite(1); - } - - /** - * @expectedException \Exception - * @expectedExceptionMessage UsersManager_ExceptionAccessValues - */ - public function testGetUsersSitesFromAccessWrongSite() - { - $this->api->getUsersSitesFromAccess('unknown'); - } - - /** - * @expectedException \Exception - * @expectedExceptionMessage UsersManager_ExceptionUserDoesNotExist - */ - public function testUpdateUserNonExistingLogin() - { - $this->api->updateUser("lolgin", "password"); - } - - /** - * no email no alias => keep old ones - */ - public function testUpdateUserNoEmailNoAlias() - { - $login = "login"; - $user = array('login' => $login, - 'password' => "geqgeagae", - 'email' => "test@test.com", - 'alias' => "alias"); - - $this->api->addUser($user['login'], $user['password'], $user['email'], $user['alias']); - $this->api->updateUser($login, "passowordOK"); - - $this->_checkUserHasNotChanged($user, "passowordOK"); - } - - /** - * no email => keep old ones - */ - public function testUpdateUserNoEmail() - { - $login = "login"; - $user = array('login' => $login, - 'password' => "geqgeagae", - 'email' => "test@test.com", - 'alias' => "alias"); - - $this->api->addUser($user['login'], $user['password'], $user['email'], $user['alias']); - $this->api->updateUser($login, "passowordOK", null, "newalias"); - - $this->_checkUserHasNotChanged($user, "passowordOK", null, "newalias"); - } - - /** - * no alias => keep old ones - */ - public function testUpdateUserNoAlias() - { - $login = "login"; - $user = array('login' => $login, - 'password' => "geqgeagae", - 'email' => "test@test.com", - 'alias' => "alias"); - - $this->api->addUser($user['login'], $user['password'], $user['email'], $user['alias']); - $this->api->updateUser($login, "passowordOK", "email@geaga.com"); - - $this->_checkUserHasNotChanged($user, "passowordOK", "email@geaga.com"); - } - - /** - * check to modify as the user - * @expectedException \Exception - * @expectedExceptionMessage UsersManager_ExceptionLoginExists - */ - public function testAddUserIAmTheUser() - { - FakeAccess::$identity = 'login'; - $this->testUpdateUserNoEmailNoAlias(); - } - - /** - * check to modify as being another user => exception - * - * @expectedException \Exception - */ - public function testUpdateUserIAmNotTheUser() - { - FakeAccess::$identity = 'login2'; - FakeAccess::$superUser = false; - $this->testUpdateUserNoEmailNoAlias(); - } - - /** - * normal case, reused in other tests - */ - public function testUpdateUser() - { - $login = "login"; - $user = array('login' => $login, - 'password' => "geqgeagae", - 'email' => "test@test.com", - 'alias' => "alias"); - - $this->api->addUser($user['login'], $user['password'], $user['email'], $user['alias']); - $this->api->updateUser($login, "passowordOK", "email@geaga.com", "NEW ALIAS"); - - $this->_checkUserHasNotChanged($user, "passowordOK", "email@geaga.com", "NEW ALIAS"); - } - - /** - * @expectedException \Exception - */ - public function testGetUserByEmailInvalidMail() - { - $this->api->getUserByEmail('email@test.com'); - } - - public function testGetUserByEmail() - { - $user = array('login' => "login", - 'password' => "geqgeagae", - 'email' => "test@test.com", - 'alias' => "alias"); - - $this->api->addUser($user['login'], $user['password'], $user['email'], $user['alias']); - - $userByMail = $this->api->getUserByEmail($user['email']); - - $this->assertEquals($user['login'], $userByMail['login']); - $this->assertEquals($user['email'], $userByMail['email']); - $this->assertEquals($user['alias'], $userByMail['alias']); - } - - public function testGetUserPreferenceDefault() - { - $this->addSites(1); - $defaultReportPref = API::PREFERENCE_DEFAULT_REPORT; - $defaultReportDatePref = API::PREFERENCE_DEFAULT_REPORT_DATE; - - $this->assertEquals(1, $this->api->getUserPreference('someUser', $defaultReportPref)); - $this->assertEquals('yesterday', $this->api->getUserPreference('someUser', $defaultReportDatePref)); - } - - private function addSites($numberOfSites) - { - $idSites = array(); - - for ($index = 0; $index < $numberOfSites; $index++) { - $name = "test" . ($index + 1); - $idSites[] = APISitesManager::getInstance()->addSite($name, array("http://piwik.net", "http://piwik.com/test/")); - } - - return $idSites; - } -} -- cgit v1.2.3